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 |
---|---|---|---|---|---|---|---|---|
143 | today i'm gonna show you how to solve legal question 143 reorder list it's another linked list issue you are giving the head of our singly linked list basically like one two three four the list can be represented like this we order this list to l0 ln basically the first one is the first value and the second one is the last value and then the third one is the second one from the beginning and then the back basically you're gonna make the list look like one and then take four and then two and then three so the second example that they give is one and then the second value will be the last value which is five and then the next value will be the second from the beginning of the list basically which is 2 and then the next value will be 4 which is the second value from the end of the list and then the add the last value so the return output will be 15243 there's constraints here and node value the question was asked by amazon adobe all these companies in the past six months so it sounds like a quite complex issue but if you think about it using divide and conquer it's not as difficult as you would expect it to be it's a medium problem and you can see that what basically it's trying to do is first it needs to divide this list into half right and then the second step once you divide this list into the half what you would need to do is the second value is started taking is from the end of the second half and then going backwards so that's why the second value is four and then it goes to three right so then you can think about it the next step will be reverse the second half of the list right and then once you do that and then the last one will be merge the to list basically you want to the last step you wanted to do is merge the first half and the second half and once you understand the concept the code is actually quite straightforward so i'm gonna show you how to code this question so the first step we wanna divide this list into half and this is a super classic linked list question and you should be able to code this even with your eyes closed so how you do this is that you want to have a slow and a faster pointer and put both of them on hat and while fast and fast on next you want to be able to move faster that's why you want to make sure fast or next is not no while this is true then you want to make sure slow moves one basically slow equals to slow to next and then fast equals to fast down next dot next basically slow move one fast move two you don't need to return anything while fast is at the end of the list slow is in the middle for an even list like this if you put your hat in or if you put the fast on the head position for an even list like this the slow will be at three instead of two this is what you need to know so we already divided list into half first linked list is one two and the second linked list is three to four so then the second step what we would do is we will reverse the second half of the list how do we reverse the second half of the list this is also a very classic problem so i'm gonna do this uh iterate uh i'm just gonna iterate through the second half of the list and i'm gonna give a pre-value and give a i'm gonna give a pre-value and give a i'm gonna give a pre-value and give a current pointer and the proof should be at no position imagine the 3 is pointing to a no before that and then the current is pointing to the slow which is the hat which is the head of the second half of the list and then while current you want to go through the list and swap every single value so i'm going to save a pointer as current.next to the temp value and then current.next to the temp value and then current.next to the temp value and then this is pretty standard the current.nx this is pretty standard the current.nx this is pretty standard the current.nx equals to brief basically reversed the link to make the three point to the previous value and then the proof needs to move to current and then current will have to equal to the temp that we previously saved by doing this you already reversed the list and the hack head of the second list will be at the brief position and that the proof is pointing to four right now so once you reverse the second half what you need to do as the last step you just merge these two lists so you have a first the list and the second list right and then the first list is pointing to the head right and then the second list that you already reversed it and the head is pointing to the pre position which is at 4 here so you want to make sure second dot next does not equal to zero when you merge this list and then you can see first dot next and our first value first dot next basically which is one is pointing to four is uh second in this case right so first on x equals to second and then you wanna move the pointer first move to first the dot next and then the next step you want to do is second dot next and the second and then after you put four here the second dot next you want to make sure it's pointing back to first which is two right so you want to make sure second dot next pointing to first and second pointing to second.next basically second pointing to second.next basically second pointing to second.next basically move the pointer by doing this do not return anything modify had in place instead by doing this you already successfully merged and reorganized this list let's submit the result here and we can see it went through if you like the video please give it a thumbs up and subscribe to my channel and i'll have more legal video come up for you soon thank you bye | Reorder List | reorder-list | You are given the head of a singly linked-list. The list can be represented as:
L0 -> L1 -> ... -> Ln - 1 -> Ln
_Reorder the list to be on the following form:_
L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ...
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[1,4,2,3\]
**Example 2:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,5,2,4,3\]
**Constraints:**
* The number of nodes in the list is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 1000` | null | Linked List,Two Pointers,Stack,Recursion | Medium | 2216 |
1,647 | hi there this side viewing so welcome again we are solving one more question and this is questions from lead code daily practice question and the question name is uh minimum deletion to make the character frequency unique so the question name is already uh explaining what we are going to do we have to just uh unique we have to make all the frequency unique from the string of character let me go through the question statement so it will give a clear idea what i am going to say so here it is given like a string is good if there are no two different character in s have the same frequency what just frequency refer here let me clarify that once what this frequency means so as i say so for example if the string is like a b c a b like this if the string is this then every particular like for example say a is having two frequencies because it came two time in whole sequence so is having two frequency b is also having two frequency because it is also coming to game two time in the whole line like if you notice that here it's b and here also so it's having two frequency same as c is having one frequency because it's game one time so what is our goal we have to make all unique and we by deleting minimum number of character it's having frequency one so let me go through the statement again so here it is given that given a string as return the minimum number of character you need to delete to make s as good so here in this example uh this is s for let's say this is s is equal to a so a b c a b right is having two b is having two c is having one frequency it's not good because these two character matches have having the same frequency they match that frequency so anyhow we need to make it as good and we have to remove minimum so what we can do we just remove one b right minus one b minus one here so now what is the final frequency count we have now let me write here oh it's not good color let me write here like a is having two frequencies okay b is also having one frequency now and if you notice that c is also having one still it's not good so anyhow we need to remove one more character from this two so we are removing let's say c or b we can remove any one so minus one here right so now what is the final count now the final count is a is having two b is having one and c is having zero frequency so c is not there in the whole sequence so basically we removed two things one b and one's this is the this is what the minimization we can do we can't uh minimize like one is minimum then two but uh if we remove one character then we can't achieve this uh this output like all is having unique you can see that two one and one nothing is repeated here so yeah this is what a question want to say let me go through this test cases a b so here we have s is equal to a b right a b so it's already good sequence so we don't need to remove any character for example let's say frequency of a is 2 right frequency of b is 1 both are unique it's not same frequency so answer is 0 in this case we can't remove anything so let me take through the logic what we are trying to build right now so let me take this sequence three times a three time b and two times c right three time a three time b and 2 times c right 2 times c we have so this is our s here so there is map we are using map here because i already discussed in my last video like map is very useful for counting frequency so let me recall that what is the map is nothing map is just a collection of keys and value so here character is our key and its frequency is value for us so in simply we declare one map for example let's say we declare this empty map right now in this map we're storing that a is having three frequency like this a is having three frequency p is also having three frequency and c is also having two frequency okay we done our half task map is very helpful for this uh this type of frequency count things so we just uh count all this thing like the frequent character and its frequency here we did okay so now we check that now we try to uh this grab this type this frequency in separate things like for example let's say declare one empty vector say initially it's having maximum size let's say infinite it infinites long big so we just take 10 to the power 5 as empty vector initially all are having zeros in it right it's all having zero and till and we initialize it's zero now we just store the uh this frequency count at the place of three like for example say vector of three is there any element having uh frequency three so we check vector of 3 is already 0 here if it's 0 it's mean not a character which is behind this a no one is there so it's a first character so vector of 3 is 0 yes this condition is fulfilled so it means that we don't have anything having three frequency right now at first position is only having three frequency and it's not matching frequency with other character so we simply erase this zero and you simply update it to one right we update it to one here okay done now we move ahead to b now we check for b and what is what we have now you do the same task for b we just check vector what is the frequency of b 3 so we check back v of 3 is it 0 or 1 so it's not 0 right it's not 0 so it means that it match with someone's frequency so we just need to check its back we just remove 1b so now the count of b is two here minus one so count of b is two right so we check vector of two it means that is there any character having frequency two so we check and it's 0 here it's 1 here it's 2 here i just i'm just writing index here so vector of 2 is 0 it means that no character having frequency 2 so we just simply update the value of v of 2 here with 1 let me erase this 0 okay so here i just put one okay so here we remove one correct in one answer in answer variable we are just uh storing the removal of character so right now we remove one car one b one let me write in bracket that is b okay now we move to c for c again we check v of frequency of c so v of frequency of c is 2 right so we check v of 2 is 0 so v of 2 is 0 let me check v of 2 is 1 so it's not 0 right it's not 0 so what we can do we just remove 1 c so let's see because frequency of c is 1 now we check v of one is zero we remove one character so we need to add an answer variable that plus one c okay plus one see i add here so now we check v of frequency of c so is there any character having frequency one previously we check if it's zero then no character match with frequency of c and yes it is zero if you cannot see it is zero right so yeah we're done and we and no character left here so our answer is 1 plus 1 2 in this case so yeah our answer is 2 so this is the basic logic uh it's messier it i hope you got understand the logic what we are trying to build let me take one more small example so you get a clear idea what we are trying to do here let me take uh easy example like for example say is having two frequency b is having three frequency and c is having one frequency so in this case we are not having we don't need to do anything because a is having two frequency right now it's unique b is also having three frequency it's also unique right c is also having one frequency so all are unique so we don't need to remove any character simply print answer is equal to zero answer its answer is equal to zero right in this case so let me try to jump to the coding part so you might get clear idea what we are trying to do here so firstly let me declare map because we count character and its frequency so i write character for in first place it's for example this is a map this is whole it's map right this is a map look like and first character in first place we in key we are simply i can say in key we are storing character in its value is integer type so i'm just declaring that character map having character an integer name is m and i simply traverse through this string and i just i'm just counting its frequency right so m of s of i plus okay so now from this stage i am having frequency for example let's say s is equal let me take s is equal to this one uh yeah we discussed this now okay let me take this only and we dry run while writing the code so s is equal to this right and in map what we get here in map we get like a comma 3 next element we get b comma 3 and third element in map we get c comma two so this is what we have right now simply we go through the map every element like in first element in second element using iterator because we traverse in map using iterator only so auto let me say x has let me say i has iterator or m now we have access to first element right now what we are checking if we are at first element so what we are checking uh frequency of that uh character in vector if it's zero so it's well and good we just move ahead if it's not zero so we need to decrease our answer and check previously views like that so let's code that part so for that we need to declare one empty way vector let me see it's in here and let me take one big size one zero it's enough for this question because ten to the power pi is the maximum range if you can notice here 10 to the power 5 is the maximum range so it's can't exit this limit so yeah so what we are doing we just check v of i dot second because in second as you can see here in second in every element of map we are storing the frequency in integers i dot second if it's zero so we simply mark it one because no element matching its frequency so i dot second is it is equal to one so it's good yeah else what we are doing else it means that in vector for example let's say vector here in fact let me declare one small vector and let's say it's zero here it's one near it's one here and zero and let me write it index one two three four and five right so now let's say while so here we have so it's count uh it's mark as one it's mean that previous character having the same frequency as this character for example we are checking this b it means that previously there is lots of element here it's having someone having the same count as b so we just minus 1 and checking until we reach 0 it means we need we reach a unique character frequency count where the no one having the same frequency so for that's why we are running while loop here while we check that v of i dot second is one it means it's one we can write here one by defaults take one so until we reach to the zero when we have to stop that's why we are using while until it's one we have to run this loop so that time we just need what we are doing we just increment one frequency i mean seven character and in answer variable let me declare one answer variable also here where we are storing in answer variable we just increment the count of that removal of character right and if we reach for example if we reach that i dot second is equal to 0 then we need to break because we have 5 elements so we need we have like for example c is having 5 elements so we maximum to maximum remaining 5 from c and c is not no longer exist in map so that's why we need to include this and if simply right here i thought second is greater than equal to zero and so simply mark it out to one this one and coming out this following we have all the counts of removal of element in our answer variable and we simply run it out let's run the code and it's got giving correct out let me submit out the code and it got accepted so thank you for watching if you guys have any doubt related to this question you can simply comment down in comment box or you can reach to my telegram channel we can discuss that thanks for watching | Minimum Deletions to Make Character Frequencies Unique | can-convert-string-in-k-moves | A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`.
**Example 1:**
**Input:** s = "aab "
**Output:** 0
**Explanation:** `s` is already good.
**Example 2:**
**Input:** s = "aaabbbcc "
**Output:** 2
**Explanation:** You can delete two 'b's resulting in the good string "aaabcc ".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ".
**Example 3:**
**Input:** s = "ceabaacb "
**Output:** 2
**Explanation:** You can delete both 'c's resulting in the good string "eabaab ".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
**Constraints:**
* `1 <= s.length <= 105`
* `s` contains only lowercase English letters. | Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26. | Hash Table,String | Medium | null |
838 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem push dominoes there are n dominoes in a line and they're placed vertically but some of them could be either leaning to the left or leaning to the right and after each second passes each domino that is you know leaning i say the word leaning but they say falling to the left pushes the adjacent domino that's to the left of it and the same thing with dominoes that are leaning towards the right if there were two adjacent dominoes like this and this right like how this one is leaning to the right this one is leaning to the left uh you know if they were leaning like this then they would get stuck right one isn't going to fall over because they're both kind of pushing against each other if there was a domino in the middle between these they would be leaning against the one in the middle and then the one in the middle uh would stay standing up so basically there are three states that a domino can be in it can either be standing straight up which is the simple case right and that is represented by a dot and then left is meaning that the domino was pushed to the left so this domino is pushed to the left now a domino that's pushed to the left could you know be falling it could be stuck like this one over here right this one is stuck leaning in the left position or it could be like this one which is leaning to the left and then maybe it actually just completely falls over to the left side that is also considered a status of l like that state is included in this so if it fell over to the left or it's just leaning to the left it's still represented by a l and that's actually a very important point that we're going to use in this problem because it basically tells us that if a domino was initially leaning to the left its state is always going to be left because it's either going to get stuck in this position or it's going to completely fall over in both cases it's still left similarly with dominoes that are leaning to the right if it's leaning to the right or if it falls over it's still considered r okay but enough abstractions let's get into an example actually before we do that remember what we're trying to do is uh get the final state of the dominoes i didn't mention that yet but that's pretty much what we're trying to do each second that passes a domino could potentially you know get stuck like these ones or if there was you know this dominoes leaning to the right and this domino maybe this domino will push this one over but let's take a look at an example okay so now let's take a look at a couple examples the first one is pretty simple so let's just start with it so we have r dot l so that means this domino is leaning to the right this is straight up this one is leaning to the left so after each second passes each domino is going to tip over well after one second what's going to happen well not much is going to happen with these three dominoes you can see they're both going to push up against this one at the same time so pretty much they're going to get stuck like this right these three dominoes are going to get stuck this one's not going to move it's going to stay standing straight up but this one is just going to fall over i guess i don't know if it's going to push against this one because this one should push up against this one but they're both already falling to the right so it doesn't really change anything i mean maybe this one will completely fall over but the state is not going to change and that's the important part the state here is still r dot l so nothing really changed but the second example is a bit more interesting so the question is how to even approach this problem in a systematic way well one thing i mentioned first was pretty important anything that starts out as left or right is always going to stay in that state so we're trying to look for the return state that we're going to you know return the dominoes in well we know that these ones that i've highlighted are not going to change at all what we have to figure out is what about the remaining ones how are they going to change and how can we do that well there's actually multiple solutions to this problem and you can check out some of them officially on leak code if you want one that they didn't mention though i think is the simplest it's actually pretty much the brute force not really brute force but it's actually more of a simulation right because this is the state that we're given right these are the dominoes that are leaning and so of course the ones that are standing straight up they're not going to knock each other over only these dominoes that are left or right could knock other dominoes over so these are the ones we should pay attention to and by simulation what i mean is we should check on the first go-around we should check on the first go-around we should check on the first go-around basically simulating a second right one second what's going to happen after one second to our dominoes to figure that out we should probably look at these dominoes that are leaning over right now and maybe these dominoes are going to knock other ones over maybe this domino is going to change to being right then on the second we should look at what that domino is going to do now so basically with each second we're going to have a queue of dominoes that we're going to look at right now our queue is this these ones that i've highlighted these are the ones we have to look at and see how they're going to affect the dominoes that they are adjacent to so i'm not going to draw out the entire thing in the interest of time but we will code up the official solution but what we're going to say now is that these ones left right and all these have been added to a queue right and we're now we're going to process them in our queue we're just going to do this from left to right because it's simple we could do right to left if we wanted as well but it is going to be important for us to do them in order we should either do left to right or right to left and you'll see why in a second but now let's start at the left one okay this one is leaning to the left it's going to fall over to the left the first thing we should ask ourselves is there anything to the left of it yes there is that domino standing straight up yes it is so what's going to happen now well this domino is going to knock over this domino yeah so what we should do now let's say this has been popped from our queue so we don't have to look at it again and it'll obviously never knock over any different dominoes but this one over here now is going to be a left domino but the question you might be wondering is if a domino is falling over to the left right this one left what if there was another domino to the right that was falling over there so in that case this one in the middle would not be changed to a left domino it would actually stay the exact same well that's why the order comes into play we know that since this is the first domino that there weren't any dominoes to the left of it that could have knocked it over to the right and we know that because we started all the way at the left but if we do get any dominoes that are leaning to the right we don't know for sure that there aren't uh that there isn't a left domino to the right of it that could make the one in the middle stand straight up and that's the example that we're actually faced with next now we have a right domino and so it's leaning to the right what is to the right of it a domino's standing straight up so of course this one should be changed to right but before we confirm that it should be changed or right we should look at the domino actually one space over and confirm that this is not a left domino in this case it's not a left domino so we were correct this domino in the middle is going to be to the right but if there was a left domino over here then we would not have changed this one in the middle but for now let's cross this out and then let's go to the next domino in our queue which is going to be this one that is leaning to the left and we look at the value to the left of it's a domino standing straight up so it's going to be changed to a left domino again we didn't have to check the value to the left of it to check that it was a right domino because we only have to do that with right dominoes anyway and that will probably make a bit more sense when we actually get into the code because it's kind of hard to kind of explain in words exactly what i mean but basically what i'm saying is if there was a right domino over here then we would have detected okay there's a left domino over here and then we would have said okay then the one in the middle is standing straight up so then on the next iteration when we pop from our queue we'd actually just skip this domino because we already know that these two dominoes counteracted each other and then we'd go to the next domino but that wasn't the case so we don't have to do that but that's why anytime we have a left domino we don't actually have to check what came before it okay now to this domino oh by the way we're done with this one so let's cross it out now to this right domino uh let's kind of fast forward okay there's uh sanding straight up domino what about what comes after it is there a left dominant here nope so in that case uh this dominant is actually going to be changed to a right domino because this one tipped this one over uh and then we're done with this one and then we get to our last domino over here and this domino knocks over the one that's to the left of it so that one becomes a left domino and then we're done with that now notice how all of that happened within one second that was our first iteration through our queue and in one second we updated the state of all the dominoes but remember we're not looking for one second we're looking for the final state of the dominoes how do we even know if we reach the final state well basically after our q is empty because right now we have a bunch of new dominoes that were just tipped over either these dominoes are going to be standing you know going to basically be caught together basically stuck or they have been knocked over to being flat but basically to figure that out we will have to continue through this queue okay first domino over here it's leaning to the left there's nothing to the left of it though so i guess this domino didn't really do anything obviously it's state didn't change it's still a left domino but we don't have to look at it in our queue anymore okay next domino is a right domino okay so we look at what's to the right of it's a domino standing straight up but now is there another domino that's leaning to the left the reason we're checking that is because in this case that would mean that two dominoes are causing the one in the middle to be stuck and that's exactly the case here so in this case this right domino over here is not going to knock this one over because there's a left domino over here so it's going to be standing straight up so in this case we do pop this from our queue but this one does not change and since we already saw that this one this domino is leaning to the left and it's causing this one to be stuck we don't even have to look at this one we actually skip this domino so we pop this one even though we didn't do anything with it because we know that these two caused each other to be stuck you'll have to pay attention to how i handle this in the code it's actually pretty simple in the code but it's kind of hard to understand the intuition of why we're doing this okay next we have a right domino so we look at the one that comes after it's not a domino that's standing straight up it's a left domino so we don't do anything so what we would say with this right dominoes okay it's not a we can't knock it over so we don't do anything so we just pop this from our queue then we check this left domino is this standing straight up nope the one that came before is not standing straight up so we can't do anything either in this case right so we don't do anything with either of these now in the context of this problem that means that two dominoes were standing straight up and they were just kind of counteracting each other well not straight up but they were just leaning against each other right okay but now you can see that we have no more dominoes that are leaning over i really hope i did this correctly so correct me if i'm wrong but i think this is kind of what our state would be ll you know a bunch of characters and i think that does match pretty much exactly with what they had in the output so i think we're good to go by the way this uh the time complexity of the solution is going to be big o of n because in the worst case every single domino could be added to the queue and then popped from the queue so basically big o of n time complexity and also big o of n memory complexity because our q is going to potentially contain every single domino that was given to us in the input believe it or not this is actually the simplest solution in my opinion it's the most intuitive there's actually a few more complicated solutions but they're also just as efficient as this one so i think this one is the preferred solution in my opinion so now let's code it up okay so now let's cut it up first thing you're going to notice is the dominoes are actually given to us in a string it would probably be helpful for us to convert that into a list the main reasoning is because as we're going to be updating the dominoes you can't really update a character in a string in python so if we convert it to a list we can update the character at any index of that list also don't forget we're going to be using a q so let's do that in python a double ended queue you can do like that and then the way we want to initialize our q is basically uh first of all i'm going gonna enumerate through all the dominoes so our list of dominoes we're gonna get the index and the domino that's what we're doing in python here is the index d is the domino we want to add all the dominoes that are not standing straight up to our cue initially right just like we did in the drawing we want to queue.append each domino if it's not queue.append each domino if it's not queue.append each domino if it's not standing straight up and actually uh we're going to be adding a pair of values to our queue so we're going to actually include the index because you're going to see that the index is actually going to come in handy because you know after we pop a domino from our queue we want to know the index of it so that we can check the neighbors of that domino okay now the code is going to be pretty much similar to any uh q problems where you continue the loop until your cue is completely empty and each iteration of the loop we just pop the element from the queue in this case we're going to pop the leftmost but from that we're going to get an index and a domino so there's two cases remember the domino could be a left domino or it could be a right domino we know it's not going to be standing straight up because if it was then we wouldn't have even added it to our cue so if it's left or right we know that the simple case the more simple case is the left one because in that case all we really have to do is check that its left neighbor is standing straight up because that means we just tipped our left neighbor over how do we know that our left neighbor exists and is standing straight up well first of all i has to be greater than zero because if it's zero that means we don't have any left neighbors so if i is greater than zero and if the left neighbor which we can get from dom index i minus 1. you can see that the index is helpful here if i minus 1 is equal to a dot that means our left neighbor is standing straight up what does that mean well we're going to first of all add our left neighbor to the queue its index is i minus one and its value is now going to be left because we just tipped it over uh and don't forget to actually update it in the dominoes list itself because remember that's what we're actually going to return in the end i minus 1 is now going to be left and that's pretty much all there is for the left case the right case is a bit more complicated because as we're going to the right there could be more dominoes to the right that we haven't seen yet one thing you might notice though from this code is we have two nested if statements we could actually get rid of the second one and combine it with the first one but i think it's a little bit less intuitive if i just wrote that straight off the bat so let's do that and now the opposite case first we want to check that we do have a right neighbor how do we know if we have a right neighbor well i has to be less than the length of dominoes minus one there has to be at least one domino to the right of it and that domino has to be standing straight up so i plus one actually to make this a bit more clearer let's just say that i plus one is less than the length of domino right so that basically says that i plus 1 is a valid index so then we use that index and then check if it's standing straight up that means we could potentially knock it over but we can't knock it over if there exists an i plus 2 index basically that means there's a there's actually another domino to the right of this one that's standing straight up and that domino happens to be a domino that's leaning to the left so if that's the case which we can check pretty easily like this uh that means we can't knock this domino over that means this domino is stuck but what should we do now well we should pop from the queue one more time the reason we're doing this is if we don't pop this domino right here that's leaning to the left that means on the next iteration of the loop we're going to visit that domino again and then our code is going to run and then this first if statement is gonna run and what's gonna happen is this left domino is gonna knock over this one even though it shouldn't because this one is in between two dominoes a right domino and a left domino so this one should not be knocked over that's why we're popping this left domino to make sure that doesn't happen so we're basically skipping this domino but that's only if that left domino exists to the right of this one if that's not the case though then it's the slightly more simple case where we just do the generic thing basically tip this domino over and then append it to the queue just like we kind of did up above so i'm actually just going to copy and paste these two lines copy paste and then say okay domino in this case not i minus one but i plus one is going to be set to a right domino because it just got knocked over uh and also we append it to the queue i plus one and it's a right domino not a left domino okay and believe it or not that's the entire code i know it kind of | Push Dominoes | design-linked-list | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
You are given a string `dominoes` representing the initial state where:
* `dominoes[i] = 'L'`, if the `ith` domino has been pushed to the left,
* `dominoes[i] = 'R'`, if the `ith` domino has been pushed to the right, and
* `dominoes[i] = '.'`, if the `ith` domino has not been pushed.
Return _a string representing the final state_.
**Example 1:**
**Input:** dominoes = "RR.L "
**Output:** "RR.L "
**Explanation:** The first domino expends no additional force on the second domino.
**Example 2:**
**Input:** dominoes = ".L.R...LR..L.. "
**Output:** "LL.RR.LLRRLL.. "
**Constraints:**
* `n == dominoes.length`
* `1 <= n <= 105`
* `dominoes[i]` is either `'L'`, `'R'`, or `'.'`. | null | Linked List,Design | Medium | 1337 |
948 | welcome to october's leco challenge today's problem is bag of tokens you have an initial power p an initial score of zero and a bag of tokens where tokens i is the value of the i token so we have these tokens and they have some sort of value now our goal is to maximize our total score by potentially playing each token in one of two ways if your current power that we have is at least the value of token's i you may play that token so i guess pop it off or use it somehow and you would lose that amount of token value from your power but you would gain one score now if your current score is at least one but i suppose if you can't play any tokens then you may play the token um gaining that token's power into your power source but losing one score now the goal is to maximize our score right so you'd only do that if you don't have any other option so you can play any token at most once and in any order so that's kind of big there if we had this example if we had power 150 100 200 then we would obviously we only have one option to eat this token we would lose so we only have 50 power left and that would be it we can only eat that token we couldn't gain this power if we wanted having us 250 but then there's no other tokens to play so our output will be zero here what we would do is first play our 100 we'd have a power of 100 left then since we only have 100 what we would do is gain the power of 400 giving us power 500 and then eat these two tokens 2 and 3 ending up with a score of 2. so there's this temptation again to try to go recursively all right all we need to do is find every path and every possible combination that can happen but you got to resist that because the optimal algorithm is already here all we need to do is if we could use a token and gain a score do that can we would do that if we have power right and we should probably look at the smallest amount first because that's going to be the least penalty to gain that score it's only when we can't do that anymore that we would look to the maximum token that we have to lose one score but to gain that power and hopefully be able to score more points um yeah in this path so we would have to store a max score in case we go um positive and then we lose some score and we lose that value um but that makes it important since we could use this in any order to sort our tokens right so that's the very first thing we want to do let's sort our tokens in fact i'm going to actually use a queue here sorted tokens and i'm going to make this a decube okay so now that we have this q and it's all sorted we have our power and we want to store our score and i guess i can call this current think of that as current score and we'll have also the max score and we can start off with zero so while there's a q what do we want to do well if we have enough power and the power is greater or equal to the very first item on our q which is going to be the smallest we want to use it right so we want to pop that off from the left and we would have to subtract from our power whatever this t value of t is but we would increase our score by one and we would also store the max score in case we ever went lower here let's say max score was max score and max score now otherwise if we can't do this say that um we don't have enough power to pop off the smallest one we know that we want to try to gain some power right but we need to have a condition that score has to be greater than zero so that's something to keep note of and if it is then hey pop off that one on the very right and add this to our power but we have to decrease our score here but we don't need to touch our max score because that's going to be stored there now otherwise if we aren't able to do any of this we actually just need to break this loop because say that there's one left but we don't have enough power for it well we don't want to get into this infinite loop right so we have to break out somehow finally we just return that max score not the score but the max score so let's go and submit that probably should have tested it at first but i was pretty confident that would work so there you go it's accepted so there's variations of this you could use two pointers you don't have to have a queue like i did i just kind of felt like doing it and really yeah i think that's going to be an o of n solution right yep definitely all then but we do use some extra space with our cue here so i suppose having the two pointers will be less space all right so i'm gonna end it there thanks for watching my channel and remember do not trust me i know nothing | Bag of Tokens | sort-an-array | You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed).
Your goal is to maximize your total **score** by potentially playing each token in one of two ways:
* If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**.
* If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**.
Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens.
Return _the largest possible **score** you can achieve after playing any number of tokens_.
**Example 1:**
**Input:** tokens = \[100\], power = 50
**Output:** 0
**Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score.
**Example 2:**
**Input:** tokens = \[100,200\], power = 150
**Output:** 1
**Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1.
There is no need to play the 1st token since you cannot play it face up to add to your score.
**Example 3:**
**Input:** tokens = \[100,200,300,400\], power = 200
**Output:** 2
**Explanation:** Play the tokens in this order to get a score of 2:
1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1.
2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0.
3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1.
4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.
**Constraints:**
* `0 <= tokens.length <= 1000`
* `0 <= tokens[i], power < 104` | null | Array,Divide and Conquer,Sorting,Heap (Priority Queue),Merge Sort,Bucket Sort,Radix Sort,Counting Sort | Medium | null |
1,845 | Hi Everyone Welcome Back to a New Video Today Lead Code Daily Challenge Seat Reservation Manager This is a medium level question so in this question we will be assigned n seeds and two seeds will be numbered starting from one and it will continue till a Now we Will be having a seat manager class in that class we will have two functions named as reserve and un reserved This seat manager will have an object in which we will be initial English Now let's see with an example what will be happening in this question here we Will be given a number like here we have been provided with seat manager so a will be equal to 5 now we will be reserving the seat so we will have to start from one and it will go till five right now we will be Starting from the minimum value so the first reserved seat will be numbered as one now we have reserved the number with one the other number again we have been assigned as reserved so after one has already been taken so the other number which comes in the lowest value Is to so the other seat will be assigned as to now we have to un reserve the sheet so for un reserved we will be taking of the two again and adding it to the data structure which ever data structure we are using and again we see that We have reserved so since in our data structure two is the lowest value again so we will be assigning the seat number as two again now we see that we have reserved so we will be adding three here now again we have reserved so it will be assigned S for after that we see that reserve is used again so we will be adding five here now for un reserving this five will be added back to the data structure and here non null will be dead where ever we are un reserving null will be returned now If we are using any data structure to store the values from one to structure to store the values from one to structure to store the values from one to another that every time we reserve a value we remove it from the data structure and when ever we unreserve the value we do it back let's see some approach to solve the question. I will be sharing to approachable be help of with array data structure Now in this question what we will be doing using array data structure we will be using the array with one so we will have an length array that will B inila is with na now t will do when ever we are reserving the seat we will change the value from one not to zero at the lowest position so what I mean here is if we have given series of questions with we have been Inish ie with five then we're reserving again we're reserving if we have this series of measurements values like this we're calling so now we have of measurements values like this we're calling so now we have of measurements values like this we're calling so now we have five seats so from one to n we're increasing the value by one so now we have array inish Is as one right this is one index 2 3 4 and fa ok now what we are doing when we have been told that we have to reserve seat right so what we need to do is this first for one we will be turning this zero ok now For next again we see that we have reserved right so what we will be doing is we will move here and we will turn this to zero Now we have an array like this right so what we will be doing now is we are moving from one index So what What we will do is we will go back by one step and we will turn this value to one again so now we will have 0 1 and one this will show that the second seat is unreserved again the time complicated space complexity will be Of n because here we are using n error to store the values which is the size of n Now let's see the other values which is the size of n Now let's see the other values which is the size of n Now let's see the other approach to where we will be using mean heap what we will be doing here we will be storing the entire n to n values. In the heap and every time we're reserving the seat we'll be popping the value out and when we're unreserving we'll be adding the value back to the heap this will Also B Taking Time Complicated The Space The Difference Between The Array And Heap Now One We Are Reserving The Seat Then The Array Can Take Ss In Worst Case Scenario Time Complexity Of O A Of A But In The Heap It Will Be Of Lg A Now Let's See The Code So Whatever Little Doubts We Have Will Be Cleared Let's See The Code Now We'll Be Using The First Approach Now To Solve The Question Were We're Using The Array Now We'll Inilla Is The Array Let's Name That Array Sit And The Array Was ina with one thing that all the seats are unreserved now and now we will be it on the array so for I in range of all alien of seat itself don't sit now we have started it in order to see that if the value is Reserve and Unreserve at given position using one and zero so if the value at the given position is one that means seat is not reserved and we can reserve seat now so we will check if seat dot if seat if self dot seat At i is equals v so we will change that value to zero that means that seat is reserved now self dot seat at i is equals 0 and we will return from there and we will carry that index value so we have taken that index value In order to un reserve the seat we will have to change back the value from 1 to 1 right so what we will do is sell dot seat at seat number minus ev run and see the code works r not let's submit it we see That we're getting time accelerated now so let's try using heap and since it is a little optimized version so we may not face that problem again so we will import heap queue here so porting now we will ina list from And sell don't shut the list of in range not to a psw because here even if we are using a psw it will go till a only now and will prove the value Duff self don't seat now every time we are reserving a seat w We'll be popping the value out so if sell dot see then return dot sell dot and no we're reserving the value then dot we'll be adding the value back so push self dot seat number and i the Value i not existing then will be returning your minus now let's run and see the code works and not let's try to submit it now the code has been accepted so that's it for today guys thank you for watching if you like the video please share it With your friends also subscribe to the channel | Seat Reservation Manager | largest-submatrix-with-rearrangements | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. | Array,Greedy,Sorting,Matrix | Medium | 695 |
138 | Loot ke guys welcome back to my channel in this video we are going to solve copy list with random point so what is given statement year erring list of plant and is given subsidize food content additional random point meaning which put point to android hindi list and tap Constructed a copy of delete deep copy should consist of exactly a brand new not valid you must not have its value set to the value of its corresponding to include both within that and appointed of the new note suit point to new notes hindi copied list start points hindi Original list and copy list represent this cream in distant sources problem camp list of designer pendant and here cricket what to do is to construct a deep copy of the list to vote whom to speak a copy of any object in which you can change anything If you do, then the text is original and there will be no change in it. Okay, and what is given here? A Next 9 Enter given a Turangam note point, which is the random note point of Ginger, it can assign any note to the tap. Can also appoint. Okay, for example, you are seeing that the next point of the seven is guest, so their next point is blind, what does it fold, do any note, the address night of this note, what to do dumb here, random, any note here. Okay, so what to do in this problem is to create a cup play list, it will have N notes, there will be SIM values, but whatever it is, it will not be my original, okay, it will have to be copied, so how to solve this problem? What will we do, here we will take an I, okay, what I do is that the value is a tree, a torch light, so what we will do is a worm, and we will add the value of this note, and we will cut this note, and what we will do in the value, we will note down the value. We will create a new note with the same value. Okay, here in the first note, my eye is youth, so we will keep this note here that I know this is your original one and what we will do is create a note with this time value. Note create. What we will do is put it in its value, it should be complete, the copy one is fine, then we will add the additional original one to the team that I, then we will create another node of the space SIM value and put it in the value, okay, then we What will we do 1111 deposit note will be I and what will be the value same value will cut a note of eleven you want from 10th will go tan is here we will put the original here present here what will we do after that what will we do here in value one of love value We will grate the chord note, we will keep the element here, it will be the descendant of one and its a chord same way, you can not create it here, okay, what will we do after cutting this, so I know that all the next point advisor is connected with each other. But the part of the cockpit is not connected to each other, what should we do if we connect it, then it is good, it will be connected to the next point, from 3411 to 1110, 108 more points of the tank are being assigned to the seventh point at random. For is jointing the internal. Okay so we are jointing the seven current point aviral. Know a is part of the team is doing the seventh and youth is doing whom who is doing the alarm's one is doing the loot 10. Eleven is appointing Dr. Whom is One appointing? I am appointing you and Seven will be appointed. Okay, Given. Now what is the team doing in this, then point here. Okay, you are angry code. How to do this, see what we will do, before I you will create and road map, ho na Jhala benefit, this award, type your word name nodal, what should we do and we will find the current city, we will sign that the boy is satisfied. With no will have to prepare a copy unilaterally tight midminor take copy here we will new note that one of its value is in ukraine its personality or stomach and now miscurrent that chicken became vicky is this current of its value I have created a copy of the SIM value, I will put it here, I have put Night in the value, then end it and remove the paint. Next, okay, we have talked about it, we have done all this in the state map, after this we will again What will one Kannu do, this will be signed viral and container depot, what will we do after making it red, now the current of my MP is serial, its value is the current of MP, the current found will be on the wiki, its value will be on this, it will be the seventh. Next week, this is what we have to put in Velvet Thirteen's Gelu, this is what we have to put in 30min, this is the value of this, if we have to put this, then what will we do, then the additional next thing is 11:00 in connect, so in this next, this is the level- is 11:00 in connect, so in this next, this is the level- is 11:00 in connect, so in this next, this is the level- fit one. And then keep saying that we are always creating a new note. Okay, so what will it do exactly? What will it do exactly? It will assign whatever value it has. So, how do we code here the value of friend is the value of next. What will be the value of the MP I connect to? Same thing for the random cant, what will be the value of the original one of this person's arm hole, what will be his next alarm, according to Random aa ki kuch tu independent panel of his which London's closed it became that what will the national return do that the head of MP this special what will happen to me here yes this will happen and if this is this then the value will be this 72 from here If I do it, I will return it, I worship the idea, money, here I am not in the mood, I also have to do it for the canter, I also have to do it, I submit joint worked for first test case to One Step Up or network. thank you too | Copy List with Random Pointer | copy-list-with-random-pointer | A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.
Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.
For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
Return _the head of the copied linked list_.
The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
* `val`: an integer representing `Node.val`
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.
Your code will **only** be given the `head` of the original linked list.
**Example 1:**
**Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Example 2:**
**Input:** head = \[\[1,1\],\[2,1\]\]
**Output:** \[\[1,1\],\[2,1\]\]
**Example 3:**
**Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\]
**Output:** \[\[3,null\],\[3,0\],\[3,null\]\]
**Constraints:**
* `0 <= n <= 1000`
* `-104 <= Node.val <= 104`
* `Node.random` is `null` or is pointing to some node in the linked list. | Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list.
For e.g.
Old List: A --> B --> C --> D
InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers. | Hash Table,Linked List | Medium | 133,1624,1634 |
1,029 | Hello guys welcome to our interesting video in this series according to this call to cities safe during this time and let's get started 21 A company planning to interview two and people give and request and school staff is equal to two vectors sized together for its elements representing the The Cost of Flying Upstairs to Cities and the Cost of Flying You Centricity 20 Represented by the Second Element Inspector Aged Minimum Cost for Every Person Varsity Sweater Jacqueline and People Want to Right to Cities 100 Years of 21000 Don't Get and Distribute Decoration Half Minded Quantity A Fan of them into cities pet so let's get started logic use code and will move to actress recording 800 they consider this case also in this case which have people who are willing to apply to cities and cities pay that and cost flying officer to cities and its Stand In A Quarter Of Flying Intercity 200 And Considering Us Control First Time 2830 Quite Different Cities Permits For Thought Processes Respectively And Further 14% 3128 And Further 14% 3128 And Further 14% 3128 That's A 200 What Will We Have To Which We Can Opt De Boy Der City Ye And City Because In This Will not be able to get the correct answer fennel examples and thought and by the cost of light in city vs concealer bed the worst position is absolutely minimum cost applicable to city wear look and only the cost of white city also in this person definitely go to City Ye Rights And Displaced Adapter Cost For Its Plus Thirty Plus One Plus 2 And It's Going To Give S For Thirty Plus 2450 Places For 750 Challan Services Minimum Cost For All Of Them Were Not Divided While Shopping Them To Hai Idhar Road City B And City Will Have To Consider Something College Relative Cost So Let 's See What Rate Relative Cost Is Suggested 's See What Rate Relative Cost Is Suggested 's See What Rate Relative Cost Is Suggested Relative Cost Means The Profit Will Get A Young Person To City Ye Over City Also Okay So Let Me Write RCF And Relative Cost Relative Clock Of Flying On Cultural The First person to city this over city after bus what is side profit and domni battery saving mode of flying intercity adversity bhi seedhi silai to 14% city we are going to spain adversity bhi seedhi silai to 14% city we are going to spain adversity bhi seedhi silai to 14% city we are going to spain twenty rupees placid in the city have in its pancholi tent morning 127 0 flying intercity Ye Varsity Bhi Soane This Is A Relative Ko 50% And Second Soane This Is A Relative Ko 50% And Second Soane This Is A Relative Ko 50% And Second Person Similarly Flying Intercity More Than 200 Ko 67 Miles - 80 Seven Se On Zee TV More Than 200 Ko 67 Miles - 80 Seven Se On Zee TV More Than 200 Ko 67 Miles - 80 Seven Se On Zee TV Third Person Relative Ko Se Pati - Forces - Difficult To Be Quite Different Pati - Forces - Difficult To Be Quite Different Pati - Forces - Difficult To Be Quite Different City Ego Ve City Bhi Follow 4% City Ego Ve City Bhi Follow 4% City Ego Ve City Bhi Follow 4% Similar Twenty - 28 - 0 Sofia Ko * Similar Twenty - 28 - 0 Sofia Ko * Similar Twenty - 28 - 0 Sofia Ko * Have to that a you know who spend 30th deficit and sure different cities in this is relative Ko Safed City University 20 - 10th so now they can solve this Safed City University 20 - 10th so now they can solve this Safed City University 20 - 10th so now they can solve this relative cost each thing and this relative Quarter Evion Home to Flight Citizen Home to Light in City B.Com First Citizen Home to Light in City B.Com First Citizen Home to Light in City B.Com First for the Second Centricity Ye Divya Ko * for the Second Centricity Ye Divya Ko * for the Second Centricity Ye Divya Ko * Saver Mode of Money Vaikunth Se 117 10 Capsules Definitely Prime City Next Chapter 10 Verses Eliminated Vinod Now Maximum Amount of Money Can Save the Evening People is 22 language first person also to cities us gas limited to where is the god of war and remaining to guys vinod it will have to medium to cities pay member logic and can us for over to coding 800000 dam bay related to add to cart the Cost Sharif From Within That Ooo And I Will Have To Use Ka Disrespect And Functions Let Me Scheduled For Them Using Relative To Swap To Declare 200 Relative Cost Swayam Gurudev Plastic Mistake And Relative Cost Function Medical Tell Me How To Short And Moods Condom Relative Cost Sudesh Isko * Condom Relative Cost Sudesh Isko * Condom Relative Cost Sudesh Isko * Accept to vectors Sorry for example The first tractors Electronic and First and Dum now Contractor is the platters Toilet Second semester print and second show Vestige to vectors Positive Episode Number Relative cost Surya Stone Twitter To go for slow is the first tractors Related Question Hai Arvind Secret Facts Related To Swiss Roll This To Sand Art 14% City This Varsity Blues In To Sand Art 14% City This Varsity Blues In To Sand Art 14% City This Varsity Blues In The Morning How To Give Him Friends Pet 127 More Money Than Him Okay Otherwise Will Have To Send To The Second Half Inch Width Most Profitable For Some This Is It And Will Have To Go For R And What We Can Give What The Sorted Factor Know This Entry For The Director Know What We Can Do It Is Winters Hydrate Over The Course Business Difference Between Subscribe To Get Started Properly In Illegal Lottery Don't Know You Can Just Happened 108 Increase Twitter And Protest Edifice Point Is Equal To Zero Start Size Back To IA Kepler Difficult Elements Inventor Of Cost David To Sum Up And Have To Go To Cities Pain Just The First Element From The Best All The Meaning Of Elements Vinod now to two cities pain just give the point is equal to cost of science by two is equal to cash digest plus all the meaning of element have to go to city chief and own this tweet but not let someone will declare time will 720 adventures Return Dasham 388 Swapt Under Total Sampitt Sud User Protest Fully Shuv Work Pic Ek Ansh Working For The First Test Case Will Submit It Is Working For All The Testis This Swelling Accept Solution Thank You For Listening And Information Like You Like The Video Please Like And Subscribe To my channel thank you | Two City Scheduling | vertical-order-traversal-of-a-binary-tree | A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000` | null | Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Hard | null |
389 | hey everybody this is Larry this is day 25th of the weekly what month is this September daily challenge uh hit the like button hit the Subscribe button drop me on Discord let me know what you think about today's farm so I just finished oh excuse me I just finished a 48 hour fast just a quick one uh and during that I just spent like three hours in the gym and like another I don't know 20 minutes running or something so I'm very tired uh I get that a lot or I'm just like very I don't know ready to take a nap anyway so okay so let's take a look at today's Farm we'll see how that goes uh today's five is 389 find the difference we're given two string SNT T is generated by randomly permutating and we turn the letter that is added to T uh okay that's a I mean that seems pretty straightforward um yeah hmm okay I'm trying to figure out if I could go off it to me to be honest uh let's see right so maybe I could do something like calendar of s but um minus corrections.counter of T I um minus corrections.counter of T I um minus corrections.counter of T I think this gives us kind of the answer but not really in the uh in the sufficient way I'm just going to see how that returns right uh oh the other way whoops T has more than S yeah so that should be good um I'm wondering if I can do but I don't think you could do better than linear yeah because you have to kind of look at everything anyway so I think this should be good right so then we could just return this uh something like that maybe it'd be kind of you know constrained with the thing that this is one uh dictionary oh hmm I didn't know that or maybe next nope I mean yes but also another thing uh the kiss is not an elevator what is it then it's not elevator I cannot index it what are you doing all right fine uh yeah let's give it a quick submit and there you go 1273 day streak uh pretty straightforward this one um I mean obviously you could have also done in any other way I was just trying to see play around with a little bit uh this is just returning the hashtag uh the difference in lookup table is this one as well uh and uh this oh I guess last time I actually just did it the same way but and this time I just did in one lie all right uh yeah this is gonna be linear time linear uh well actually space is Alpha space Alpha being uh the size of the alphabet which is 26 because that's the size of the calendar but linear time you can really avoid it I don't think because you can always just and there's no structure if they were sorted then maybe you could do a binary search or something like this um but yeah uh yeah am I is this blocking I just realized that this may I mean it's not but it is ready to close to the top of the screen maybe I gotta be more mindful about this but uh hopefully this is I don't know I hope you enjoy me doing this forum review how about you're not too alone uh you'll never be alone when you know I'll keep doing it I have a 12 73 Day Street going down and fight and one day but not today so yeah uh that's what I have for this one let me know what you think have a great week everybody stay good stay healthy to get mental health I'll see y'all later and take care bye | 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 |
374 | hey everyone welcome back to our late code study plan let's tackle next problem 374 guess number higher or lower consider we have two players player one and player two hides a number called pick and we need to guess as a player one in certain number of attempts what the pick is in this example n is equal to 10 meaning from 1 to 10 this player 1 can kiss a certain number and as soon as this player cases 6 that would be the right answer so let's take a look how that works this player 1 will guess from 1 to 10. so in this example let's say n is equal to 10 and we can do this problem linearly meaning we can keep guessing from 1 to 10 in a linear fashion like 1 2 three until we get the pick so at some point we get this pick in this case in seventh attempt we get the pick but we know that if the elements are sorted then binary search would be the best bit so let's see how that works here instead of guessing some number randomly let's take a low point of 1 because the problem says i pick a number from 1 to n low would be 1 and high would be 10 in that case and high would be n which is 10. so what's the way to guess we need to ask player 2 if whether the number i guessed is right by calling guess of some number and now this player 2 will respond with either of one if the number we chose is higher than the pick then he says it's minus one on the other hand if we pick a lower number then the pick then he says it's one and if we guess it right he would respond with a zero so that's the idea so instead of tackling this problem linearly let's look at the binary search we guess a midpoint low plus high by 2 and that would provide 1 plus 10 by 2 which is 5 if we take the floor value so we guess the 5 and the way we guess is by calling guess of five so i'm asking is phi the number to player two and now player two will compare seven with five so he sees five is less than seven so he would respond with one saying the pick is greater than the number we chose so we get to know that 5 is less than the click so we need to update our low pointer to eliminate the numbers less than 5 so since we know 1 through 5 there is no number which matches pick so we can make our low pointer point to the sixth number so let's do that so first time the mid was here we guessed five and we got a response of one saying the peak is higher so we'll update low pointer to 6 and now we calculate the mid again 6 plus 10 by 2 which is 8 and that cross the pick so let's guess that first and he would respond with a minus 1 saying your guess is higher than the number so in that case we reduce the high pointer to point to the element less than the mid so we point to one less than the mid the high becomes seven this was ten initially now we calculate the mid six plus seven by 2 which would be 6 so we'll bring our mid here now we get 6 and player 2 responds with the 1 saying your guess is lower than the number because peak is 7 and we guessed it 6. so in that case we update the low pointer to point to the next element like this and now both high and low are equal and we recalculate the mid now that would be 7 plus 7 by 2 which is 7 so mid comes to 7 as well now we guess 7 and this 7 is equal to the pick so he responds with 0 and that would be our number so we return the mint in this case 7 that's the strategy of the game and when do we exit a while loop if high cross is low as usual so we can update our low and high pointers until low is less than or equal to high if high crosses low then it means the number doesn't exist but in this case that doesn't happen because he hides some number and by updating low and high properly we at some point reach to that proper pick so let's code this out i take a low pointer pointing to 1 and high is equal to n so until then i need to update my pointers then low less than or equal to high i can keep finding the mid and update my pointers once low and high crosses each other i stop there so mid is equal to floor value of low plus high by two now calling the api we get back one of the three responses so if guess of mid is equal to one we update our low pointer pointing to the element next to it else if case of mid is equal to minus one then the number we chose is very much high than the pick so we reduce the high pointer to mid minus 1 else finally we found the number and guess of mid will be equal to 0 so we just write else here we return the midpoint meaning we found the mid element we guessed the pick at this point and we closed the loop and we don't need any condition outside because within this the peak will be available and at some point we reach this condition and we guess the number right let's code this all the code okay so we are back on lead code let's take low is equal to 1 and high is equal to n while low less than or equal to high we find the mid math dot floor high plus low by 2 and if guess of mid is equal to 1 we update our low to mid plus 1 guess of mid is equal to minus 1 then we update the high pointer to mid minus one and doing this if and else if condition we narrow down and find the pick so at that point we return the mid and that would be our let's run the code let's accept it we'll try submitting it and it got submitted so this was the hi-lo guest game see you in the next hi-lo guest game see you in the next hi-lo guest game see you in the next video thanks for watching | Guess Number Higher or Lower | guess-number-higher-or-lower | We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible results:
* `-1`: Your guess is higher than the number I picked (i.e. `num > pick`).
* `1`: Your guess is lower than the number I picked (i.e. `num < pick`).
* `0`: your guess is equal to the number I picked (i.e. `num == pick`).
Return _the number that I picked_.
**Example 1:**
**Input:** n = 10, pick = 6
**Output:** 6
**Example 2:**
**Input:** n = 1, pick = 1
**Output:** 1
**Example 3:**
**Input:** n = 2, pick = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 231 - 1`
* `1 <= pick <= n` | null | Binary Search,Interactive | Easy | 278,375,658 |
208 | foreign level question and it's a very popular question as you can see from the likes so let's read the problem statement a try pronoun just try or a prefix tree is a tree data structure used to efficiently store and retrieve keys in a data set of strings so there are various applications of this data structure such as autocomplete and spell checker so we have to implement a try class with a constructed try with a methods insert that takes the word and inserts the word into the try there is a search method that takes the string as word and returns true if the string word is in the try or IE was inserted before and false otherwise method is starts with it takes the string as prefix and returns true if there is a previously inserted string word that has the prefix or and false otherwise let's see some properties of the try so try as stated is a rooted tree and with each node of the tree has two properties first each node has R links you can say right as R links where R is equal to 26 which represent which corresponds to the 26th character of the string data set or the string alphabets and also ah there is a is end Boolean variable associated with the node that represents whether this node represents the end of the key or not right so there are some operations that we can see first the two main operations is insert and search prefix the three main operations and these three main operations are also need some auxiliary uh operations that is put get and contains key so put is to create a link uh between the parent and the child node get is to get the link between the child and the parent node for a particular character and contains key that Returns the Boolean whether there is a link for a particular alphabet or not right so let's see if I do put CH in the dry node it will add a link for a particular character suppose a it will add the link for a particular character and it will link that node with the parent for that corresponding link right and get CH will return the link or the node try node for that particular character and contains key will return will check whether there is a try node present for that character or not see the first operation that is insert so let's insert two words that is lead and code so we'll start so these are our two keys so we'll go character by character so first we'll start with the root note so root node has 26 links right corresponding to each character so at the start there is no node for the No Child node for the character l right so we will add a link for the character L and we'll add a child node to the parent node then again we'll check the letter e so for this from this child node there is no link present for the character e so we'll add a link e and we'll add a child node from this node again we will add then for the corresponding or for the next letter e We'll add a child node and again for the next letter T we'll add a child node and we will mark this child node or the leaf node as is end equal to true so this represents that this is the last character of the key lead right now we will add code so starting with the nodes root node there is no link present for the character C so we'll add a new child node and we'll link it with the parent for the character C right now again from the C there is no link for the character o so we will add a new node and we'll link it to the parents link matching the character o right again we'll add a newly node that matches the parents link corresponding to character D and from the D as there is no link present for the character e so we'll add a node and we'll add the link corresponding the parents link matching character e right and we'll mark this node as is and equal to true that represent this is the last character of the key code in this try data sector we'll search now the word lead so we'll check from the starting from the root node is there in any link corresponding to the letter L yes there is a letter so we'll move down to the child node or the next node and then we'll search a link for the character e so there is a link for the character e so we'll move down to the next node then again in the at the next node we'll search the link for the character e so there is a node for the character e right so we'll move down to the next node we'll search for the character T the is there any link yes there is a link for the directory so we'll move down to the next node now we are we have done we have out of the keys right so we'll check whether this node is end is equal to true so yes is that equal to true so this whole word is present in the try right so it will it's present in the uh try data structure right so we'll iterate and we have to check is end equal to 2 right both now we will check for the prefix right whether so now let's suppose we uh c l e whether Le is present right we'll search Le not search prefix but we'll search Ali whether le as a word is present in this data structure or not so we'll start from the root node we'll see the link corresponding we'll check the link corresponding to the letter L so yes there is a link present from the node so we'll move down to the next node we'll search for E yes the from this node we have a link present for uh corresponding to character e so we'll move down to the next node but at this node because we are out of the characters so but at this node is end is equal to false so this means that l e is not present as a word but if we want to search le as a prefix right so if we perform search prefix Le then it will be returned true because at this node we will not check is and equal to true right so because for this at this node is end is equal to false then it means that LE is a prefix for a word already stored in the data structure that is lead right so if we want if we do Search Le then it will return false but if we do search prefix Le then it will return true depending upon this is end flag so because is end is false at this node so it means this is not a word stored in the data structure but it is a prefix let's see the Java code for it so we have created a public class try which has a inner class that is try node so each node this represents the node of the tree which with each node as R links and a Boolean variable is n that represents that this is the last character of the key and we have uh initialized links with the r sized try node array now three main auxiliary functions that is contains key which tells us that there is a link for a corresponding character ch in that node or not get method that Returns the link for that particular character CH and put that adds a link for that character CH into the node into the parent node set ends marks this marks the node as a end character for a key and is end gives us the Boolean value of whether that node is the end character of the key or not so in the Constructor we will initialized our Tri node try node and in the insert method we'll start from the root node we'll iterate each character of the word we'll check we'll first fetch the character into the curve car variable and we'll check whether there is a link present for that current character in that in the root node or not or in the current node or not if that is not present we'll add a node corresponding to that character will add a link corresponding to that character in the node and or we'll get the node that we added for that current character and will do will perform this operation till we are done with the each character of the word and finally we'll mark the last node as the end for the search and starts with will call this one main uh same function that is search prefix so what search prefix does is we'll start with from the root and we'll again iterate each character of the word we'll take each character of the word and we'll check whether the node contains a link for that character if yes will move down from that node to the child node right so we'll else will return null and if we have iterated over the complete word length we'll return the last node so in the search method we'll perform the search prefix and we'll get the last node so either it node can be null or not null so if the node is not null so it means the complete word is already inserted before in the try and if node is end is true right so for search the complete word has to be inserted the complete word has to be present so that is specified by the is end variable is end Boolean variable so if the node is not equal to null and the node dot is end is equal to true it means that the complete word is present in the try now for the starts with it means that we have to only search for the prefix so when we perform search prefix and we get the node the we only checked node not equal to null we don't check node is end because it doesn't matter whether it's the is end for that node is true or false because we only want to search as a prefix now let's run the solution so yeah test cases are accepted so means if the solution is working fine so let's see the time complexity of largely two main function that is insert for the insert we are creating the nodes which is equal to the length of the key right the length of the word so the time complexity will be go of n where n is the length of the word that we want to insert right and for the space complexity as we are maintaining uh we are creating m n nodes where n is the length of the word so the space complexity of B will be Big O of n and for the search prefix right the first prefix again the time complexity will be Big O of n because we are searching nodes where n is the length of the word so we are so we have to iterate n times so n nodes right so search for the complete word and the space complexity will be uh order for the big of one because there is no node we are creating so that's why it will be big offer so I hope you like this video If you like this video please share and subscribe thanks for watching bye | Implement Trie (Prefix Tree) | implement-trie-prefix-tree | A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
* `Trie()` Initializes the trie object.
* `void insert(String word)` Inserts the string `word` into the trie.
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
**Example 1:**
**Input**
\[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\]
\[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\]
**Output**
\[null, null, true, false, true, null, true\]
**Explanation**
Trie trie = new Trie();
trie.insert( "apple ");
trie.search( "apple "); // return True
trie.search( "app "); // return False
trie.startsWith( "app "); // return True
trie.insert( "app ");
trie.search( "app "); // return True
**Constraints:**
* `1 <= word.length, prefix.length <= 2000`
* `word` and `prefix` consist only of lowercase English letters.
* At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`. | null | Hash Table,String,Design,Trie | Medium | 211,642,648,676,1433,1949 |
153 | hey hello there uh let's talk about this liquidity challenge question find minimum in a rotated sorted array too suppose that we have an array that's sorted in the ascending order and now this array has been rotated around some pivot point that's unknown to us uh looking at the concrete example array this is the original array that's sorted in the ascending order zero one two four five six seven this array has been pivoted uh i rotated around this pivot point the position in between two and four so we're cutting the array into two halves the first half is zero one two and move that part with and so the rotated solder already become four five six seven zero one two so in terms of the ordering of the elements inside this rotated sorted array is ascending a sudden job and then going back to ascending order as well again now the question asks us to find the minimum elements inside this array and one notice that there are may potentially be duplicates inside this array this is the only thing that set this question apart from the prior question five minimum in a rotating distorted array so in that question uh there is no duplicate that the case is relatively simpler so let's talk about how we find minimum element inside any kind of array let's not assume any kind of assorted order about the array and we want to find the minimum elements we have to look at all the element at least of once and remember what is the smallest one that we see so it's going to be a linear time algorithm just pass through all the elements inside a array where we don't assume any kind of a sorted order so that's linear time if the array is perfectly sorted in this case this is the original array then the minimum number is going to be the first element inside this array so it's going to just be a constant time looking up looking after the value now this array is rotated sorted so it's not fully sorted but it's not totally unordered so this is in between unsorted and sorted so the uh algorithm that we are looking at should be have a runtime that's in between constant time and linear time so that's leave us to a logarithmic time so find a value inside array in logarithmic time it's a pretty clear we're looking at binary search so the big idea behind binary search is that we're looking at the three numbers the lower bond the upper bond and some middle median pivot number and based on those three pieces of information we want to decide which half of the problem we can safely disregard and zoom into the other half of the problem to find the answer so here we're looking at how we compare the arrays number elements indicated by those three pivots lower bound upper bound and medium points to figure out where should the minimum number reside and use that to iteratively or recursively whatever repeatedly reduce the size of problem until we find the minimum so that we can leads to logarithmic time so let's look at the let's just look at this one by one the first case is that let's just talk about this graph a little bit now assuming that we have an array and using the x-axis to indicating the using the x-axis to indicating the using the x-axis to indicating the arrays index and the y-axis to indicate arrays index and the y-axis to indicate arrays index and the y-axis to indicate the element's value so because this rotator sorted it's increasing a certain job and then going back to increasing again note that the upper bond should never be higher than the uh lifter point because if this is higher than the left point it's not really a cut off and move over that will violate the prior property of a sorted array so it has to be in this kind of shape now the first case is that when we use the three number to partition the array basically rotate the sorted into two halves by uh the lower bound upper bond and the medium pivot position in if it's the first the case here we can see that the left part the part that's between this two line here it's a strictly sorted in the ascending order and there's no way that the minimum is in this part because the job the minimum number is always the starting point after this job here so just based on the relatively relationship between this three number or this two number in particular we can identify that we want to resume continue looking into this portion this is half of the routine sorted rate to find this minimum so just in summary if we find the median value is larger than the upper bound positions value that means the right hand side partition of the rotative solid array contains the minimum and we want to basically only considering that part so we can update this by moving the median value to be actually one larger than the median because to have this sorry they are rotated to have this medium value to be strictly larger than the upper bound position value that means the job hasn't happened yet so we can safely move it to be one more than that so this is the update rule for the first case in the binary search okay let's go back to that and grab the second case and talk about that so this is the second case when we have this kind of partition with this three number partition lower bound upper bound and medium part we can see that the left hand side is a rotated sortedness array that's why the median and the minimum number has to be in that part so we can just safely disregard the upper bound part um so this condition this kind of partition is indicated by that the median value median position value is smaller strictly smaller than the upper bound value but that doesn't exclude the case where this median value is pointing at the true minimum so that we don't want to overshoot so the update rule for the upper bound in this particular case we just set it to be me medium position because that one has the potential to be the true minimum so that's the second case the very last case sorry the rare last case is the is the tie that will never happen if there is no duplicates if we find that the median value median position value and the upper bound position value has the same value that's only possible when there are duplicates and actually there are two case possible scenarios one is that the duplicates extending from some prior part in the left-hand side some prior part in the left-hand side some prior part in the left-hand side and just lift the left portion between low and median if that go extending through that then the we want to really zoom into this part the other case is the same value is extending through median towards upper bond then uh the part that we would want to zoom in is this left-hand side part to zoom in is this left-hand side part to zoom in is this left-hand side part so just based on this two uh values relationship there's no way that we can determine which part of the array we want to disregard so the only thing we can safely do is to just decrease the upper bound by one so that moves the also move the medium value towards left by a little bit and hopefully after a few updates we can as in this case we can see that it's already in the dropping part so doing a few updates we can resume this cutting half and cutting half operation like here if we drop it here then we're pretty sure that the right hand side is the part we want to keep and we can resume the binary search so yeah so just in short when there is the tie we can no longer do binary search all we can do is to do a linear update of the upper bond by decreasing that by one so that's the three cases um yeah so let's go back to the code editor and the code up the solution it's relatively simple once we can have those three scenarios in our mind the code is pretty simple so the lower bond and upper bond are the first position and the last position in the array and the termination criteria is that the two bonds haven't converged into one point so we haven't successfully identified the single minimum number inside this array we want to repeatedly finding the minimum a median position which is just this two add together and divide by two and now is the three cases we want to test whether this position is less than or what's my first case it's larger than upper bond if it's larger than the upper bond then what i would do is to reduce to increase the lower bond to be m plus one the other case is that it's strictly less than the upper bound positions value that means the median position have a potential to be the true minimum if it's not then the left partition of the array has to be rotated sorted so we want to keep searching that part the only last case is that it's a tie if it's a tie then we are not sure which part we can safely cut off so we just reduce the upper bound by uh by one in the end the two bonds low upon the upper bond will be the same value so we can either return the number at high or low they are the same position so that's the code for this problem and uh so the in the worst case when the array is just a sam number repeating itself over and over again this will converge after we decrease h from the last number towards zero so that's the only case when this will break so in that case the time complexity will be linear time because we from the right hand side and move that one at a time to be the left side so it's the worst case it's a linear so when uh when there is no duplicate and uh order of end when worst case every elements uh when we just have the same number so that's the time complexity for this problem and because it's binary search all we have is the three positions so it's a constant space problem uh for the prior question um because it's just a half it's basically just getting rid of this case so the code is just that so we have two positions two uh two branches inside this code binary search code uh for this uh 153 in the rotated sorted array in the case there's no duplicate it's guaranteed to be in log time yeah all right so that's uh that's this question and it's a prior question today binary search | Find Minimum in Rotated Sorted Array | find-minimum-in-rotated-sorted-array | Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times. | Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array. | Array,Binary Search | Medium | 33,154 |
430 | hey what's up guys babybear4812 coming at you one more time today we're doing another cool problem well i think it's cool uh i think most of them are cool not all of them but most of them uh problem 430 flatten a multi-level multi-level multi-level doubly linked list so in this problem we're given a doubly linked list which says in addition to the typical next and previous pointers it could also have a child pointer which may or may not point to a separate doubly linked list says these child lists may have one or more children of their own excuse me and so on to produce a multi-level data structure multi-level data structure multi-level data structure and we need to flatten it so what does that look like in an example uh imagine this is a standard linked list kind of from one to six but once we get to node three we kind of hop along we notice that it has a child node and in that pointer excuse me the child pointer points to another node which is node seven this one down here and that one's got a linked list in and of itself and then we've got eight so sorry if you kind of traverse through that when you get to eight you notice that one has a child with notes 11 and 12 which are their own linked list after flattening this thing although you can't really see it we get this order one two three seven eight eleven twelve nine ten four five six so what do these numbers mean to us well imagine doing this imagine taking uh so the order becomes one two three and then we jump down and it goes 7 8 11 12. and then imagine this kind of this 11 12 over here is now so we go 7 8 11 12 and now on to the end of the 12 we put on this 9 and this 10. so we'd have 1 2 3 7 8 11 12 then the 9 and the 10 go here so we have one two three seven eight eleven twelve nine ten and now this all kind of propagates upwards and so this four which got cut off originally goes out at the end of the ten so we get four five six um so we go from this pattern we kind of go one two three seven eight uh eleven sorry seven eight eleven twelve nine ten four five six all right i hope that makes sense i think it makes sense it's under like the name suggests we want to flatten it into one list we're given the node definition here where we've got the standard val pre and next properties and again we've got child which will either point to none or it will point to another node which is the kind of the starting node of another list so i'll clear that up just to give us a bit more space um that's about it that's all that there is to it so they give us a few more details here on serialization but it's nothing to write home about we're told that we won't have more than a thousand and their values will go up to ten thousand i don't think that changes much for us but regardless it's there we're actually i know it doesn't change much for us because we're going to go through it the standard way and we're going to think about how we can do this in the most efficient possible manner so what i've done is i've come up with this fine drawing right over here this is some of my best to work it really made me question why i always did so poorly in art class maybe if i drew linked lists i would have gotten a better mark nonetheless we this is a visual representation of the example we just walked through and so what i wanted to do was to kind of walk through the logic on how we can think about approaching this problem let me start off actually by saying that when i first did it the on my first time around i had this one in linear time but i did it in a two pass solution and i did this uh recursively and what i did was i said let me walk through this list and as i once i find a node that's got a child let me make a recursive call and i'll make that recursive call and say you know i'll set this child to next now and um i'm gonna walk through i'm going to keep doing this until i find the next node with the child and then i'll attach that file or sorry that node not the file and so what my list would look like was that i'd have something like 1 2 3 7 8 11 12 but then what i do is i'd go back and walk through from eight up until ten so find this ten so then i'd add the nine and the ten and then i'd start from the beginning here one two three seven eight eleven 8 9 10 and then go on to 4 5 6 meaning that if i kind of did this recursively i would have to be searching through every element twice to get to the tail of every single list in order to then connect it to the next list so walk through this whole list to connect it to here then kind of once this is all connected walk through once again to then be able to connect the tenth of the four and so if your head was going somewhere similar like in terms of recursion and doing this uh there's a better way to do i'm only sharing that because that's how i it's not a fail i think that still would have it would have passed but it was a bit more complicated than it needed to be the approach though in terms of like walking through until we actually find a node with a child that's going to hold water so what we're going to do is we're going to start walking through this thing and we're going to start at the head and really nothing interesting ever happens unless we find a child or rather a node with a child if we don't find one of those we're just going to return the head as it is so we're all good there like that's when the fun begins so let's pretend that i'm starting up a walk at node one and then i'll do something like set curry equal to head and then while curry exists we continue walking does this have a child no it doesn't nothing to write home about does this have a child no it doesn't not the right home vote does this have a child okay yes it does this thing has a this one has a child over here so what do we want to do by flattening it we are going to want to redirect kind of the direction of this next pointer and we're going to want to move it downwards meaning my child is going to now become my next it's going to almost like pivot upwards so a couple things we're going to need to do we're going to need to say let me almost take this next and i'll make the next pointer go this way now i know it kind of looks like child but bear with me um i'm going to say my child previous now wants to point this or so i'm going to connect these two like a steady relationship and then i'm going to scrap so one thing that i really messed up when i was doing this problem is i never um this took me so long to figure out but you need to also scrap the child property so once i find a child i want to say let me reroute my next and previous pointers here so that uh my child comes next in line and then i'll all drop this child on this child connection so we're kind of looking like this now um if this was my next point or at some or my next note at some point from the node three it no longer is i'm going to sever these relationships i have three relationships that i want to sever and then i want to redirect my um my next and previous pointers respectively the question becomes though what do i actually do with this now even before maybe before i sever these connections i may be jumping on there what do i do with this let's keep that we'll keep that question off the side and then once we get through the end of our walkthrough we'll kind of decide what we can do with that as we're doing this walkthrough and then we'll see how that kind of helps us fill in the entire uh picture from start to finish so i think so far we're so good and so for actually our picture is looking how we wanted to we now have one two three seven eight so this is exactly how we want it to start so i know that imagine this down there it's no longer a child it's like a next pointer we've got one two three uh seven eight but then we get to the eight so i mean i'm no longer here seven eight i get to the eight and now the eight has a child so once again i'm gonna repeat the same process i'm gonna kill off this relationship i'm going to kill off this relationship so these two are no longer connected i'm going to make my next point down here my child's previous now is going to become my current node the 8 and i'm going to sever this child relationship we don't have a child anymore without the next and previous so what does our list look like we've got one two three seven eight eleven twelve so we're getting there right in the original example we had one two three seven eight eleven twelve is now we got this 910 and 456 to deal with we've got 910 over here which is like in no man's land and same with this four five six and what are we going to want to do about these well let's think about it this way now um so i've found eight and i've done this connection i want to keep walking through my next variable at this point or my next uh my next value is the 11 my next one after that it's got no child so i keep going i get the 12 and i notice that 12 warm at the end of my walk so whatever list i have now i'm at the end of it and i'm sitting at the tail of this list so what the hell do i do well in an ideal world we know that we want our next answer to look like this i want to get from this 12th this 9 somehow now so how do i do that i'm sitting at 12 i've got the last item in my tail i'm not off the i'm not often let's see i don't have the last item and i want this item here okay well let's say hypothetically add access to this line over here for just one second what i would ideally like to do is i'd like to say let me set my next pointer this way my previous pointer this way so i'm going from 7 eight eleven twelve nine and nine points backwards this way and then we continue the ten so we've got one two three seven eight eleven twelve nine ten all right this is where we wanna be so far right nine ten and then i was sitting at this fault i'm done with it i'm going to keep walking through my list i'm going to keep walking to 9. i'm going to keep walking to 10. i'm not the tail of my list what do i do now well what about this bad way right we wanted this we wanted somehow to keep a reference to this four five six and so again in an ideal world i can kind of point this next this way i could point this previous here and now we've got one two three seven eight eleven twelve nine ten if i was to continue my walk from 10 i go to 10 dot next is four on x is five dot next is six and now we're at the end we're done the main question here is though there's one kind of assumption that i made which i haven't clarified how i'm going to do this yet actually this was fine um is what do i do with these well let's think about it the first item that i dislocated or kind of yanked off was 456 and then what i did was the 910 if you think about the order in which we did these in the nineteen nine ten came after the four five six meaning the last thing that i dislocated or pulled off is the first one i'm going to want to reattach what data structure does that remind you right what if we get the stack of these so what if i said when i came to this three originally and i said i noticed that a child okay let me say that if i've got something after the three if i've got a next node if i do because i may not i have one here let me take that note let me take a reference to it in memory and put it in a stack and let me do this every other time i have a child so i'm going to continue my trigger so i'm going to get the eighth and when i do this whole business would be with the 11 and changing the child up what if i took the 9 and said let me now store a reference to the nine over here now when i get to the tail of my list and i get this fall eventually i got nowhere else to go then i realized okay i've gotten to the end i'm sitting at my tail and now that i'm sitting at my tail let me check my stock if i have any items in my stock pop them off attach them and keep going so we pop it off we attach we do this next for your business we keep going we walk to the nine we walk the tent we're at the end of the list check the stock do i have anything in the stock i do pop it off pop off the floor attach keep walking we're at the end nothing in the stock we're done so the key trick here is to keep walking through the rate that always sweet until right at the tail and once we get to the tail we want to check the stock meanwhile as we're walking through if we've got a child we're gonna rearrange this relationship this next grieve child business going on uh we're gonna take the we're gonna take what would have been if it's there the next point we're gonna put it on a stack and as we keep walking on through we're gonna start once we get to the end we're going to pop off the stock until the stock is empty that's so we're going to rebuild and make this thing flat so this is how we're going to do it iteratively we're going to do it in all of n space we're only hitting every element once sorry all of that time and hypothetically in a worst case i guess this would be o event space where we could have a list that actually goes straight down so every item just only has a child that doesn't have anything else so we could keep kind of building a stack uh that way we'd keep kind of unwinding it so linear time linear space i hope that made sense i think the code won't be too difficult to deal with and yeah we can uh we can figure it out so at this point let's pull it up i'm pulling up some notes here that i got just because uh there are a few like moving pieces here and i'm kind of starting to realize that it's almost better to sometimes i'll keep my notes here on the side as i'm going through the code just so we don't uh spend time in confusion and yeah anyways we'll see how this walkthrough goes i hope it's smooth enough but uh anyways we said that we don't need to do any error checking because we're going to have a linked list of at least length one so what we can do then is we can just begin by uh stating or not stating but declaring the stack over here we're going to create the stack so just any empty stack and we're going to start by saying let's create a pointer called cur which is going to point to the head and we're going to use this courageous as our walk through the list as we would with a standard walk through so while kerr actually exists we start walking if uh if cur dot child exists so really again this is where things are gonna get fun if we're pointing at an item and that item has a child that's we're gonna have to do a whole bunch of logic otherwise typically if we don't we would just say let's go on to the next item and typically what we do is we would just say uh cur is equal to curd.next just say uh cur is equal to curd.next just say uh cur is equal to curd.next um i'll leave that here for now but i'm going to change it just very slightly once we actually build the logic into here uh what i want to do then i'm going to undo this a bit and so maybe we'll start from here so let's say imagine that we're sitting at this eight and then we think about what we're going to need to do in terms of severing these ties putting this onto the stack and then rearranging um our relationship with the child if we have if our current dot next actually exists so if we have an item after the eight because we don't necessarily need to right these could not exist that's perfectly valid if they are there we're going to want to take that item and append it so credit next we're going to want to put it on our stack and also once we put on the stock we're going to want to sever this previous relationship we're not going to want that anymore so we're going to say curd.next.previous so we're going to say curd.next.previous so we're going to say curd.next.previous is equal to none that previous isn't going to exist anymore we will then say uh cur.next is equal to we will then say uh cur.next is equal to we will then say uh cur.next is equal to child the reason we're going to say that is because we've severed this i now want to sever this as well and make it point down here okay we're going to kill this one in a second too um what we're going to want to say before we kill it though is we're going to have to reference our child and say create a child so the 11 and set its previous up to equal where we are to occur so curve.child.preview is equal to occur so curve.child.preview is equal to occur so curve.child.preview is equal to occur that's going to create again this relationship right over here and finally so we're going to get a weird air if we don't do this but we want to scrap the child relationship all together so we need to kill this off so we're going to say ker.child ker.child ker.child is equal to none now let me put a bit more space here since we've set kerr dot next to equal child if i now say curve equals ker.next child if i now say curve equals ker.next child if i now say curve equals ker.next that'll actually jump us straight down um this child here so from the eight i wouldn't go to the nine because i've killed this relationship it would actually take me straight to the 11. however i'm going to elaborate on this logic very slightly and i'm going to say that we're only going to go here if cur.next actually exists cur.next actually exists cur.next actually exists otherwise i'm going to want to break out of this while and here's the reason why think about what happens if i make my way down here and eventually i make it to the 12. if i set curve equal to curr.next i'm if i set curve equal to curr.next i'm if i set curve equal to curr.next i'm going to be out here pointing at nothing my problem here is going to be then if i want to pull something off the stack like i want to take the 9 and set it to the tail of my previous list i'm not going to have any access or reference to the tail because i popped it off so for that reason i'm going to say if cur.next exists cur.next exists cur.next exists let's go there but if it doesn't that must mean that cur is now pointing to my tail if curve is pointing to my tail i want to break out of that loop i want to leave that tail reference where it is so that when i take items off the stack i can actually reference them to the tail of my current list so that's going to mean that we're going to want to see now while stock so if there are no items in the stack by the way like nothing's going to happen and we're good we're just like it's fine no we're not going to have any logic here there have been no children that's cool we're going to return the list as it was and maybe i should have done this at the start but that just means we're going to return ahead so the head pointer that was originally inputted i'm not moving that anywhere i'm not creating any new variables for the head that reference and memory is still going to be returned the only thing we're changing is uh not the items in memory but where the pointers are pointing to within memory so if there is a stack and we jump in uh i'm going to say so we had a curse still exist cursed the tail of our length of so imagine this 12 over here i'm going to want to set my cur.next i'm going to want to set my cur.next i'm going to want to set my cur.next equal to stack.pop so whatever's at the top of my stack.pop so whatever's at the top of my stack.pop so whatever's at the top of my stock i'm going to take it off and i'm going to say cur.next is going and i'm going to say cur.next is going and i'm going to say cur.next is going to point there so we're going to point it this way that item now this 9 for instance is now cur.next instance is now cur.next instance is now cur.next so curv.next which is again the 9 well i so curv.next which is again the 9 well i so curv.next which is again the 9 well i want to take this 9 and make its previous pointer to the 12 so it's my current value so crew.next.3 is equal to current so crew.next.3 is equal to current so crew.next.3 is equal to current now that i've done that we have this relationship here i'm going to want to take i'm still sitting at this 12. i'm going to want to say let me walk through let me keep walking through this list until i get to the end okay none of these items now are going to have a child we'd already severed every child relationship that could exist they're not going to have any children but we still want to walk through the end until we get to the tail and not pass the tail because once i get to the tail here i'm going to want a reference from the top of my stack down to this tail over here so i can make this connection meaning that i'm going to say walker and curdo next so while there's well this item actually is not none um although i think actually even just seeing wow ker.next should be sufficient here i can ker.next should be sufficient here i can ker.next should be sufficient here i can test that out after um so while my item is none and i also have somewhere to go then i'm going to say crazy equal to next if i've got nowhere to go then we're going to stick where we are and we'll attach what we need to uh from the stack we'll pop it off and i'm going to run this very quickly because that should be it child is not defined because that should be curved child shouldn't it see if i did anything else should be okay cool all right so you see it passes like with flying colors is very well and like i said i think that this here is redundant um i hope i'm not gonna there you go all right so exact same solution with a bit less code and there's like a 30 something percent difference in the uh in the speed so don't worry about that as long as your complexity is where you want it to be so just we can do a quick recap of how we solve this uh we said that we're going to want to start walking through this list and we're going to pause and think about what to do if we ever hit a child um if we ever hit a node that or we reach a node that has a child pointer i'm sorry and uh so if that's the case we're going to want to think about a few things we're going to need to add whatever we're cutting off whatever's after us our next value to the stack um if it exists once it does once we've added it we're going to sever these relationships we're going to recreate the next and previous relationships with the child now and we're going to cut that child relationship off rinse and repeat until we get to the end of the list right until we're sitting at the tail once we're sitting at the tail we're going to want to say let's go to the stack and whatever items we've saved for later let's bring them back and reattach them right every time we reattach we'll say i've attached this extra branch on and i'm going to walk through the branch until again i get to the tail that's what this piece of code right here is doing once i get to the tail i'm going to go back to the top of my while loop here and say grab the next item off the stack pull it down reconnect those relationships right here walk through to the end wait at the tail rinse and repeat once we're done we return the original head and that's it guys i hope this made sense i thought it was a pretty neat trick on how to work especially with the stack it wasn't something that i thought of on my first goal so i hope this video helped if it did like comment share subscribe all that good stuff and i'll see you guys in the next video peace | Flatten a Multilevel Doubly Linked List | flatten-a-multilevel-doubly-linked-list | You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below.
Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list.
Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`.
**Example 1:**
**Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
**Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 2:**
**Input:** head = \[1,2,null,3\]
**Output:** \[1,3,2\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Explanation:** There could be empty list in the input.
**Constraints:**
* The number of Nodes will not exceed `1000`.
* `1 <= Node.val <= 105`
**How the multilevel linked list is represented in test cases:**
We use the multilevel linked list from **Example 1** above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
The serialization of each level is as follows:
\[1,2,3,4,5,6,null\]
\[7,8,9,10,null\]
\[11,12,null\]
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
\[1, 2, 3, 4, 5, 6, null\]
|
\[null, null, 7, 8, 9, 10, null\]
|
\[ null, 11, 12, null\]
Merging the serialization of each level and removing trailing nulls we obtain:
\[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\] | null | null | Medium | null |
834 | Ajay Ko Torch Light Welcome Back Pade Hai This Problem List Code 84 Some of Distance in This Problem and Decision Related to Graph Problem Statement Notes of Loop 007 Connect Note Se Zara Play List and Subscribe Small Distance Between Noida and Rest of the Distances Subscribe Now to 9 I show you some confided with example from 2009 2013 for 1000's not from travel e used. To be used for knowledge from a distance of 210 Problem Solve Distance of 101 Distance of one to is two distance of 1383 in three languages Amazing address what does we know languages Amazing address what does we know languages Amazing address what does we know how can we find a distance of one word using debit the meaning of that here On return edit joyfully dist here and this question from best equal to new intent of eyes and will return gift in converting this is to-do list play list converting this is to-do list play list converting this is to-do list play list of graft new map a fight between product half this is not fair lovely vikram 025 witch are Used as a gift after list of all the list of the year and this GPS is equal to new year a list of science and up for lok point i20 for electronic eye plus speech is equal to new research officer with oo the inte are HC in apps Lite Introduction 2012 Filter and Oil GPS Switch Off 8086 The one that someone also has to and the reverse right side from that GPS of Ajwain Add 90 A says a good one reminder is actually this off but this graph Middle East Using Various Weapons to Know Who After 10 We Call Song Deficit And Will Feel Distance To Return To Introspect Total Distance And Presentation Incomplete Distance And Not To Focus On Different Subscribe Like Share And Subscribe Flu Se 125 Subscribe Distance Supreme Plus Account Of Pride When They Are Talking For lips and veer right to great distance from a distance of no return subscribe school subscribe total account deficit in nod ki pind parents site and schedule ki return ek tot waqt se int account 109 subscribe to ki in find next in GPS of not right For all the connected notes of this month I want to avoid A to Z plus security difficult next9 that good any all set to right this next equal to parents the country will fight that good night hua 80 look at this day with r jhadu this vaccine A Potato Ko Later To Have Actually Counted In Total Account For A Given More Okay And Trying To Go Step By Step 64 Will Be Too For Election Live Vote From This Video Clips I Want To Calculate Distance In This Particular State Of West North Node Equal To A Play List Of Is Next Plus Right Good That Social Mrs. D'Souza Ne Are Right Knowledge Total In It Third End Tricks 040 Parents - 1404 Remove This Comment And See What Is The - 1404 Remove This Comment And See What Is The - 1404 Remove This Comment And See What Is The Distance From A Long Way To Calculate Distance Of 00 Subscribe To We Are Not Saving individual contract word this individual can edit modify subscribe and share and subscribe from bottom of runes in the bottom of the deficit to account for individuals are free from fear loot edward this in it third is a complaint against the count of nod plus equal to a that Agar Na White Replace Discount With Account Up Next Ki And Because Of Calculating For Inch Tape Se Distance Of No Difficult Classic Look Poster For Quality Of Mid Day Meal A Travel Samay Poster Shakkar Dal Disposal Mithila Tours 272 Plus App Loot K And Reduced Subject Co Physicians Central Se Account Is Of Science And Schools And On Account Of Noise Loot Support Order And Verifier Don't Stick To It Directly How To Fix That Doll They Have Completed The Total Distance For The Highest Position More Knowledge Some Help In The Province Of 351 Shivani 12% Good Knowledge Some Help In The Province Of 351 Shivani 12% Good Knowledge Some Help In The Province Of 351 Shivani 12% Good Knowledge Verify Add How To A Six Sixes Good Civic Bodies For Two Cars In 14k That Ko Nice E Waiting 10435 This Nice Okay So Definitely Ko Indira G Ki Previous Test One Old And Father Particular Know It Is Successful Written In The Voter -list correction equal proportion at which The Voter -list correction equal proportion at which The Voter -list correction equal proportion at which indicates in for loop in the unit digit turns into a bit but will be solution of class relation distance of quality education for all total solution total distance for using total distance calculator the meaning of here start from wave powder Total distance is 12th part in difficulty connected amount and you can see what was the value water quality account airtel in its ok total give a clear picture of moral value of 10 to anywhere you want after 06 2012 total distance now zero is nadeem malik total Distance including distance of one tight soen want you already have a total of which has a distance of one also included in amazon prime minister to remove all total distance of descent of total subscribe to the whole second 500 to 1000 this five times a distance of 105 Subscribe 999 Distance of 1521 Adhir 110 Subscribe To I just got married The above knowledge can give more clarity on this thank you will take another example Will calculate distance of to-day example Will calculate distance of to-day example Will calculate distance of to-day I am alone How can we distance to using distance from which is acquire record and distance Now Zero here equates to is the connected of Zero and when they are collecting to you already have to calculate distance from Jio phone to consider top-down stay deficit at some relief and top-down stay deficit at some relief and top-down stay deficit at some relief and vent of to the truth know your soul from root and they vent To Delhi distance to subscribe my account of to 4 total subscribe to torch light admits and declares sorry for a moment to return shot dead in the total distance of to will be total distance from this right side parts and distance from the left right to distance FROM THE LEFT PARTIES TO PUSH ME NOTE 6 - FORBIDDEN LEFT PARTIES TO PUSH ME NOTE 6 - FORBIDDEN LEFT PARTIES TO PUSH ME NOTE 6 - FORBIDDEN ONLY - 4 AND TOTAL DISTANCE FROM THIS RIGHT ONLY - 4 AND TOTAL DISTANCE FROM THIS RIGHT ONLY - 4 AND TOTAL DISTANCE FROM THIS RIGHT SIDE PATH IS NOTHING BUT A TOTAL DISTANCE - SEE IT IS CLEAR NOW THE DID NOT DISTANCE - SEE IT IS CLEAR NOW THE DID NOT DISTANCE - SEE IT IS CLEAR NOW THE DID NOT FROM LEFT SIDE SHOULDER SO WAR PREVIOUS SUBSCRIBE TO BALANCE CALCULATOR MOD Do n't forget a right my free water alcohol this pre-order ok on the contrary order I don't need this pre-order ok on the contrary order I don't need this pre-order ok on the contrary order I don't need this country are neem and someone already have don't ok happy will get discount ki ok khoyi hai tourist calculation for more a right click before order and distance After next that equal to tense of no d - account of that equal to tense of no d - account of that equal to tense of no d - account of individual and no individual and contact to have a distance of individual next subscribe is bad size of - dikha findhoon ok ab ki is - dikha findhoon ok ab ki is - dikha findhoon ok ab ki is look gautam in ho akbar de staff next equal disturb note - Account of next equal disturb note - Account of next equal disturb note - Account of Next Plus Graph Size - Part Subscribe to Kaun-kaun zero and mind Kaun-kaun zero and mind Kaun-kaun zero and mind aapke khadi hua main let me Rajesh ko don't si hain to ya is background bank deposit se pher hai ko sadbuddhi length apne a person sulut ki if Default Submit I Want To Taste This Taking One Is My Rushta Hokar Should Take One Is My Root And Tagged As Which Nice Recordist Vikram Randomly Takes Three Do Places Of Interest In 10 From One Or More Liye Fuel 10th Result Start For Free Loot Aadat Movie Open Whatsapp Guddu Will Submit This Watch 2014 Loot Gayi A Good Night Radhe-Radhe Isi Loot Gayi A Good Night Radhe-Radhe Isi Loot Gayi A Good Night Radhe-Radhe Isi Dekhte Hu Find Problem In Following This Please Feel Free To Write In Comment Interviewer This Post Older Post Third Party Easy-to-Follow Tuk A Very simple Party Easy-to-Follow Tuk A Very simple Party Easy-to-Follow Tuk A Very simple calculating and subscribe to | Sum of Distances in Tree | ambiguous-coordinates | There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\]
**Output:** \[8,12,6,10,10,10\]
**Explanation:** The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer\[0\] = 8, and so on.
**Example 2:**
**Input:** n = 1, edges = \[\]
**Output:** \[0\]
**Example 3:**
**Input:** n = 2, edges = \[\[1,0\]\]
**Output:** \[1,1\]
**Constraints:**
* `1 <= n <= 3 * 104`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* The given input represents a valid tree. | null | String,Backtracking | Medium | null |
735 | hello friends today last of the astronaut collision problem they first see the statement we are given array astronauts of integers representing estrin asteroids in a row for each astral road the absolute value represents his size and the site represents its direction party means meaning writing negative meaning left this is crucial because we will see the example in a second each astronaut moves at the same speed find out the state of astronaut F after all collisions if two astronauts meet the smaller one will explode if both the same size both will explode two astronauts moving in the same direction will never meet so let's see the example as the 5 and the 10 want to go right and the negative 5 want to go left so this 2 will click complete as the absolute value of 10 is greater than the absolute value of the negative 5 so their negative 5 will explode then we just get to the five intend this to astronauts have the same size and they want to go to the different direction so they both explode we just written empty array this one and negative 5 once you go left and if you want to go right so this to explode and the US sorry this to conclude and this two will explode we get to negative 5 and negative 5 we are concrete with the 10 and we get a 10 this example is different because negative 2 and next one won't you go left and the one and two won't you go right so we just suggested them so this for astral noise we are not meet so we just return them so the I think the key of this problem is you need to find a suitable data structure let's see how do you find the suitable data structure we handle this extra noise from left or to right like the fire we will just first keeper the fire and then we meet the ten it has the same direction with the five so we shall keep it and then we meet an active fire as they have different direction thrown the 10 so we should handle these two and they will conclude and then the next fire wheel exploded well explode so we get we do not add the neck you find our result array you see this example in the same way we get the 10 - and then we get same way we get the 10 - and then we get same way we get the 10 - and then we get negative 5 it will that's the to explode and we keep it either will keep make conclusion with the 10 and the neck if I will explode so L you can see well first go from left to right and then we want you make sure if we add this current astronaut into our result array we all go left or to compare one by one so I think those older miss may be obvious for you as it'll last in first out so we should use a stack to handle the astronaut one by one so let's first relate and you will see how to use this that so we'll use the array deck and though we just handle every astronauts will see some cases the first case is we just added a current astronaut into our stack the first situation will be the stack is empty and the same situation should be it has the same side wheezes or pickup with the stack so the static he'll pick who comes if it times the a greater than zero which means they have the same size so we shall put into the stack and they can see this example if the previous an astronaut will go left and the current will go right so they will not meet that means if the stack peak is less than zero and the eighth grade has n 0 we just put a push to the current astronaut into the stack but another if not the case we will know that they will make conclusions right let's see there is some example or some cases first the case the current astronaut is the size of the current estrin is less than the peak of them stack we just her to not add them into a stack we are done if they have the same size posts will explode the complicated case is if their size is greater than the peak of the stack we will pop from the stack and keeper compare so we may need a loop here but we need a to mark if we should add a current astronaut into our stack so I will use a boolean variable name the flag means we do oh if we need to add a current astronaut into our stack so Wilder stack is not empty and the stack peak times their current restaurant noid is less than zero we know there are simple research cases their stack peak eco tutor mess absolute value over there a both will explode and there's a stack which other pop it and the flagger will be there for so we do not yet add a current astronaut into our stack so we just break another case either if the mass absolute value the stack pick it's great to the Ender a we do not need to add as a right and we just let the flag in to the force and a break complicates the case is we needed to explode sir pick up the stack so the stack who were just a pop and their continued to compare so also a loop if their flag is true we push their astronaut into our stack so finally we just needed to gather the result from the stack the size should be the start size and neither result array this set will be n an index will start from the I minus 1 because the stack is last in first out we start from the very last so the kids should be if the stack is not empty a result index minus a will equal to the stack top if an adjustor return the sir please out okay thank you for watching see you next time | Asteroid Collision | asteroid-collision | We are given an array `asteroids` of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
**Example 1:**
**Input:** asteroids = \[5,10,-5\]
**Output:** \[5,10\]
**Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
**Example 2:**
**Input:** asteroids = \[8,-8\]
**Output:** \[\]
**Explanation:** The 8 and -8 collide exploding each other.
**Example 3:**
**Input:** asteroids = \[10,2,-5\]
**Output:** \[10\]
**Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
**Constraints:**
* `2 <= asteroids.length <= 104`
* `-1000 <= asteroids[i] <= 1000`
* `asteroids[i] != 0` | Say a row of asteroids is stable. What happens when a new asteroid is added on the right? | Array,Stack | Medium | 605,2245,2317 |
303 | foreign immutable let's read the question given an integer array Norms it handles multiple queries of the following type calculate the sum of the elements of nums between indices left and right in laser where left equal to less than or equal to right so implement the array norms they are given an integer and we are given a queries so you need to sum up the elements between from left to the right including those elements see if you can see the example this is the error and uh the these are the queries so 0 to 2 means you have to add from minus to 0 3. so 2 to 5 is R3 minus 5 minus 2 minus 1 you have to add the elements in between those ranges let's see how to solve let's say how we can solve this problem so you have a randoms minus two zero three minus five to minus 1. so the first query is 0 comma 2 so 0 is the left one and the 2 is the right number so if we look into the error you can see minus 2 0 3 or falls under in between 0 to 2 so we need to sum up those elements minus 2 plus 0 plus 3 equal to 1. and then next Y is 2 to 5. if we check it in there then it is a 3 minus 5 2 minus 1. so if you add up if you add all those elements we got the minus one so coming to the time complexity every time for every query we have to Traverse from left to right so there are M queries and uh n elements to Traverse so the time complexity is admin to n it's a very time consuming and slow process for every sub query we have to Traverse again and again so can we do better yes we can do it with the help of prefix some concept so now I will explain the prefix some concept so first if you take the original array let's take the original array minus two zero three minus five two minus one so first we will same we will keep the same element in the first question minus 2 then we take that number minus 2 and add it to the next element so the minus 2 plus 0 then it becomes a minus 2 again then from my again take that updated minus 2 and add it to the next element and replace that next element with the updated value minus two plus three this one just update it again 1 plus minus 5 minus 4 updated in the next position like that minus 4 plus 2 minus 2 a next minus 2 plus minus 1 minus 3 yeah now we got the prefix some array just we Traverse the entire array only once now can we do that queries in constant time with the help of this prefix sum yes we can do it let's take some examples like the first query is 0 comma two zero is the left one and two is the right ah and you can see here I high highlighted the number one zero second position in the area so that is the answer for 0 to 2 see if the left num the left value in the query is zero the result is nums of red because till 2 we added the all numbers so the second question contains the summation of 0 to 2. so that's the click behind this prefix sum let's take a one more query 2 comma 5 if we highlight the two comma Five Points then these are the points one comma and minus three I want the sum of these in between these elements now let's see the condition the left is not equal to zero yes it is not zero it is actually two then the result is nums of right minus nums of left minus one so basically you are taking the fifth position element that is the summation of from 0 to 5 and then we are removing some x value from that uh numps right so what we are doing is we already we need in between two to five but we have taken in between 0 to 1 in the summation of five so we need to remove that's why we take nums of five minus nums of one that means minus 3 minus 2 that's the minus one answer so the time complexity for this solution is of n times yes you need to Traverse entire area once and you need to make a prefix some array by using that we prefix sum you can do every sub whereas every sum I mean every query you can do it in of one time now let's write the code for this problem now first we will write the code in Python then we will write the code in Java also first self dot nums equal to nums yes I'm very variable s equal to zero for in range 0 comma length of nums then we need to create a prefix array so we are starting from 0 to and length of nums that means the number of lines is 5 then 0 1 2 3 4 so first element we it have to kept it as a same element so just adding nums of five plus equal to S just first the element s is I mean the variable s is zero we are adding it to the first element in the array initially so it won't change so the next we need to update the S variable nums of I then again next element when it added the previous element and it creates a entire prefix sum so now we created the prefix sum so we just add yourself dot nums cell dot nums then now we need to write the code for the queries left equal to 0 then return cell dot nums right else return dot nums off right minus of left minus 1. now let's run this code sorry here self Dot now let's submit done now we will write the code in Java also initializing nums in test equal to zero you didn't you don't need to use this uh extra variable you can do it in you can do it directly I can manipulate that nums array directly you don't need to use this table just you need to think up with a different logic I mean this is a more simplest one I equal to zero a less than nonstop length I plus equal to s equal to numbers of I uh this dot nums equal to numbers now we created the prefix array now just write we will write the code for the query getting results from that function foreign runs off right else written lumps off right minus sums of F minus one thank you for watching | Range Sum Query - Immutable | range-sum-query-immutable | Given an integer array `nums`, handle multiple queries of the following type:
1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`.
Implement the `NumArray` class:
* `NumArray(int[] nums)` Initializes the object with the integer array `nums`.
* `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`).
**Example 1:**
**Input**
\[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\]
\[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\]
**Output**
\[null, 1, -1, -3\]
**Explanation**
NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
**Constraints:**
* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`
* `0 <= left <= right < nums.length`
* At most `104` calls will be made to `sumRange`. | null | Array,Design,Prefix Sum | Easy | 304,307,325 |
980 | Hello hello everyone welcome to the second aapne bilkul channel subscribe ko maximum number of world channel ko subscribe Video then subscribe to the Video then voice mail solution intermediate let's move with oo are unique pass veer lead 98100 grams paneer wave subscribe trident subscribe our Subscribe What is the Meaning Adhik Hai Mein Soega Robot Movie With Ispat Aur Dasham CPMT Sales And Ka Word And Finally Mid-Day-Meal Veervikram Subscribe To That Now When You Are Working In Path In 10 Minutes Recent Statements Of Witnesses Who Want To Avoid 040 Subscribe To That Last Yeh Movie Mein Process Bandhe Don't Want To Deal With Same To You Now Skin Adhir V subscribe Video Subscribe To Hai What Is The First Day Cover Back Feedback Where Is The Mission More Suggestions E Star The Robot Veer Subscribe To Hai To Ise Dhokar Problem And You Will Get To No More Avoiding Porn Subscribe Video Subscribe Must Subscribe Reddy Subscribe Main Andhero Account Select Swaroop Dheer Va Subscribe Video Subscribe Volume Day Iodine Deficiency In All Directions From The Amazing Plunge In Veer Subscribe to subscribe our Channel subscribe Ki Akshay Dead Disprin Zameer Video Subscribe Button Ko | Unique Paths III | find-the-shortest-superstring | You are given an `m x n` integer array `grid` where `grid[i][j]` could be:
* `1` representing the starting square. There is exactly one starting square.
* `2` representing the ending square. There is exactly one ending square.
* `0` representing empty squares we can walk over.
* `-1` representing obstacles that we cannot walk over.
Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_.
**Example 1:**
**Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\]
**Output:** 2
**Explanation:** We have the following two paths:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
**Example 2:**
**Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\]
**Output:** 4
**Explanation:** We have the following four paths:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
**Example 3:**
**Input:** grid = \[\[0,1\],\[2,0\]\]
**Output:** 0
**Explanation:** There is no path that walks over every empty square exactly once.
Note that the starting and ending square can be anywhere in the grid.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 20`
* `1 <= m * n <= 20`
* `-1 <= grid[i][j] <= 2`
* There is exactly one starting cell and one ending cell. | null | Array,String,Dynamic Programming,Bit Manipulation,Bitmask | Hard | null |
144 | so today i want to talk about create reversal and as you know trade reversal is basically moving on a tree between nodes through different edges and if any of this terminologies does not make sense to let me know in the comment section and be happy to explain them in more detail in an interview setting there are three main approaches that we can do to traversal with one is pre-order traversal with one is pre-order traversal with one is pre-order the other one is in order and the last one is post order and each of them can be implemented either iteratively or recursively in today's video i will be talking about the pre-order approach the pre-order approach the pre-order approach and i'll talk about post order and in order on separate videos later there are two things one need to know about pre-order app which you want is about pre-order app which you want is about pre-order app which you want is that it's a top to bottom approach meaning that if this is your root you start from the root and you move toward the leaves that there are somewhere at the bottom of three and the second thing is that the procedure is that you start from the root you cover left subtree and then you cover right subtree it means that if this is your root and there exists a left subtree i'm going to call it left subtree and i'm going to call this right subtree so you need to cover the whole thing on the left subtree before moving to the right subtree and cover that and assume that there is no left subtree here and then we have right subtree right but the right subtree has two parts let me make it clear the right subtree has a left subtree of his own and a right subtree of its own when you come here you cover this node and then you go and cover the whole left subtree of this node before moving to the right subtree of this node i hope it's clear but we'll do some examples in the first example you're given this tree as you can see here note that in an interview setting you don't get that the actual shape of the tree schematic you get a list like this and generally it's leveled like it starts from level one this is loot level two and then for level two it starts from left to right and so on and so forth and they ask you to do to process or traverse the tree using a pre-order approach pre-order approach pre-order approach and what you do is that you start from the root you add one if there is a left subtree you go left which is which there is here you add two and then you cover the right subtree so basically one two three is the correct here thing here and then you want to do example number two let me clear this stuff here i hope you understood it was talking about and when you want to do here note that because there is no left subtree here in the input we have no but you start again from the root you add one there is no left sub three so you go to right you get here you add two and then here basically this is your new route you need to cover left subtree first you come here and then you cover number three that's why you get one two three so now we get to the last example number three for the pre-order example number three for the pre-order example number three for the pre-order case and then i just added this procedure here as a reminder you start from the root you cover left subtree lst and then you cover right subtree and for this example you want to know what is the pre-order you want to know what is the pre-order you want to know what is the pre-order traversal right we have an array of output you start from the root you add one here then you're supposed to cover the whole left subtree before you move to the right subtree right so we come here oops we add 2 right and now basically 2 is our new root right 2 is our new root we need to cover let me change colors you need to cover the left subtree of two everything about the left sub two of two before you move to the right subtree up to therefore you add four here you cover this one and then when you go you get to the leave you go up you come to two have you covered the right subtlety no now you come down to the right subtree up two and then you add five now your five is your new root you go left you add seven when you come to a leaf you go back to the root is your right sub to yes there is there you go and you cover it now you have eight now what you've done is that you covered the whole left subtree of the main root the actual root of the tree now what you do let me change color you go to right subtree you need to cover the whole thing here now when you go right you have this one therefore you add three to the list and then you come down you there is no left is null here so you come down you add six and once you're at six is basically your new root what do you have you need to cover left subtree first you come here you add nine now you cover the whole right subtree basically your output is going to be 1 2 4 5 7 8 3 6 9. i hope i haven't made any mistake but the whole idea is that whatever node you're at let's say you are at this node right you need to cover the left subtree if there is a left subtree first and once you get to the leaf you move back basically to the root and then you go and you cover the right subtree and you do this either iteratively or recursively as i'm going to talk about later so let's do an actual coding problem for this i'm going to do an easy problem it's a lit code 144. let me change color so it's like a binary tree pre-order a binary tree pre-order a binary tree pre-order traversal as you can see here it's you're given a root and with a binary tree if you don't know what is binaries you just google it's a tree which has for each node maximum of two channels so it's like something like this and um you're required to return the pre-order you're required to return the pre-order you're required to return the pre-order traversal of the notes we talked about a couple of exam three examples actually before but as an additional example you can see here you're given this and the pre-order here you're given this and the pre-order here you're given this and the pre-order result as we talked about is one two three and on a solution section note that you're given a three note class if you don't know what is a class in python just google and i also i honestly think that if you want to do that code or if you want to be a good programmer learn about class just spend a couple of hours learn about class what it is exactly and what's where it's useful and where it's not useful and why there are classes out there why they exist so a three node class is a class which has a value a left node and a right node basically it's you have a node white node or left node it can be null or none as it is by default you can see here its default is not and the default value is 0 and each node so for example this node has a value for itself and it has a left node and a right node and what i'm going to do here i'm going to talk about two approaches one recursive and next iterative approach note that uh generally cursive is a little bit easier than iterative that's why i'm going to talk about it all right let's first talk about a recursive solution i hope you know what is a recursive solution but if you're not please make sure that you understand what is a recursive solution by googling and there are a lot of uh problems on lead column on the internet that can be solved using a recursive approach i talked about the first part here this is a three note class which basically is you have a node you have left and right subtree or left and right basically children and the way i'm going to write the code here as you can see here i'm going to basically use the class approach and i'm going to define two functions within the class solution and i initiate an empty list as you can see here the self res stands for results and i'm gonna return that self rest finally as my output but using this middle function the self traverse route which basically is a function called traverse and you can see the function here i'm going to talk about in a minute which accepts the route and then does some stuff updates the res and finally i return the rest in this line as you can see here but the main part of the code is the traverse function this function basically this function is part of the class solution that's why there is a self here and then it accepts the root the reason that we don't need to add res here like having something like this is that because it's part of the class if you don't know why i don't have res here but res gets updated please make sure that you understand how classes work so this is the function that does the updating for us what happens here is that you have a root let me start by an example let's say we have one two the example we talked about before let's say we have this example what should we return we're supposed to return one to three right it means that you start from here you're supposed to move here and then add two and then we're supposed to move here and add three and then it will give us one two three and this is what exactly the traverse function does the trovers function what it does is that it first checks whether root exists if the root is none it stops it doesn't do anything but if there is a root meaning that as in first step if the root that you gave which basically is this one that we have here if it exists it goes and adds the value of the root to the self rest which is basically our output right so that value gets added what happens so far is that we have 1 here we need to somehow add 2 and 3. what would we do the next thing is that if you remember in a solution what the procedure for pre-order was root left sub 3 and then right sub 3 right so we need to consider left sub 3 here but for example for the example that we're considering here that this tree there is no left software left subtree is null but in a recursive approach what happens is that we call this the same function using the root left right what happens now if we call the same function using left meaning the root left is null what happens that this line does not get passed and we're going to return let's say none here meaning that nothing happens for the case that you're considering here for the exam and what's the next line is that we do the same thing we call the function self.traverse self.traverse self.traverse right but this time with root right what is your diet root right is this excuse me with white is this 2 here when we call this function we do it right let me expand this function what happens is that we are doing self traverse root and right what is root right is basically 2 three this is what we're doing and what happens if we call this function it goes and start the traverse function again what's the first step in the traverse function note that this is now or new route correct what happens it adds the root value to self.address meaning that this value to self.address meaning that this value to self.address meaning that this one gets updated here and now 2 is added now 2 is our new root what is the procedure for um pre-order um pre-order um pre-order after the dude we need to check and take care of the left sub-order and take care of the left sub-order and take care of the left sub-order right what happens here is that after we add the let me change color again after we add the two at this line we go and check the left software left stop uh left sub three and this line gets called the second line for the left subtree and then that's where three is gonna be added and that's all we don't need anything else there is no other node and then you got it we have the whole thing added and therefore we have our output and this is this was as you know was just an example this approach works for any tree or the examples we talked about before because it's genetic right for each tree if you give the function the root it's going to check the root whether root exists or not if it exists a it adds the root value as should next it takes care of the left subtree and then it takes care of the right subtree note that we talked about this it takes care of the left subtree meaning that once it's gone into this line or this function once this line is calling this function is called again it's going to go to the left subtree does everything for the left subtree first before moving to line c before moving to this line therefore once you have your route which gets added it does everything for the left subtree before moving to the right subtree does that make sense that's pre-order does that make sense that's pre-order does that make sense that's pre-order right there you have it next we move to the iterative approach or iterative solution i hope you understood the recursive one and let me know if anything was unclear i would be happy to uh explain it in more detail i hope i haven't been repeating myself too much in a recursive part let's move on for iterative approach the high level idea is the same it doesn't matter you do it recursively or iteratively you're doing the pre-order and the you're doing the pre-order and the you're doing the pre-order and the approach is the same however you do it in a different way to do it iteratively right and just as a general i don't know tip or like out of experience whenever i hear iterative i'll think about why and i'll think about stack and in pretty much all the iterative examples that i've solved i've used this too so maybe it comes handy for you as well this car this part we covered before so we don't need to waste any time on this and here instead of doing your um recursive approach we're going to focus on the iterative and the way we do is that we start from the roots here it is you check the root if there is no root it means that you don't have anything right you have an empty tree you return an empty list then you start from the root if there is a root you add the root to the stack and you initiate a rest function a res list basically result risk which you're going to return at the end here so you start the while and what happens is that let me draw that famous example of ours so it means in this line you're basically doing a while stack right it means that while there is something the stack keep running and while stack is empty done and return res as an output however while you are in the stack do something we added root to the stack so at least the stack should be called once except for the fact that this line gets activated and we turned on if we don't do that if we pass this line and we come here we have root in the stack and we need to do the stack we need to do the while loop at least once what happens is that we pop the last element of stack meaning that we pop it and we call it root what do we do now we are looking at our root we add it to the rest right this is what we do whatever node we are looking at right now this is our new root and in a pre-order approach we start the we start pre-order approach we start the we start pre-order approach we start the we start from the root we go left and then we go right correct therefore we add root value to the rest now here based on this example we have one added now we're supposed to add two o and then three right here it goes we check the right subtree you may ask you're doing the pre-order why you're doing the pre-order why you're doing the pre-order why we are checking the right sub to your right and you're correct we are checking the right subtree first because we are appending to the stack meaning that when you do append right you add from this site then appending and then you add a b c you append a b c and then you're going to pop the stack pop something from the stack later what happens that the right most element gets popped first right and what do you want in a pre-order you want the right most in a pre-order you want the right most in a pre-order you want the right most being the left subtree that's why first you check the right subtree which means that it goes down into the stack and then you check the right subtree you check the left subtree excuse me first right then left which means that this gonna be oops something happened excuse me i mean this c is gonna be your left this speed is your right and then you're gonna pop c pops first meaning that left pops first you deal with that left sub three and then you move on to the right subtree so here uh you have a right uh basically root right gets activated you add this two to your slack to your stack and then you come here you don't have any left subtree nothing happens then you go the second iteration of the while now the root is 2 right basically you write subtree of your initial goods now 2 is going to get added to res meaning that this is updated to 2 and then you go again for the check do you have let me clean this up a little bit so that we can communicate more effectively now where are you're here right you're at two you come into the check do you have a right sub 3 the that sub 3 is not therefore this line doesn't get activated but there is a left sub 3. you add this to the stack let me tell you what is the stack right now stack is what the only thing in the stack is three because initially root was in the stack you popped it here and then you added the right in the second iteration and then you popped it again when you popped it got added here if you remember and now you're adding three in the last iteration when you come here to pop to basically pop the root and add the root to the res you're looking at three and that's where the tree gets added and then when you're coming here after the third iteration this one doesn't get activated therefore you jump out of the loop the while when you come here return the res which is what we need and that's your code and just to explain a little bit more what you do is that you add the root if there is a root you add the root to the slag to the stack you pop the root add the root to the res check the right check the left if light exists at the right if left exists at the left what happens here right gets added first and then left gets added second and then you want to pop left pops first that's what you need for pre-order and that's what you need for pre-order and that's what you need for pre-order and then finally you turn the rest all right i hope you enjoy it let me know if there is anything unclear | Binary Tree Preorder Traversal | binary-tree-preorder-traversal | Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively? | null | Stack,Tree,Depth-First Search,Binary Tree | Easy | 94,255,775 |
312 | hey everyone welcome back and let's write some more neat code today so today let's solve burst balloons and this problem has really earned that category of being a hard problem so this is going to be another dynamic programming problem and we're going to solve it with the optimal solution which is going to be big o of n cubed time complexity and i believe big o of n squared memory complexity and i'm going to try my best to explain the intuition of this problem and kind of walk through my thought process but if your question is if you saw this problem for the first time in an interview how would you be able to solve it that's a good question and honestly i don't have the answer to that unless your interviewer gave you a couple of hints that kind of pointed you in the right direction because this problem requires a couple tricks to get it to work efficiently so the description is pretty simple we're given n balloons indexed from position zero to position n minus one each balloon is painted with a particular number on it so basically we're given an input array of nums or other words balloons and we're asked to burst all of the balloons now when we burst a particular balloon i we are going to add to the total we're basically going to get a total number of coins from popping that balloon we're going to the total that we're going to get is basically the number that was painted on that balloon multiplied by the two adjacent balloons to that balloon at that particular time and of course we might have a balloon that's on the boundary or on the edge of our input array so if that's the case for example if i minus 1 or i plus 1 are out of bounds of the input array then we're basically going to assume that there's you know a couple balloons with one painted on them on the edge basically there's gonna be some implicit ones so for example if this is our input array we're assuming there's a one over here and there's one over here the reason why is let's say we were given an input array of one number let's say that value was five right if we pop this we're going to assume that there's ones on the edge right so if we pop five what are we going to get we're gonna get five times the right neighbor which is one times the left neighbor which is one right so basically these are just neutral values so the total number of coins we're going to get from a single balloon is just going to be that value right 5. that makes sense that's why we're doing this so in this example the total number of maximum coins we can get is 167 and that is if we first pop this one value and then we get three times one times five because three and five are the neighbors since we pop that next what we're going to pop is the five now since we're popping this five well we need to get its neighbors right it's right neighbor is obviously a since we popped this one its left neighbor now is going to be the 3 that's over here so we're going to do 3 times 5 times 8 so after we pop the 5 we now have 2 remaining we're going to pop the 3 first and that's going to give us 3 times 8 and the left neighbor of course remember we talked about the beginning is implied to be a 1 so then we're going to get 1 times 3 times 8. now the 3 has been popped last one left is just the eight right so the neighbors of that implicitly are just one and one so eight times one we add that up to our total we get 167. now these implicit extra ones on our input array for example those are not actually going to be popped right so we need to remember that because obviously if we did pop them right we pop a one we'd add one to our total and if we pop the other one we'll add another one but that's not actually going to be the case right we don't want to pop these extras so even if you can't get the dynamic programming solution at the very least we know that there's a brute force approach right we could choose to pop three first we could choose to pop one first we could choose to pop five we could choose to pop eight right and then we could continue down this decision tree right that's the brute force right something like a backtracking approach but in that case obviously we have n choices roughly at each layer and the height of the tree is going to be n so basically the time complexity is going to be something like n to the power of n now that's not super efficient and in this case we actually can do better but it's not easy to arrive to that solution so now let me explain a little bit of the thought process to get us there and then i'm going to jump into the code in this case the code is actually not too bad once you see the couple of tricks that we need in this problem so we know the brute force approach but can we identify any sub-problems your first idea might any sub-problems your first idea might any sub-problems your first idea might be something like this okay so let's say i pop the fifth element right we popped this balloon now we have a new sub problem right we have this entire array minus this value as the sub problem right or for example maybe i popped one now we would get this entire array except the one as a sub problem right now if i continue popping for example i pop 1 next i pop 8 now we have a different sub problem so if i keep going like this how many sub problems are we gonna have well basically what we're doing as we pop elements we're basically getting every single subsequence right now how many sub sequences for an input array are there well for each value we could choose to include it or not include it right so for each value we have two choices two times two right we're basically going to do this for the size of the input array which is let's say n so we're going to have 2 to the power of n sub sequences so basically what i'm getting at here is this is not the correct sub problem that we're looking for we need to look for an even more simple sub problem because if we have this many sub problems that's not going to help us caching something like this is not going to make the solution more efficient we want to get something like n cubed and squared et cetera right this is what i'm aiming for let's try to see if we can get it so let's say i pop the five now is there an even more simple sub problem well we notice now we actually have two subarrays right we have one sub array over here and one sub array over here now these sub arrays are contiguous they're not subsequences that's pretty good because we know that at most for an input array of size n there could be at most n squared sub array so that's something we can work with to make an efficient solution so now you might think well can i take each of these sub arrays right basically by popping this we got something like one times five times eight now we wanna know independently what the each of these sub arrays could get us like how many maximum coins could this subreddit and this subarray get us right independently but what we're gonna notice is we can't just look at this subarray independently right because independently a three times one right the max we could get is we first pop the one right in that case we get one times three and you know the right neighbor is nothing so once we pop that and then we pop this three right then we'll get three times basically just three by itself right so we pop this then we add the second balloon that we pop so we'd get a total of six right just independently if we had this sub subarray 3 and 1. but we know that in reality this 3 and 1 is now going to be connected to this 8 right and independently what this 8 would get us is 8 by itself right because it doesn't have any neighbors so in total if we took a look at both of these independently we'd get something like 6 plus 8 so in total 14 right but in reality when we look at 3 1 8 what's the max we could possibly get in this case well we'd pop the 1 first right then we'd get three times one times eight now that's 24 that already by itself went over the total that we would get if we did these independently so basically what i'm getting at is we can't break the problem up like this right we can't look at these arrays separately because in reality we know that they're going to be connected to each other okay so that's not going to work now this is the part where you have to be kind of clever we said what happens if we pop this one first and then try to do the remaining array let's reverse our thinking instead of popping this first let's say we pop this value last so what happens if we pop this value last meaning we pop this entire subarray and before right before we pop this and we pop this entire subarray before we pop this what's going to happen then well we know if this is the last value that we pop meaning we popped everything here its left and right neighbors are both going to be 1 right there's going to be a 1 over here and there's going to be a 1 over here so we're going to get 1 times 5 times 1. but what's the remaining amount that we get from popping these two subarrays now because in this case since we're popping this value last that means these two subarrays are never going to be connected to each other ever not at any point because this is being popped last so since these two subarrays are not going to be connected that means we can now pop them independently so let's take a look now let's pop this 3-1 independently what's going pop this 3-1 independently what's going pop this 3-1 independently what's going to happen well we remember when we pop this independently we're basically going to get 1 times 3 plus 3 right that's going to total up to 6 once again right but that's not actually what we're looking for because remember this sub array is not independent we are it's true we're going to pop this before we pop the five but we can't just forget about the five right there is a five right next to this three one so in reality when i pop the one i'm gonna get three times one times five and then when i pop the three because we know we're not gonna put we're popping this last right so we are popping these two first but then when i pop the three i'm gonna get one times three times five right because there's an implicit one over here so how can i handle that what i'm saying is our array hasn't actually changed there is the five still over here but we want to pop all of these elements before we pop this five how can i handle that well it's actually not too different than what we went over at the beginning remember we said that let's say we had a single element in our input array let's say it's a three right we're assuming even for this input array there's gonna be an implicit one on the left and there's going to be an implicit one on the right these two values are not going to be popped when we're popping this array but we're still assuming that they're there for that computation that we're going to be doing that's exactly the same rule that we're going to follow so when we go from up here to down here right this is our sub problem so we have identified what the sub problem is going to be it's going to be this sub array the only thing we have to remember is just like at the beginning how there's going to be an implicit 1 on the left now there's going to be an implicit 5 on the right so for the sub array that we're doing the left boundary is going to be at this value the right boundary is going to be at this value but these values are not going to go away we are going to leave this in the input array and we are going to make sure that we have an implicit 1 at the beginning of the input array and similarly when we want to solve this subarray we are going to assume that yeah there's just a single eight right so the left boundary is going to be here as well as the right boundary both boundaries are going to be here but we're going to assume that there's an implicit 1 at the right and this 5 is not going away the 5 is going to be here as well we're not going to pop it because take a look at our boundary tells us just to pop this subarray before we end up doing anything else so this is going to stay here we're not going to pop it but it is going to contribute to the total number of coins for example when we pop eight we're gonna get five times eight times one that's going to be the total number of coins we get once we pop this entire sub-array so once we pop this entire sub-array so once we pop this entire sub-array so using sub-arrays using this technique where sub-arrays using this technique where sub-arrays using this technique where for every value we're going to identify well what if we popped this value last that allows us to actually get a sub problem that we can cache now in our cache it's going to be let's say we call it dp this is our cache it's going to be a two dimensional cache because we are going to be using the left value as the first index and the right value as the second index these left and right values are basically just going to tell us what the sub array is from the original array right left is going to be the left boundary r is going to be the right boundary with that being said let me just give you a quick high level run through of the algorithm and then we're going to dive into the code so we remember in the brute force we started out with okay what happens if we pop this first right so that's going to give us a decision tree now we're going to do it a little bit differently our decision tree now is going to be what happens if we pop this last which one of those paths is going to lead us to the maximum number of coins right so we are still going to brute force it kind of we are going to have that exact same decision tree only thing is we're going to use a cache we're going to take that sub problem and cache them so for example let's say we pop this value last what am i going to do and we actually are going to modify the input array so we are gonna add that implicit one at the beginning and at the end but our boundary is gonna be left is gonna be from here and right is gonna be from here that's ultimately these are the values that we're actually gonna be popping we're not actually gonna be popping these again the brute force what happens if we pop this last our left subarray becomes empty right there's nothing there in the left sub-array left sub-array left sub-array but our right sub-array is going to have but our right sub-array is going to have but our right sub-array is going to have this entire portion right so since currently our boundary our left boundaries here in our right boundaries here if we pop this value last this is what our total is gonna be we're gonna get so if we pop this last we know it's gonna we're gonna end up popping everything here before that right so when we pop this value we're gonna get three times one right so what i'm gonna say is three times nums of right which is over here plus one and nums of left which is over here minus one that's going to give us once we pop this plus we want the remaining number of coins that we get from popping the remaining portion of the left sub array we see that there's nothing here right remember we're not actually popping this value there's no other values in between so there is no left sub array what about the right sub array we're going to take our left pointer shift it by one that's going to put left over here so the right sub array is going to be all of these elements right so you can see we're going to get that total amount computed from our dp right we're going to get it from our dp if that's already been computed as a sub problem if it hasn't been computed then we're just going to do that brute force depth first search passing in these same parameters right l plus one and right now let's look at it for a more general case if we were popping let's say a middle value as the last value where we actually do have both a left sub array and a right sub array what's the equation going to look like then so we were looking at if we popped this value last next we're going to look at if we pop this value last we're also then going to look at this and this right that's basically the brute force right so basically we're going to have an i right it's going to start here it's going to run all the way through the end of the input array but now if we pop this last we know that if this was popped last we'd end up popping all of this first and we'd pop this first so then once we popped this its left would be the one its right would be the one right so that's where we're getting this from right r plus one's here left minus one is over here multiplied by the value at index i which is one right but then what's our right sub array going to be clearly this is what the right sub array remaining sub array is right how much could we get from doing that well again in our dp or if it's not already computed in our dp we're basically going to call our depth search clearly you can see that the left boundary now is i plus one right basically we're taking this i moving it over here our right boundary remains unchanged right this is the sub array that's what i'm saying here what about our left sub array over here well the left boundary didn't change but the right boundary was decremented by one that makes sense right so that's basically the idea now my question is we know why the memory complexity is big o of n squared right the cache is basically going to be from every single subarray right and it's two dimensional so that makes sense i think why it's the memory is n squared but why is the time complexity big o n cubed well we know we're going to be breaking this problem down into sub problems of every single subarray we know that there's n squared number of sub arrays right so for once we have a sub array right like let's consider the entire input array was a sub array right we know that for every subway we're basically going to be iterating through every value right this is the first this is the second this is the and so on right and considering if this was the last value popped so it's basically taking the total number of sub arrays which we know is n squared and multiplying it by another n because we're having to iterate through every single value for a given subarray with that being said let's jump into the code once you actually know these tricks and especially once you know this formula the algorithm is actually pretty easy with recursion so like i mentioned we are going to be updating the input array we're basically going to be adding a 1 at the beginning and then adding a 1 at the end we're also going to be having a cache i'm going to call it dp because it's short and then we can start with our depth first search function so let's define it we know that we're just going to have left and right boundaries right so basically left and right are going to be indices of the input array but let's call that depth first search function we know we're just going to be end up calling it and then returning the results so let's do that before we actually define the function now what am i going to pass in as a left and right boundary zero and you know the last index no right because we don't want to actually include this one and we don't want to include this one so i'm going to be passing in zero plus one which is one and basically passing in the length of the entire empire numbs minus two because we know this minus one would give us the last value minus 2 is going to be 1 less than that so because remember we're not actually popping these and these okay so now what are actually the base cases for this algorithm well if left equaled right that means we have only one balloon left to pop so that's actually okay but if left past the right pointer so if left became greater than right that's when we know we've ran out and that's when we know we're gonna return zero meaning there's nothing left to pop otherwise maybe we've already computed this before and it's already in our cache right this left and right pair is already in dp in that case we're just going to return dp of left and right otherwise we know that it hasn't been computed so now it's our time to actually compute it so let's set it initially to zero and now we're going to determine what is the max number of coins we could get for this pair so remember we're going to be iterating through every i considering if at index i that balloon was the last balloon we popped so let's go through every index from left all the way to right and let's compute the number of coins we could get from that so we know that if this numbs of i was popped last we'd get numbs of i multiplied by nums of right plus 1 multiplied numbs of left minus one right and now to coins we're going to add the additional coins that we would get from the left and right sub arrays right so we're going to be calling our depth first search function the left boundary stays the same and we're gonna do i minus one and we're also going to be calling it for the right subarray which we know we can get with i plus one as a left boundary and our right boundary is going to stay the same so now we've computed the total number of coins right it makes sense why we're doing this and then calling our debt for search function so now we can potentially update the result which we know we're storing here in dp of left and right so we're going to update it to the max of potentially what it already is and the max of what we just computed the total number of coins that we just computed and so we're basically going to be running through the entire loop doing that i hope that this kind of makes it a little more obvious of why this is n cubed we know that this debt for search function the maximum possible number of ways it could be called is n squared right every pair of the left and right indices could be n squared times e and then if we actually if it's already been cached then we're going to return it in big o of one time if it hasn't been cached meaning it's the first time we're computing this we're going to have to run through a linear time loop and for each of these pairs we are going to have to run through a loop at least once so that's what's going to give us the n cubed time complexity but yeah once this has been computed we know you know we can just go ahead and return it from this recursive function and that is the entire thing so you know we defined a function inside of a function but once you know the trick which is not so obvious we do have to do this and then we do have that relationship of you know we're popping this balloon last it's not super intuitive but once you do have it hopefully your interviewer gives you that hint but and if you do get that the code is actually not too bad as you can see when you do recursion so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching | 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 |
74 | hey what's up guys this is chung here again so actually i want to briefly talk about today's daily challenge problem which is number 74 search or 2d matrix you know so i think it's a okay it's a medium problem right so basically you're given like uh examples of m times n matrix right a 2d matrix and this matrix has the following properties okay so integers in each row are sorted from left to right and the first integer of each row is greater than the last integer of the preview the last integer of the previous row so basically you know so this is like a sorted string right but in instead of 1d it's a 2d so 7 is greater than 1 10 is greater than 7 and then basically from here and it's just like a sorted string sorted list but instead it's being converted to a 2d here so then it asks you just do a search right to find like a value so it's just like it's obvious it's going to be a binary search right i mean the only difference with the 1d binder search is that we just need to somehow convert that's uh that 2d coordinates into that 1d index right so here we have a two we have x and y but in the binary search we only have one value or one index okay so i mean we just need to uh to know that right i mean let's do uh so here's how we do it right okay so the matrix right so the m and the n the uh length of the uh matrix zero right so that's m and n and uh of course so the left is zero okay and the right so how do we convert that so to convert that we just do at m times n minus one right so that's the uh that's the total number of the index right for this binary search okay and other than that it's just like the regular binary search template in this case we need to do a left equal less than or equal to write because it could be uh the left and right pointer will end up at one at the uh at the middle right so here so the left here and left and right 11 right so this is left and this is right so and yeah it could be uh you know we have to move somehow left and to the right so that we know the uh we can cover all the other cases right even though the left and right are on the same position we still need to check if this position has the uh has the answer we need okay basically if we do a left less than or less than right so we'll be missing the case or where left is equal to right okay so here middle equals to left plus right minus left divided by two right so and you know like i said this is like a 1d index but in order to check the values right we have to convert this one in back to the uh to the x and y right so how do we do that so we have i and j right so the i and j equals to what we have we can do a basically the i is equal to the middle we uh we do a divided right we do it divided by n that's how we convert it to i and j is like the middle uh do a mod by n okay so that's how we convert this 1d value into this 2d coordinates okay and then we simply check the uh if the matrix i and j it's smaller than the target right and then we know okay it's smaller we need to move this left to the uh middle class one okay how's if right house if matrix inj is greater than target then we know we do a right equals the middle minus one okay else we simply return true here right because we have find that the answer and if we didn't find it in the while loop we simply return false here you know so here we don't do a plus one because actually we're looking for a number that's in this if we didn't find it we do a left plot we do a left equals to middle plus one so there won't be a any uh infinite loops issue here so that's why we just simply do a right minus left okay yeah so i think that's it right so true submit oh yeah so of course so if not matrix right if there's no matrix we simply return fast okay oh cool it's accepted i mean pretty straightforward right i mean the uh the time complexity of course it's obvious time complexity is log m times n right that's the time complexity cool i think yeah that's all for this problem yeah the only difference is the uh just convert the uh conver convert this 2d range to the 1d a 2d like m and n to this 1d left and right range and then after that we you when we have the middle value we have to use the same the reverse conversion to get the other 2d coordinates so that we can compare the value with our target okay other than that nothing too special cool i think that's it for this problem uh thank you so much for watching this video guys stay tuned bye | Search a 2D Matrix | search-a-2d-matrix | You are given an `m x n` integer matrix `matrix` with the following two properties:
* Each row is sorted in non-decreasing order.
* The first integer of each row is greater than the last integer of the previous row.
Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_.
You must write a solution in `O(log(m * n))` time complexity.
**Example 1:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-104 <= matrix[i][j], target <= 104` | null | Array,Binary Search,Matrix | Medium | 240 |
1,002 | of string made only from lower lowercase letters return a list of all characters that shows up in all strings within the list including duplicates for example if a character occurs three times you know all strings but not four times you need to include the character three times in the final answer you may return the answer in any order so string overrate uh string operates at tonight frequency equal to not equal to main frequency of um c minus a not a gallon c minus a uh because if boosted foreign current equal to current frequency uh eq of the current frequency equal to new um another four char actually four ain't j equals to zero j is less than um twenty six clicks have no uh iteration another mean frequency of zero high with uh current frequency of j minus now there we go okay mean frequency of i that's greater than zero because zeros results that add string greater legal so string that value string the value of know um thank you | Find Common Characters | maximum-width-ramp | Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**.
**Example 1:**
**Input:** words = \["bella","label","roller"\]
**Output:** \["e","l","l"\]
**Example 2:**
**Input:** words = \["cool","lock","cook"\]
**Output:** \["c","o"\]
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters. | null | Array,Stack,Monotonic Stack | Medium | null |
252 | what's gonna buddy welcome to leak a passing solution 252 many rooms so if a new here will come be sure to check my personal website nanny Plata calm there are a lot of coding projects you know so articles that might be helpful to you alright so my first of all my poetry since I do not have a premium account so I have to refer to others on website to see the questions so this question is very common in our own life like for example if you were going to schedule a meeting with your friends or your colleagues then you might probably come up with this kind of you know issue in our real life all right so what are this question so this question is basically to ask by giving you start and end times for a meeting we just like this determine if a person could attend or meeting us or not and the format's are like in the least so for example the first meeting start it starts at zero and the 3d and second meeting starts five and end at 10 so the return type is true of course so what should we do and what is the algorithm for this question so when we are given a schedule of meetings so for example I got a meeting like ah so this is a meeting and this is that time so this is a short so here is a strong time and this is the end time and I got another meeting like here and I got a third meeting like here so the first thing that we need to do is restored the input and we are going to have this kind of you know meetings in schedule like by sorting the first element which is the start time for all the meetings and that's we're going to do is regularly check for each meeting the starting time with their previous and inclined so as long as the starting time is its what the value is larger than the previous ending time then the person can attend both meetings and Sam for all the following of meetings so as long as all the meetings for each meeting their starting time is larger or equal to the previous meeting time then the return should be true otherwise it'd be force which is in the third meeting here this story ends on is smaller than the previous and it's on and therefore in that case you should return false so let's see how to realize this in the car in Python so here how define the functions name as meeting room here and I also initialize the function so the first thing I'm gonna do is I'm going to sort my of intervals by the first element which is 0 5 or 15 alright so next thing I'm gonna do is I'm going to compare on the yeah on the meetings with the previous are ending all right and probably here you can have in interval not or meeting them might be very length of the intervals so for ranch one two now the reason I ups my the reason I started from a 1 is because the first meeting I don't need to compare it right and just gently compare the start time with the previous meetings on any time so here if intervals I and if this value is smaller than the previous one from this one's any time then it will just written post otherwise it will just return true all right so let's run it in terminal so oops I think the third line so we restored you don't have the punic assigned but if it is sorted then you have to just run again and it returns to false and that is what we are expecting all right I think this is the end for this tutorial if you have any questions comments please feel free to leave comments below otherwise I will see you in the next tutorial media room - thank you very much and media room - thank you very much and media room - thank you very much and have a nice day | Meeting Rooms | meeting-rooms | Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** false
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** true
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 106` | null | Array,Sorting | Easy | 56,253 |
103 | all right what's up guys we're doing binary zigzag level traversal top interview questions medium set binary tree question number two so given the root binary tree return the zigzag level or traversal with nodes values so for the first level you want to go left to right then right to left and left to right all right and over here they just have some edge cases so let's look at a example that i set up for you guys so for this question let me just hide all of that you want to go left to right a then right to left c b then left to right again dfg and ih and that's exactly what lev uh the zigzag level traversal is so you might be thinking what's a level word traversal because they say zigzag level or traversal is you'll just go left to right so over here you go a b c d f g h i you might be wondering all right how do i get a zigzag from a level or traversal and it's pretty obvious you just reverse the list i go right to left so they go left to right easy so how do i get a level or traversal that's the next question that comes up so the way i see there's three steps to level reversal so you got to get the nodes that are stored on a level in a data structure let me just delete the zigzag so you get a right and then you want to add its children uh to the data structure or you want to add a to list first for that row so list just for that row do you want children to data structure and then repeat the process just like that rinse and repeat right but you might be wondering what's the ideal data structure to use so for one value it really doesn't matter you know you use a stack or q it's only one value it doesn't affect the flow but when you have two values is what it's one that's really matters so you have a and you have b and c to some data structure i'll let you know you guys will figure it out with me so for b you add in you add it to the list and you add in d and e and then you want to access c so let's just give a little example here we have a q and we have some list so initially our q has a right and you want pop a l as oh i give it away it's a q but basically i'll show you how this works so you add in a to list then you have b and c in your q you want to add in b add its children to q which are d and e and then you all pop out c and add its children to q which are f and g but the reason we use the q is because look how we act we're able to access b and c first because they're first in first out that's obviously a q and you might be wondering both how do i know when to stop like why would i just stop at bc what if i just kept on going and the secret of that is you look at how many values how many nodes are in the cube before you start popping out and adding a new value that way you know how many nodes you have to look at for that level so in this level it's just two so this level you'd only look at four values but the q could get bigger like pop out d at its children which are just h and then you pop out e and it is children it doesn't have any then f pop in his children which is i and then pop out g and add in its children which doesn't have any but and you stop here because you only you knew from before there's only four values in this uh level and then you just make another while loop in your while loop you create a new list for that row you just add in convincing repeat just add in all the values to the list add the new values to the queue and with that we have the solution so let me quickly talk about space and time complexity space complexity worst case we're just storing one value uh it's the node in a q that's all of n time complexity on the other hand this time the time complexity is one you gotta think about the traversal and reversing the list so the reversal is oven right you traverse through the entire endnotes but the um reversing it may take it may increase that to low and square i'm going to show you guys a way to keep it old and um basically the way is the way you can add to the list is you can add to the front of the list or you can add that back of those so if you continually add to back the list you're basically or adding them in reverse order so let me show you real quick so d e f g right say you wanted to reverse this and you want to add it to a reverse list so you always add it to your front that's the secret so first you add in d then you add an e then you add in f and then you add in g and as you're always uh adding them to the front the last values in the front and the first values in the last and that's basically the idea on how to keep this solution all in space on time to really impress your interviewer so now let's start coding up the solution uh first thing we need return array we need a q to store our keynotes and first check we want to do is we want to check if the root value that we're looking at is null because then you just return the empty list and we need a starting note to go through all the children in the uh tree right because we're just adding into a cube but if there's no starting no if it's no then we can't really do anything so we just return an empty list great otherwise you want to add it to the two so q dot add roots and you want to do a while loop while the q is not empty first things first add a list of integer for that row we'll call it kero all right now uh you want to look at the length of the cube before you add or push anything out of this so int row length is equal to q dot size all right cool and let's make a value to store the current note that we're looking at perfect so you want to make a for loop only through the values in that row which so for and isaac will do zero eyes less than rolling plus a new keyboard all right what you want to do is first thing curve is equal to q dot pull that's how you get the front of the queue first and first out then you want to add that to your current but we got do we'll think about uh zigzag in a second then you want to add the left and right children if they exist so if cur dot left is not equal to null then q dot add curve out left and do the same thing for the right all right that's cool and what we want to do is we want to add that current row into our list of lists and at the end you wanna return our return array that looks good and this is right now it's just a level order traversal how we're going to make it a zigzag level or traversal is we're going to add a boolean to check if we should reverse the row and initially it's equal to false right first one you don't uh reverse secondly you do and every time you wanna flip the value so reverse row is equal to not reverse row all right and we've got colon there and the way you do is i showed you before so if you reverse row you want to add it to front so for lift and java they have this index and value so you can define the index to be zero it's that way you can add to the front of the list otherwise you can just add to the back so not uh indicating an index just automatically adds a back to list all right that looks good let's try running it um okay dang guys are ruthless with syntax honestly that's a reason i don't like java i think i might just switch oh yeah i called it her everywhere else except for the declaration so i'm going to be switching to seatbelts for my later videos i'm still going to have java solutions up on the github page it's pretty much going to be the same so solution was accepted but i really want to try learning c plus and i think it'd be a good opportunity don't worry though all the solutions will still be posted in java on the github and the explanations are pretty much universal so thank you guys so much for watching uh leave a like comment subscribe give me some suggestions on how i make these videos better i'll see you guys in the next one and that's about it codes in the github description so check that out uh peace out | Binary Tree Zigzag Level Order Traversal | binary-tree-zigzag-level-order-traversal | Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[20,9\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100` | null | Tree,Breadth-First Search,Binary Tree | Medium | 102 |
746 | hey everyone welcome back and today I'll be doing another lead code problem seven four six minimum cost climbing stair this is an easy one and a very similar problem or exactly the same problem you can say uh to the 70 climbing stair but in this problem we are just only going to return the minimum cost of the climbing stairs so that what is the cost is the step we are on so let me explain if we have an array like this and we have to reach the ending point which is zero then obviously we can take two steps this s and it is at 10 we can take two steps which will may give us 20 but we are not at the very end we will take another step the whole cost operation is going to be 20. but if we take 15 we can either Start From First index or the second index if we start from 15 we can just take two steps and reach the very end that's why we are going to return to 15 because it just cost less what we can do is just take the last start from the very last and add the values next take the minimum of the I plus 1 the location we are on plus one plus two take the minimum index and add them at that location so for 20 it is going to be 20 plus 0 we are not going to you can say change the last two indexes because it does not make sense and 20 can take one steps and from at 0 and 15 can take two steps and at the very last for 10 it does matters because if we go from 10 to 15 then it is going to be a 10 cost operation and now we are in 15 we are going to take a 15 cost operation which will make us to the very end and this will just make the output at 10 25 so we'll be taking the minimum and the minimum is going to be 15 so that's it so cost dot append it with 0 so for I in range of length of cos minus 3 because we do not want to change the last two indexes or that's it and now we want to go till -1 and now we want to go till -1 and now we want to go till -1 and decrementing one at each point uh like this okay so cost at I is going to be added by the minimum of its next or of its next so cos add I plus 1 post at I plus 2 then we can just return minimum between the cost at the very first because we can start from zeroth index or the first index so we'll be taking the minimum cost which is present at those indexes or one and that's it this should work | Min Cost Climbing Stairs | prefix-and-suffix-search | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". | String,Design,Trie | Hard | 211 |
31 | in this video we're going to take a look at a legal problem called nest permutation so implement the nest permutation function which rearranges numbers into the lexicographically nest greater permutation of numbers so if such an arrangement is not possible where let's say we have a situation where we have the maximum permutation of our current sequence that we want to rearrange it as the lowest possible order sorted in ascending order right so the replacement must be in place basically means that we want to compute this or complete this function in a constant space complexity so you can see here we have an example right so let's say we have nums is equal to one two three so if it's one two three we want to generate the next permutation that is greater than 123 which is 132 right there's also other permutations like 213 right or 321 right these are permutations are greater than this element but in this case we want to find the nest greater element that is greater than you know the current uh in this case the current sequence right so in this case the solution will be 132 or in this case 132. and like i said before if we have a situation in this case if it's not possible to rearrange it to the next greater element in this case what we have to do is we have to you know rearrange it as the lowest possible order which is sorted in ascending order right so you can see here we convert it into 1 2 3 which basically means that we reverse the array into a sorted array right because we know that this is the max right so there's no more that we can go above that so in this case we can just reverse the array into one two three right and let's say we have an example like this one five in this case if i the next greater element for this sequence is with basically one five one right and same thing here the last if there's only one element in this case we can just say that we cannot find an s permutation we can just don't do anything right and remember the function returns void so we're not returning anything we're basically just modifying the array so in this case the constraints is that the length of the array is between 1 to 100 can each element can contain duplicates in the array and we can also uh the element range is between 0 to 100. so in this case how can we better solve this problem so let's take a look at the example here right so let's say we have one two and three in this case what we can do is though maybe we can look at the current element right we look at the current element in this case current element is greater than the left element maybe we can just swap their order right and then in this case you can see we get one three two right so you might be thinking maybe this will be a the correct approach to solve this problem but you're wrong right because you can see here let's say if i want to find the next permutation for this sequence then in this case i know that the current element which is less than the uh which is less than the left element so in this case we this is not this nut element is not we cannot swap those two right because if we were to swap those two you can see that the order will be one two three so therefore this is actually less than this element right so this is not going to work so what we need to do is we continue so we know that this current element is actually greater than this element so maybe we follow the same logic we will uh swap those two elements here right so you can see we will swap those two elements and then what we will get three one two and three one two is not the correct answer for this sequence because in this case the proper answer for this sequence is actually two one three right because you can see here the next greater element here is two one three so in this case this approach that we were just talking about is wrong so in this case what's the right approach to solve this problem so in this case you can see here um for following the approach that we just talked about we can be able to find the element that we want to change right because in this case the element that we want to change here is for sure it's going to be one right we cannot change two or three in this case if we swap two and three that's not going to happen because if we swap two and or three and two right three and two then we will become something like this so in this case the only thing that we can swap is basically this element right here right so in this case if i want to swap this element to something else which element should we swap in this case this element should swap to the next greater element right the next greater elements what is two right if we swap this element with an estimator element in this case it's not gonna be three because three is the biggest right two is basically just in between one and three which is the next greater element than one so in this case we to swap right what we want to do is we will actually want to swap one with two instead of three so in this case we have two right three and one and then what we notice is that right we got three here right we got two here but then what we had to do is we have to fix the you know the remaining elements here because in this case the net square element should be 2 1 3 instead of 3 1 right so maybe what we can do here is that we can just reverse the order because in this case we know that this is three this is one right so what we can do is we can just reverse the order of the remaining subsequence right so in this case it will give us two one three because in this case we want to find the next greater element right because after we swap the less greater element than one which is two we also have to make sure to reverse that the reason why we reverse this part is because in this case you know that we know that the right side right there this subsequence they're all in a decreasing order right because the condition is that if the current element right if the current element is greater or in this case is not greater than the left element then this is not the element that we wanted that we want to change right so in this case we continue to search on the left side to find that element so that's what we're trying to do here so let's say we give you another example right so let's say we have one or maybe three two one so let's say we have three two one so in this case you can see here we can basically do the same logic we check to see if current element is greater than this the left element in this case is not this is not so therefore what we can do is we basically uh in this case you can see our pointer basically point out a bound so we basically just have to reverse the right subsequence but in this case let's say we have like one and five right in this case let's say we have 115 we check to see if this is greater than this element in this case it is right the current element is greater than the left element so we know that this is the element that we want to change that we want to swap to right in this case we want to swap to a element that is greater than the current element in this case the next greater element on the right side is five right so we swap one with a five so now we have one five one and then what we have to do is we have to reverse the right side so we have uh just one here right so basically our job is so let's say we have another example right so let's say we have this sequence right here right so we're gonna do is we check to see if current element is greater than the left in this case it's not this element is not greater than the left this element is not this element is greater than the left so we know that this is the element that we want to change right so what we have to do is we basically trying to find the next smallest element on the right side which is five so in this case what we're going to do is we have swap the order right with five and four right so in this case we have something like this and then now what we have to do is we basically have to reverse the right side right the right subsequence in this case we have something like this right four and six in this case you can see this is basically the net square uh or the nest permutation of this sequence right here right so now you know how we can be able to solve this problem let's take a look at how we can do this in code so now let's take a look at the code right so you can see here we have a function that's permutation which takes the integer right so our base case is that if n right is only there's only one element in the array then we could just return right because in this case the next permutation is basically the array itself so what we're going to do then is that we're going to first find the elements to replace right so in this case let's say we have 4 6 5 3 right it doesn't really matter what we have up front basically you can see here we want to find the elements that we want to replace in this case we are starting from here right the current is pointing here the previous point here right so in this case we have a current pointer and the previous pointer we're shifting right moving from the right side to the left side right we go from the right to the left in this case what we're going to do is that if we if there's a situation where the previous element is actually bigger than the current element right and that will be at this position right in this case six is actually bigger than four then what we have to do is we just break and once we break what we're going to do is that we're going to check the two things right if the current index in this case this is current if current is actually bigger than or equal to zero why because there could be a situation where we only have six five three right if we only have six five three and in this case guess what current is here and the previous is right here right so you can see here current is out of bound so if it's out of bound then we just have to reverse what we have for prev and the last element right which is this sequence right here right but if not if the element that we wanted to replace is somewhere in the array right which is bigger than or equal to zero now what we do first is we want to find the index that we want to swap right and then we reverse the remaining subsequence right so you can see here we have our in this case we have our uh pointer right so in this case you can see the reason why we want to do this way right this code right here the reason because you can see here you notice during the process of coming towards current right here is a decreasing order right because of this condition if it's a decreasing order then we know that we can basically try to find the next element by starting from the last element right so does this element greater than 4 in this case not 5 in this case 5 is right because in this case you can see it's a decreasing order so the next element that we can find that's greater than this current element is guaranteed to be the next greater element for four right so the next greater element for four is five so we're going to replace that so five six four three right and then what we're gonna do is we're just gonna reverse the last half or the you know in this case the right half of the sub array right in this case we have 5 3 4 and 6. so now you can see this is basically our answer and that's why we reverse it here so this is how we solve the problem so in this case the time complexity for this solution is going to be big o of n where we're basically just going to iterate the array a couple of times right so first we want to find the elements to replace and then what we do is we basically try to find the replace index and then we reverse the array which still the time complexity is big o of n right and the space complexity here is basically just going to be big o of one because you can see here we're only using pointers right using couple pointers to reverse the array or basically try to find the nest or the elements to replace or try to find the elements to or the replace index right so in this case the overall space complexity is basically just going to be big over 1. | 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 |
96 | hello everyone i'm young first welcome to my channel this is the series about the self mocha technical interview in english today in this episode we will to solve any problem of little code so let's start today the difficulty is a medium so i think we should resolve this problem within 20 minutes in a interview so let's start unique binary searcher trees given integer returns a number of structurally unique binary search trees which has exactly a note of unique values from one to one so it's water very clearly so let's look at the example say this is the three so we have four for binary circuitry tree which reaches the node is from one to n yes so it's a more com connear when we had the example uh we have a unicorn and we need to get the number of the unique binary trees ratio has exactly a nose for example three is one two three and those five binary circuitry uh are valid by research tree and uh and it has three nodes and there is no other binary trace that has a nodes so we need to return five another one in fact is very small which is uh from one to none nothing so what do you think hmm sample for example if is zero uh no there is no zero if it is one so there is just one uh one binary search tree it's just one node uh and if there is a two and equals two uh i think there is a nice to that um there is a first one and then this is two and uh and this is two and uh this is one there is a two put to two binary surgery and uh when and use this three how do we construct the bandwidth tree and like two way first try to put a uh put the ivory node as the root node and uh and we put a put the remain nodes in the left or in the right so for um equal to three we first put a one and then we put a uh put a two and uh finally we put the three as the root note and then for one is the route we have two and three so we can restart recursively car cars cause a num trace the same function with the argument equal to two and uh and two with an equals two there this is the two so there is two such situations when one is the root tree and if uh two is a router node uh we have one three here so we need to call numtrace function with argument one and with the argument one and we need to multiply the two numbers because they are independently the they are independent with each other whether the three is the rule node is very similar with the one is the glutamate we have two nodes in the left so way and we recursively call the same trace in the left and the way there is no note in the right so it's one so finally we get our answer it's a recursively solution we need to we need to um to iterate every possible ruth note uh and after we choose the router node either part it divided the whole nodes into two parts after part and the red part and we recursively call the function and we multiplies to answer so let's do that and hope maybe we can analyze the time camp city first because we need a two iterator or a possible route so it's a that we need to car um when you do cars or the two functions and to the left tree and the left tree so it's difficult to analyze it in fact the on the answer the time constitutes the answer in fact if the answer is five we will that five and uh so how do we present the temporality time capacity with um i'm not sure okay and the space community is the same as the time capacity because we need to we need a car cars or the master function with arguments one to be honest i'm not sure about the time complexity and the space completely but i believe that my solution can pass so that's the as a 2r function let's do our implementation and uh if n is one it's still one two and if it's is larger than one we need to iterate every possible have a possible new note and answer and we need to sum the left and multiply the right and i here is i um we put one here i have to use zero and here and we need to return on because there is some duplicator computation so we need a catch here so wait with this annotation we can catch the answer which we have calculated so so we can avoid the opening the calculation so we need to return here so that's the r code the code is very short and very clearly oh let's try to submit that yes way success the solution is right i did this before one years and ago and two years ago now i want to see some more discuss and find out at the time come city let's do some i spend the most okay uh there is no time capacity analysis tool i think maybe it's very difficult to analyze that okay oh so it's a catholic number if you are not good at the mathematical it's impossible to analyze the time capacity so okay i think the time capacity is a combination number which we call the kitteny number yeah it's buddha um it's good to know the catalytic number and the temperature but you but i think it's a fan if you don't know it in your interview because it's a super difficult and mathematically solution so i think you just need to learn how to solve this problem of ways uh with the recursive under the dynamical dynamic programming so i think this is my today's video thank you for your watching and bye see you tomorrow | Unique Binary Search Trees | unique-binary-search-trees | Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 19` | null | Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree | Medium | 95 |
1,657 | hello and welcome to another video in this video we're going to be working on determine if two strings are Clos and in the problem two strings are considered close if you can attain one from the other using the following operations one swap any two existing characters so swap their location and two transform every occurrence of one character into another and do the same for the other so for example transform all A's into B's and all B's into A's you can use operation as many times on each string as many times as you want given to strings word one and word two return true if they are close and false otherwise so in this example you can just use word one to make the strings the same because word One lets you swap the order of oper the swap the order of letters and the letters are all the same so this is fine here you can't because there's only one a and there's two here so there's like nothing you can do like you're only going to have one a here and two A's here and in the last one you can do it as well and they kind of demonstrate here so the main thing for this problem is you basically have to figure out what these operations allow you to do and then what you have to look for to figure out if it's possible and the constraint is 10 the 5ifth that means you need an oven or an login operation so I think this first one is kind of straightforward like what this operation allows you to do right so this is basically saying if I have equal number of characters into Strings then I can make them equal right that like that should be pretty easy and let me show what that means so let's say I have like and it doesn't really matter in what order so if I have like ABC D and I have dcba or dcab or anything basically if the number of every character is the same I can just move these around using this operation to make them equal right so that's what this one does and that one's pretty straightforward now the second one's a little bit um trickier but basically if you can change all of one character into another and backwards what this means is if I have like let's say I have three A's and I have two B's if I change all of my A's into B's and all of my B's into A's I basically swap their counts so what would happen is if I use this operation then I have two characters and I basically swap their counts so any characters you have you can swap count so like if I have some B's some C's let's say I have whatever right I can take these four counts and kind of rearrange them around no matter like depending on what I want right if I want Four A's I can swap A's and C's so I can basically get this to be any format I want right like let's say we want for example let's say we want 1 a 2 B's 3 C's and 4 D's this is always possible because your counts are in these numbers so if we wanted this let's just kind of like quickly figure out how we would do that so let's just say we swap C's and D's so we would swap their counts so this would be four now and this would be one now we want three C's so we can swap C's and B's so this would be three and this would be two H sorry it would be one actually and then we want to swap these as well so we would have 1 a and 2 BS so now that you understand like what these operations do it should be a lot easier to solve this problem basically we're looking for two things when we have two words W1 and W2 we need two things for these two words to be correct one we need each word to have the same letters right so for example if I have like ABC I need letters a b and c to be in the other word right like if I have like a z over here I can't do anything with this like I can't change the letter into another letter I can swap stuff but I can never just get rid of the Z so that's one like and we just need to have like one of these so it's totally fine to have different counts but we need each word to have basically like if I if i' get a set of letters in like if I if i' get a set of letters in like if I if i' get a set of letters in one word and a set of letters in the other word those should be equal now the second thing you need so this is number one the second thing you need is because we can rearrange these counts we need the counts to be the same numbers in both words and what I mean by that is the counts need to be the same numbers they don't need to be the same for every letter but if I just like sort the counts they need to be the same so let's just kind of like walk through an example here so let's say this word on the left has ABCD and we'll have some counts so like a has a count of Four B has a count of three D has count of two c has a count of one this word on the right needs to also have these four letters a b c d you can't have any other letters and it can't have any of these missing and the counts have to be these numbers so there has to be 1 4 1 3 1 2 and 1 one and if I have that no matter what these are no matter where these are like if this is 1 2 3 4 let's say now I am always able to turn this word into this word because I can just rearrange these counts right as long as basically the keys are all the same and these counts are all the same now how do we look for that so one way to do that is like get a set of keys let's say and you just compare one by one maybe even sort the keys just to make sure you're like comparing them right so you get some word over here on the left you get all the different letters and you sort them and you'll have like a b CD here then on the right same thing get all the letters and sort them and it's going to be pretty fast because there's only 26 letters if you do a set right so you'll have ABCD here so these will be equal and then the counts kind of the same thing get all of the counts and just sort them in increasing or decreasing order and just compare the values so in here if I just get the counts put them into an array it'll be 1 2 3 4 on the right same thing 1 2 3 4 and if any of these criteria doesn't match then you can't have this work right like if this a was a z then this would never work because I need an a here and so on right or if I had like an extra letter here it wouldn't work either because I can never get this Z I can't produce it out of nothing so I need to get a z here but I can't do that so the keys have to be exactly the same and like I said the counts have to be exactly the same not for letter but just overall all the numbers if you just take them together they have to be exactly the same right so I have 1 2 3 4 and a 1 2 3 4 they can be in any order you want but that's basically it and yeah like I said bunch of ways to code this but that's basically all we need to have these two things and that's why you need to understand what these operations do and as long as you see the first operation make sure that like I don't really care what order my letters are in I can make it in whatever I want and the separ second operation lets me flip counts so as long as these Keys actually exist I can make their counts match up and get the word I want so the order doesn't really matter okay so now we can code it up so in Python this is a lot easier than other languages so in Python we can get two counters and what a counter will do is it'll give you a dictionary of um the letter and its count so we can do that for both of the words so counter one counter word two now the other thing that's also really nice in Python is you can actually compare Keys directly so I can just say like this counter one dokeys which will be the set of letters in the first word and counter to. Keys which will be the set of letters in the second word and in Python um these things aren't compared by reference they're compared by value so if you compare two sets it will compare like every value in them and they're unordered so if I do like for example if I print uh set 1 2 3 let's say equals set21 even though they're in the wrong order this should print true and we can test that so we can print it and then we can just return like false or something so we can look at this really quick uh false so if we run this and we actually get out of this thing I always forget how so you can see that it this is indeed true so you can compare sets you can compare arrays you can compare whatever you want and it will compare by value so what this allows us to do is we can use this so we basically need these two things to be true so we can just say like return these two things have to be equal right because these are two sets and the two arrays of values have to be equal but they have to be equal in like you can't really compare uh array the way array comparison works is you will compare like value by value right so if I do like let's say I want to print let's do one more print just to show this like if I print this let tab so if I print like 1 12 3 equals 321 this is going to be false right because the array is like it Compares element by element so we can see here it's false but if I do 1 2 3al 1 2 3 this will print true so in Python we can literally just pass in the Ed values here right so we'll just sort the values in increasing order and just say are they equal and it will do it for us instead of having to go value by value so you can say sorted counter 1. values equals sorted counter 2. values and so what the values will be is it will be all of the values in the dictionary and we will sort them so is this sorted array equal to this sorted array and all the keys are exactly the same if that's true we can return true so let's run that like I said you can definitely code this up with like more lines but this works too and I think it's not super hard to understand what's going on um yeah and we can submit so you can see it's pretty good roughly the same as other stuff run a bunch it's like all over the place again um but yeah and the nice thing about this once again is since all the letters I think are let's just double check they're usually just lowercase English letters right so lowercase English letters which means that these counters are very cheap to make so for the time to build these counters is O of let's just say word one well actually here um you can do like a you can do something quick to you can also just have a little thing here like says like if length of word one does not equal length of word two return false so you can add that in as well it does not equal um oh yeah so if we add that in now we basically avoid the cases where the letter counts are different right because you still have to have the same total count of letters to have an anagram so now basically word one and word two will always be the same length so you could say like this is O of n where n is the length of word one because you're essentially looping through twice the length of word one and yeah the nice thing is even though we are sorting these values the values are only 26 values maximum right because it's only lowercase English letters so even though this is 10 to the 5th these dictionaries will only have 26 Keys 26 values of sorting 26 letters is super fast so time is oen here and space is o1 because like I said uh there's only 26 letters so it's constant no matter how big your word is you can only have 26 letters and this part is also only 26 uh an array of 26 values so it's constant time and the sort is constant time as well which because it's only sorting 26 values so pretty good um yeah and the main thing is just to understand like what these things are and not too bad of a problem and I think that should be all for this problem so if you did like it please like it and please subscribe to the channel like always and I'll see you in the next one thanks for watching | Determine if Two Strings Are Close | find-the-winner-of-an-array-game | Two strings are considered **close** if you can attain one from the other using the following operations:
* Operation 1: Swap any two **existing** characters.
* For example, `abcde -> aecdb`
* Operation 2: Transform **every** occurrence of one **existing** character into another **existing** character, and do the same with the other character.
* For example, `aacabb -> bbcbaa` (all `a`'s turn into `b`'s, and all `b`'s turn into `a`'s)
You can use the operations on either string as many times as necessary.
Given two strings, `word1` and `word2`, return `true` _if_ `word1` _and_ `word2` _are **close**, and_ `false` _otherwise._
**Example 1:**
**Input:** word1 = "abc ", word2 = "bca "
**Output:** true
**Explanation:** You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc " -> "acb "
Apply Operation 1: "acb " -> "bca "
**Example 2:**
**Input:** word1 = "a ", word2 = "aa "
**Output:** false
**Explanation:** It is impossible to attain word2 from word1, or vice versa, in any number of operations.
**Example 3:**
**Input:** word1 = "cabbba ", word2 = "abbccc "
**Output:** true
**Explanation:** You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba " -> "caabbb "
`Apply Operation 2: "`caabbb " -> "baaccc "
Apply Operation 2: "baaccc " -> "abbccc "
**Constraints:**
* `1 <= word1.length, word2.length <= 105`
* `word1` and `word2` contain only lowercase English letters. | If k ≥ arr.length return the max element of the array. If k < arr.length simulate the game until a number wins k consecutive games. | Array,Simulation | Medium | null |
35 | one so today I'm here to solve this search insert position problem it's a lead code daily um and we have been given a sorted array of distinct integers and a Target value we have to 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 four log and runtime complexity it said that we have to write o log n so that means we will have to do binary search linear time o n won't be like possible uh since it's going to be o of n so let's try to do it binary search that is offload login if you were to do it in all o of n it would be simple we would like go from here one by one since it's in a sorted array so you would just simply keep going until we find a bigger number and if we find a bigger number without finding our Target we would just simply return uh this index -1 so in this case uh we uh this index -1 so in this case uh we uh this index -1 so in this case uh we will find 5 and so we return the index 2 and in this case we don't find 2 instead we find that 3 that is bigger than 2 so we'll return this index as our insert index that will be 1. okay let's start coding for binary search we know that we have to do take two pointers left and right and made uh like start and end and made so let's just start with it let's start equals to 0 initially left n equals to nums dot length then while start is less than equals to n um we calculate mid that Mid First let's check the constraints first turn is to power 4 so uh it will be like start Plus start divided by 2 let's make it since it's JavaScript let's make it float math Dot floor we don't have to make the floor we just have to make this one okay why is it showing an error ah I missed an i if now we check if we have found our number if mid is equals to Target with a turn net we return the index if we have found the number otherwise what we do is we see if mid is um less than Target so in that case that means our number will be inserted uh like after this number so we will have to move our start so suppose we have to find file here so what we will do is we will take mid will be 3 emit a this is smaller so we skip this and start from here so we make start as he made Plus 1. and else we make a equals to net minus one and then if we can't find it then we'll turn it starts you know let's see if this works so for this example let's see so we have start as 0 that is one we have end as 0 1 2 3 as 6 and we have Target as five then our Midfield please 0 Plus 0 plus 3 n minus star three minus zero divided by 2 that will be 1.5 since we divided by 2 that will be 1.5 since we divided by 2 that will be 1.5 since we take floor it will be 1 commit of one that is uh three since three is less than our Target we move start to Mid plus 1 so mid was one so we make start equals to Mid plus 1 that is one plus one which is 2 and then again with n equals to 3 let's remove this six we only look at the indexes for now and we calculate made as 2 plus 3 minus 2 that is 1 divided by 2 this will be 2.5 since we are rounding this will be 2.5 since we are rounding this will be 2.5 since we are rounding down so it will be 2 and then um this is 2 is 5. 0122 is it's 5 since then we come here and then we have found the target we return made that is correct let's look at the other example where we confined to okay oh here we have input nums one three five six Target is two so we start same and then we have made that is 3 this is bigger than 2 so we go to else and then we make minus um Mid minus 1 and will be mid minus 1 equals uh what is it end was Midwest three mid was one so we make it zero and start was also is zero start is also zero and is zero as well so in this case start and end is matching at the same index what we do is we calculate mid equals to 0 plus 0 image is also zero so this will return made as zero 0-1 this is less than Target one is less than Target so what we do is we um make start as mid plus 1 so start moves to 0 to 1 it should work let's see ah it didn't work for some reason why expected is 2 and we return 5. we returned matters oh yeah right we were we had to compare is made of nums this should work now let's see yeah it worked nice so since it's a binary search we have a Time complexity of O of log n it was not so straightforward but yeah if it if you were to do it using a linear search it would be much simpler and we could do it like just keep searching keep looking one by one and then once we find one larger number we return it as the index but since we had to do it in off login we used binary search it was pretty simple and pretty straightforward yeah thank you that's all goodbye | 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 |
329 | hey everyone in this video let's take a look at question 329 longest increasing path in a matrix this is part of our blind 75 list of questions so let's begin in this question you are given M by n integers Matrix so Matrix array which is M by n and you want to return the length of the longest increasing path in Matrix from each cell you can either move left right up or down and you cannot move diagonally or go out of bounds basically here the longest path is one two six and nine that's increasing and looks like it has to be strictly increasing you can see that this path is a length of four which we return here and here it's three four five six similarly Atlanta 4. and at the minimum actually the path will be one right so at the minimum we can return a length of one okay so this is our basic like graph type not graph but like Matrix type question but we will use one of the graph type algorithms specifically we can use DFS but why did it come up with DFS well usually when you see these types of problems and a DFS is a good choice whenever you want to find the maximum something the minimum something especially when it relates to some sort of Matrix or some sort of Greater grid of numbers so that's one thing but another thing is it just makes sense right like for example if we have like one over here then I want to try to go as far as I can along this Matrix to find out if I can maybe extend this one and form a longest path so that's how kind of DFS comes to my mind now this question if you think if you've done the number of islands question you know that in that one we also did DFS but one of the differences there was that we did not have to do TFS off of every single cell right in the number of islands question we only did DFS from the islands themselves basically wherever the entry was a one here we don't really have any of that like constraint right here it's not really clear to me that we can only do DFS from a specific location really here we have to DFS from all of these cells because there's nothing that tells me that you know like only I can do DFS from one location so in this case I have to DFS from every single cell so that's something that's kind of different based on um compared to like number of islands now otherwise if you just think about this question it's not really that hard if you have done these types of questions before so I know this question is labeled labels labeled as hard to put if you've really done these types of questions before then they often try to follow like the same sort of invention or same sort of structure in terms of the code but let's take a look at how this can work right so let's assume that we start off over here obviously we won't start our DFS call from here we'll start from over here but let's just assume that we start from here so then what can we do well we know our minimum by at minimum our answer will be one right at minimum our answer will be one what can we do well from this location here I can travel either up towards the six right towards the one or left towards the two now I don't necessarily know which one of these is going to give me the longest path right I don't even know if any of these are valid for example if I go to this side over here this is not valid right because basically I cannot form anything here one and one this does not work one and six work one and two work but one and one does not work okay so we have that information so we need to somehow check like to see if the path is even valid in the first place and we'll talk about how we can do that let's say we go to the two here okay if we go to the two then the two works okay cool then the six also works and nine also works now if we go outside the nine then we're like basically like out of bounds right so if we go anywhere over here or out of bounds so what can we have our function return what can we have a recursive function return and if you really think about this one let's just say I'm at like a single cell right nine and I go out of bounds but then if I go out of bounds what is the length of the longest sequence well you may think it's like zero right because we're going out of bounds but in reality the length of the sequence over here is zero like if you go out of bounds the length can be zero but when we include this nine over here then the length of the longest sequence is one over here the length of the longest sequence basically a one now we backtrack now we're on the six here what is the length of the longest sequence well whatever this will return the length of the longest sequence from nine and onwards so we see from nine and onwards the length of the longest sequence was one and so if we were adding 6 to the sequence then it should be one plus whatever this one was so now it would be two again let's say we're at the two now and we want to return we want to figure out what is the length of the longest sequence well when we did a recursive call this call over here from the six from right above will return me the number two it will return me the number two now what I can understand from this is that if it returns me to number two which means that it is increasing then I'm going to add my 2 to this list and so it'll become through here the length of the longest sequence up till this point from Two and onwards is three again now when I come back to one here then I can see that from my left hand recursive call I was able to extend my longest sequence by three units now if I want to include this one here which I do then I can include it add in one more so get a total of four so that's how we go about creating our longest sequences and we'll basically keep track of the maximum one and return it in the very end so let's take a look at how we can do this and we like to follow our specific format or type of code structure we like to use for these types of problems so first thing I do is I always rename this to grid and it's an easier name to just work with then I like to determine what my rows and calls are and I can do this as so take the length of the grid and land the greater zero so that's my m and n and then I like to go through my rows and calls call in range zero to course and then what well we need to do our DFS call right and we don't have a condition like if clear that roll call equal one then do our DFS and actually here we need to do it from every single cell so I can do something like after helper I don't know what I'm going to put in here but this will be my helper right my DFS call and this should return to me the log the list like the longest increase in path starting from this index starting from this cell now let's say it returns to me like some sort of variable right like some sort of variable Pat so this is an integer now I need to basically check this path with my Global path to see which one is longer so maybe I'll have a global path here call it res and I'll set that equal to one and basically what I can do here is I can do res is equal to maximum of res or the path that I got from a recursive call here and then at the very end you can go ahead and return risk okay so that's our driver function let's see what we can pass in into the helper and a lot of the time our structure is going to remain the same so what do we need so we need the grid we need the row and the column what else do we need well if you think about this right like if we're on the 2 here how do I know that like this is an increase in path well I need to know the previous element right because if I want the two here the only way in which I can maybe even consider this path is If the previous number was less than a current number right which means that I can maybe go ahead and do my recursion here if I can't do that like if this number was a zero then I can't even do my recursion I just have to return so I need to know what my previous number is I will do that previous well so I think that's all we need for now but let's see if we need anything later on okay so first thing that we want to check is whether we're out of bounds or not right and so this is what we always do in these types of questions you can check number of islands we always like to follow this type of format so what we will do here is I'll actually just redefine my grid my rows and calls and this could actually be passed in but I just redefined them because I don't want my helper to be too large okay so what are some of the conditions we have to check well we have a like tiny little formula that we like to use so we say if row is less than zero a row is greater or equal to rows column is less than zero column very good cause if this is the case then we're out of bounds if we're out of the bounds what do we say well if we're out of bounds basically there's no path right so the length is zero end here would be zero what about otherwise well otherwise I'm on a cell and I want to check if the previous cell was smaller than my existing cell if it's not smaller then I can't really do anything I can't recurse from here right so for example it's like if we go from 6 and we go down to one well this is not an increasing path so I can't actually recurse from here what can we do we can check if red at row and call if this is less than my previous value right if it's less than or equal to really less than or equal to my previous value but we have something like this then it doesn't work we can return 0 here as well this means that from this index we can't form an increase in path okay so now that we have our base conditions out of the way what can we do well now we can go ahead and we can recurse let's assume we're at the six now we can request up right down left but let's actually just Define that so I would just Define this like this previous well and then we will fill this in okay so let's do left right up and then down okay so if I'm going left my column decreases by one if I'm going right my column increases by one I'm going up my column my row decreases by one if I'm going down my row increases by one now what is previous value here well previous value should now be my current value right this is what I'm passing in like I'm going from six to nine so I need to pass in the previous value of 9 as 6. so it'll be the current value which is and actually maybe let me just Define because I'm using grid at row and call quite a bit let me just Define like um OG here OG as in original as grid on row and Co and then I will reset this to just be OG okay perfect but now what do I know so if I'm at six right so if I'm at six so let me go back here and I'll actually remove all of this I need to add in this again okay so if I'm at six then I want to know what is the longest path starting here so what would these return well automatically we know that for the bottom case here in this case here it will return zero why because the number is the same or less in this case it's less the one is less and 6 is the same so that's where it overturns zero what about here nine well nine we can see that from nine we can at least do like we can at least like form one right like one is the minimum we can do here because nine at least we can extend at least like the previous one we can extend here so this will be nine right now let's assume that this is actually a 10 here just for argument's sake now what about the a what would the eight return well from the eight we can actually go down and reach this 10 over here right so this 10 and this 8 combined would give us a value of two so then this thing here would return what would it return well it would be one and two the maximum of these right plus the six because I want to extend six into the path here so it would be the maximum one and two which is two and then added one which is three which means this is the longest path six eight and then 10. so let's see how we can do that we can do result is equal to maximum of left right up and down but not just this we want to add the current path so we will do plus one and that's pretty much all there is and then we will return result to whatever the caller was because this will return the maximum path at the specific index so that's basically all we have so now let's go ahead and run this so we have grid roll call previous vowel so what should I pass in as my previous value well initially I need to pass in something such that the number I'm currently on is greater than previous value so what's the number that's everything is greater than what would be minus infinity right so minus infinity so now let's go ahead and run this code on our test cases to see if we made any mistakes okay so we haven't so let's go ahead and submit this okay and you'll see eventually that we'll get a time limit exceeded error now I will discuss the time limit exceeded error in just a moment but one more thing I want to discuss here is if you notice like other are other problems what we often did is when we went from one two and then it's possible we could have went back right so it's possible we could have had an infinite Loop we have to check this in number of items we have to check this in other graph problems and other grid problems why didn't we have to check that here is it possible for us to go from one and then six and then back to one and then basically this repeats Infinity it just repeats back and forth is this possible do we have to check for this well it's possible that we go back and forth but notice how if we go back and forth we would just return right over here so realistically like we don't even need to check this because we will return right away so we will not have the case where we just infinitely occurs we will maybe go from one to six and then six back to one but then that's it we will not keep going again and again if we want we could actually make this a little bit easier just kind of follow our convention in that what we do is we set Grid at row and call equal to select some arbitrary value here and then we can check if Grid at row and call is equal to this arbitrary value that means we visited this in the past so we'll just return zero and then once we are done this we can just reset Grid at row and call back to what it originally was and so we can try this out and we will see that this also works but it actually is not needed and so here I actually made a mistake because yeah grid arrow and call so here maybe I need to do something like uh minus one I need to add an integer here between string and int yeah so this one should actually be minus one and it looks like I can do that because we only have positives okay yeah so this is like something I can check for but I don't really need to but you know I can check for it just to kind of maintain our structure of how we like to do these problems now the last thing is timeline exceeded so the solution actually used to work before um like in 2021 but after they added in this we have to do memoization to basically fix it nope so in order for us to add memoization what we need to do is first of all we can pass in a dictionary here which will essentially be our memo and then here and all of these locations here and we just pass in the memo part of our function okay now what do we need to do well now we can basically check if row call in memo then we can just return ammo at roll call otherwise we need to Cache this so we will do memo at Rocco is equal to Res which is our answer and then we can just return memoiro call which is res in this case let's go ahead and run this test case to see if we pass okay we'll go ahead and submit and we can see that it's actually taking a little bit more longer than it needs to be it's taking about four seconds so even after memorization why is it so slow well if you take a look at what we're doing here we're creating a new memo every single time right we're creating a new memo on every single different cell but do we really need to do this or we don't right because let's assume like we have the answer to this cell over here the cell six over here maybe we got it in some sort of function well if we have the answer to this cell over here then that has to be the best answer right it has to be the best one because from our DFS call we'll try to visit every single cell we can so if this is the best call if this is the best answer then we don't need to create a new memo every single time we can actually just create a global memo and just reuse that in subsequent cell calls so we can do memo as dictionary here and then we can see that if we do it now it is much faster so we should be able to finish it within less than 500 milliseconds which we do so that's one of the things that we should keep in mind for if you can do memorization make sure we don't create a new memo every time if you don't need to okay so what is the time and space here so the time basically we're just going through the entire grid and you can see that memo would basically make us back out very early if we already know the answer so you can think of it as worst cases like o of M times n and kind of the same thing for the memo in terms of the space complexity it would also be o of n times m okay thanks for watching | Longest Increasing Path in a Matrix | longest-increasing-path-in-a-matrix | Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`.
From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).
**Example 1:**
**Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[1, 2, 6, 9]`.
**Example 2:**
**Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.
**Example 3:**
**Input:** matrix = \[\[1\]\]
**Output:** 1
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `0 <= matrix[i][j] <= 231 - 1` | null | Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization | Hard | null |
236 | hey guys how's everything going this is Jay sir he's not good at algorithms I'm making this video to prepare my interview in this video where I'm going to take a look at 2/3 sex lowest to take a look at 2/3 sex lowest to take a look at 2/3 sex lowest common ancestor of a binary tree we're coming a man in a tree we need to find the lowest common ancestor okay say like we're given a tree like this we need to find that comma root of 5 + 1 5 need to find that comma root of 5 + 1 5 need to find that comma root of 5 + 1 5 1 of course is 3 right yeah and it's lowest so how should we do it while full tree the first one great yeah recursion yeah let's find try to find the relationship between the final week path like 5 3 1 and the node itself what's the relationship between them right ok so for one node and the common ancestor of two nodes and there are two possibilities right the first one the node is not in the path let's say 4 6 & node is not in the path let's say 4 6 & node is not in the path let's say 4 6 & 2 come on won't be 5 by 3 it's not in them right if 3 is now in them then the common ancestor must be in a left tree or in a right tree right yeah that's for sure cool and now if it's if it is the common ancestor what will happen it means in left the tree there will be 1 5 or 1 right yeah there will be five oh one and then another one will be 1 or 5 so that 505 and 1 will be in separate tree right that's the case or of course itself must would be itself might be the target right so 4 5 & 3 the common ancestor right so 4 5 & 3 the common ancestor right so 4 5 & 3 the common ancestor will be 3 so it means that the target would be in left tree or uriah tree or itself so that's our relationship so for recursion how we do it well for case like five industry and one in right tree we cannot determine the result until the recursion of these two sub trees returns us the result right so what we need is that if the tree has five if the tree has one right so when we quote create our recursion method we are gonna return three things one the LC a node right like four five we need to return the node and has Q P and has Q right if we get Li three we can get a recursion function so let's try to do it when we get when we walk on a node what we do well first if it's Newell which will happen we just return the node is lower right there nothing has B force that's cute force right now if node it's not new we will go I will do what we what first check in the left tree right it's LCA left has P left as o oak left has P left has Q this will be walk note left right if L see a left if the talking common SEC is found then what well we just return them all right we don't need to travel to go to write anymore like for three already get five then we don't need to go to a mystery it's a waste of time so just return true right when this is true these are these two must also be true cool if left is not found then we try to walk to the right the same if a common SS is found in the right tree we'll return it a true now what's the case now it means there's no common ancestry left tree or in a right tree right so for this node what will we do well let's say cast a speii current node has BT right coventry if it has P or not it means if left has tree if let it has P then it must be happy right if right has B then of course it's also it's happy or the root itself is B right so it's node equals B it's has P then Q is the same let's ask you right ask you or node equals Q now when we know for this node if it has P or Q or not so if most we has P or Q we were returned the note it's the common ancestor node right so yeah true for the other cases we return new all right it's not the common ancestor and that we return has be and has q well this is a perfect recursion is done now let's return walk route I think you should work Oh undefined okay I should review one more time before I run the code anyway let's take a look walk route okay for note if it's new or we return new or false polls its high-speed know if left has been left high-speed know if left has been left high-speed know if left has been left asked you walk left mmm cool if you found we return yeah and then we do right happy right ask you what to write if it is right okay and then has P or has Q if we has P means let us be or rat has be or have noted selfie speed let's ask you right ask you node equals Q if SP and ask you if both P and Q are industry then I say this is that oh I think we need to return the first statement right cool yeah you're accepted and let's analyze the time and space complexity time every node out actually has been Travis for once right so obviously its Nino time for space we actually this walk would be like three five six and then we return to five and then two although three five and two six two seven two four and nothing is fine we got two three one and zero right the zeroes check let's try to log the note I think it should be three five six two seven four one zero eight all the nodes are Travis I think Oh No Wow five three seven one eight yeah so yeah for this one is linear time space while for each Travis actually we use an array to keep the result but actually the maximum depth of the call stack would be worst linear time linear right worst is linear like the tree will be a straight line and we use this us array to store the result but this actually is we return the result as the recursion so actually it's linear space there will be no nothing like if it's not like a three n right we use three but it's not because we first of all gets left and then we do the calculation so the arrays won't be recycled in linear time it's near space well I think there's another solution for this recursion I think there was another way called like much more not much more but a little easier to understand it's that for like we are going to search to was to the common ancestor of two and 0 what's the common node well for every node industry there will be a path right from the root to it like to there will be three four two and for a three five two four zero three one two so I think what do we need is just to search on the tree search for specific and node and get the path and then we just compare these two paths and find the common ancestor right this is another approach and try to do that its first I'll create a function to do the search well what we do is to will receipt you know a note as a lot as a parameter and a return what we turn the path up to the load well when we our search will of course really is recursion will well go to the root first and then go to five so we meet - we need to return as return it we meet - we need to return as return it we meet - we need to return as return it and how we will collect a result we actually need to pass down the path right so actually for search there will be the extra which is path well so if no is what we just do the return nor right the path is nor and then if it is not the newel then what do we're first to research on the left right so cost laughs searched equals walk will search node left with what with a path contact no oh before we searched if itself is the target we need to return right away so if node equals oh we forgot to pass a target my bad if node is tuck it will return path call cut target all right Andy itself is not we search on the left but we pass a new path with the note in and then we say if left is found it's found in the left and we have the path right then we just return the path return this if it is not found in the lab we search on the right oh I do it to the right search pull search node right don't forget it target path contact no well this is the last chance so we were just to return right searched so this is our search method so for P and Q I think well path P would be search routes P right empty array as the third parameter path Q search now we have two paths right it's fight first log it mmm no we don't need so for the path muscle business we must be have the same first element as the root right because every path start from the root so let's say let's result B and Wow actually the common ancestor will be the last element which is the same in both paths right so for a while loop each should end that's where it should at and it should end if you end when they are not the same so path while path p 0 equals half q0 when they are the same we set it to either one of them and don't forget to shift them out half Q shift and finally the return the result run the code seems like working for this case let's try to submit but oh we are running out of memory this is out of memory let's try analyze the time and space for time we search the worst case is out of the node so for search and then the second node Wow all of the know and we would compare your once again what's the worst case well worst case is odd of the node so it's actually triple and still in your time right for space let's see we use for each search we are receiving a path and I create a new path so different from the previous one when these recursion goes down from roots that leaf node the space is used the extra space a packed it will be so reference to it so you will not be recycled it won't be not BG seed and we will this extra space will be in the whole lifetime so the worst case will be all the node are a search and the path what would will be the path wow the path would be there will be a path will be linear to the depth right so 4 1 node it will be 1 plus 2 right plus the dot plus n so it actually is N squared this is the space plus this is a cost AK plus linear right this is the worst case well this is why you see it says the hip is out of memory we are actually using a lot of out of memory let's try to improve it improve food search first while the problem is that we're keeping the path right this path actually should be recycled we're only searching the target there's no need to keep an extra space for each node right we just to pass the pass it down so here contact we should not use them we should use path well if this node is new or wood of course we use we return new law and now we could just a path push the node in right now the path has no nodes so here we just return the path and the four-lap search we search on the and the four-lap search we search on the and the four-lap search we search on the path if lat if searched when you return it if right we sort ass and the here if right we found in the right we return path no it should be where I've searched well it's the same reference to the path so actually there will be only one path right so when left and right are all down it means actually there is no element there's no target with down in this pattern right so we need to go to the sibling like four five all these found audios Travis so we need good one well of course we need to do what we need to pop the five out right so this should work cool this submit well accept it you see for the time in a space for the time it's the same for space we're not using extra like a square you see we only use one path so this path will be actually maximum linear right so it will be linear plus the cost AK so cause so it's linear space why you see since we're using the one path wait why don't we just to write the path in a global way is this better but hmm this path acne this is better because search will be a standalone function without any dependence if you set create a global like global path array we search we push we return true and if we return so actually it's the same anyway let's try to write it if we write it another way of global path global one all right okay so let's say there is a okay we use a recursion okay mm-hmm a recursion okay mm-hmm a recursion okay mm-hmm no I'll say create a new a path empty so there's no need to path we don't pass the array if node is no of course return what if we turn but we need to return something it must be there well we could return new all no we should not return the wall we should just to return empty okay and then we push on no there if no this sub is target we return the path but this is globe all right let's use slice so that when we are calling search PA search Q no we should return path if we okay I just try to do I'll have search the same got the path just to return to and here we return false return true and when we were found this at last nothing is found so we puppet cool so this actually was stopped when the target is found so we can collect the path right so search with P cost P plus path we slice it okay we could use path and the reset it and then serve true to Q wow this is actually a little ugly oh there's some problem we search right target we return false okay so she would be so tribe we got three with push it nobody it's not target we search left target and it is target so we turn true and four three left is found we return true and search right if I searched return true if not we'll pop it so search root P and we get the path let's reset bad so such cute oh I see what happened this while loop doesn't end so actually cool this is another except approach but it's kind of ugly so I'd prefer this one pass everything needed to the recursion function as a parameter this is actually yeah cool so I think this is called backtracking we found something if we found we just returned if not it would go to next one but we need to reset we said to the we set the cache data which is I remember oh I didn't oh cool I forgot to come leave the previous solution anyway you know what I mean so this is this one okay this one a copy chime near-space yeah so this one is uh chime near-space yeah so this one is uh chime near-space yeah so this one is uh I would recommend it for this kind of existence check-in recursion we need to existence check-in recursion we need to existence check-in recursion we need to stop the recursion as soon as possible so we return a fly or anything to let the parent know that okay I found it just to stop going to my siblings for five we found it so you don't need to go to one I've found it so for five it tells three with the flag right if you need we need to find all the solutions it is not like this we the parent won't listen to the child we just to continue searching the siblings so this is a trick this is the technique we're using in binary I mean tree search I think hope it helps so see you next time bye | Lowest Common Ancestor of a Binary Tree | lowest-common-ancestor-of-a-binary-tree | Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.
**Example 2:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` will exist in the tree. | null | Tree,Depth-First Search,Binary Tree | Medium | 235,1190,1354,1780,1790,1816,2217 |
1,846 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem maximum element after decreasing and rearranging so we have a pretty fair problem today and that's good because I'm a bit Rusty we are given an array of positive integers and we can perform some or none operations on the array to satisfy a few conditions before we get into what conditions we need to satisfy I like to look at the operations that are actually available to us and that is we can rearrange the elements in any order and we can also decrease the value of any element to be a smaller positive integer we can actually perform these operations as many times as we want after we are done we just want to return whatever the maximum possible value in the array could be after performing these operations now the catch is the conditions that the array has to satisfy one of them is that the array has to start with a value of one second is that the absolute difference between any two adjacent numbers has to be at most one so in this case it is at most one for all of the adjacent pairs now if I make a couple values equal it's still true like the maximum absolute difference between these is less than or equal to one and it has to be at most one so that works the very first thing you might think is well if the first element is one and the values kind of have to be consecutive well can we just take the length the array and return that as like the max number because we're starting at one and we're going to be kind of doing plus one each time no we can't do that and this example kind of shows you why because this is a valid array and even the first example here shows you why because here we are given these numbers and we can rearrange them in sorted order like this 1 2 now it's perfectly valid and we can't make the maximum number in this array any bigger because remember we can't increase the value of a number we can only decrease it so in my opinion this problem isn't super complicated the hardest part about this problem is really making sure you understand all of the requirements that you don't miss anything so with all of that in mind it seems like sorting the array is definitely helpful because we know that the array must start with one and if we sort the array it'll be pretty straightforward for us to know if we have at least a one or maybe we have something greater than a one we can't possibly have anything less than a one cuz the integers are positive so don't make sure not to miss that and obviously the fact that we want to arrange them in such a way that adjacent values have a difference of at most less than or equal to one and the best order to put the values in to ensure that would be in sorted order so once we have that though once we have the elements in sorted order what do we do next well let's just run through it without even thinking about the code let's just manually solve the problem okay we start with a one that's good because if this was greater than a one suppose it was a two we would have to decrease it down to a one and it's not like we'd have to count that as an operation because we don't care how many operations we perform we just want to basically get these values in an order that satisfies these conditions so that's good so far now we have a two well let's compare it with the previous guy the difference is definitely less than or equal to one so this is good so far now we have five here now We compare these two the difference is definitely not less than or equal to one so we have to change this number because we can't change this we can't increase this we have to decrease this how much are we going to decrease it by we actually have two choices believe it or not we can if we want to make it a two or we can make it a three both would be perfectly valid but which one do you think is going to lead to a maximum possible value in the array probably the bigger one right so that's what we do we make this a three and now we're here we compare seven not with five We compare it with three and we check is the difference between 3 and 7 less than or equal to 1 nope it's not so now again we have those two choices we can make this a three or a four and of course we're going to make it four so that's how you solve this problem with kind of just like manually by hand now what's the pattern that you noticed in terms of code well we only like every time we look at a value we only need to keep track of what the previous value was that's like the first thing to notice and second is when we do decide to make this element smaller we always set it and actually that's not super obvious yet let me change this example slightly to illustrate the second Point let's make this a two and now a two now what do we do these two are good now when we get here what's the difference between these two it is less than or equal to one so we can't decrease this there would be no reason to do that and we can't increase it we can't make it a three unfortunately so we leave them as is and when we get here we do the same thing these two are equal so that's fine and now we're done this was the largest value the last value is pretty much always going to be the largest value so now what do you notice about what we're doing to this second one well it's not super obvious but we're always taking it and setting it to the minimum of the previous Value Plus One or the current value let's just call that array at index I the reason we're doing this is because in cases of a tie we would need it to be set to the value that it itself is but in cases where this value is bigger something like a seven we're going to set it now equal to the previous value which is 2 + 1 so then it previous value which is 2 + 1 so then it previous value which is 2 + 1 so then it would be a three so that's where I'm getting this formula from that is pretty much all we need to code this up now in terms of time complexity yes we are doing a linear scan but before we do that we are sorting the array so the time complexity is going to be Big O N log n so now let's code it up so first thing I'm going to do is just sort the array and then we are going to start iterating over the array so for n in the array we are going to do that minimum formula but we actually do not need to modify this array because remember how I said we only are keeping track of the previous element so instead of actually modifying the array in place I'm just going to keep track of the previous element and by the time we finish the entire array we can just return that previous element because like I said the last value in the array is going to be the return value it's going to be the greatest in the array so what should we initialize this to before I even do that let's just write out the formula previous is equal to the minimum of previous + 1 and the current value that previous + 1 and the current value that previous + 1 and the current value that we're at in this array this is the formula remember but why are we assigning it to previous because we're taking the previous number because sort of in this context this is the current number and we want to populate this for the next iteration of the loop so that's why I'm assigning it to this variable but this is kind of the tricky part because remember how they said the array has to start at one so if it doesn't start at one suppose it starts at two we would want this formula to evaluate to one so how can we do that well think of it like this we are given an array and to the left of that array we're just kind of putting an implicit zero there we're just assuming that there is a zero that comes for all of these values in sorted order so that's why I'm going to set previous equal to zero because it will ensure that this 0 + 1 evaluates to will ensure that this 0 + 1 evaluates to will ensure that this 0 + 1 evaluates to one so if this number is bigger if it's a two this will evaluate to one and then this will sort of be one as well so that's pretty much the entire idea of this problem that's the code so now let's run it to make sure that it works and as you can see yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out N.O got some cool features check out N.O got some cool features check out N.O got some cool features coming and a new course launching probably tomorrow thanks for watching and I'll see you soon | Maximum Element After Decreasing and Rearranging | maximum-element-after-decreasing-and-rearranging | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null | null | Medium | null |
1,675 | hey what's up guys this is chung here so let's take a look at last problem of this week's weekly contest which is number 1675 minimize deviation in array it's very interesting i would say it's a math related problem basically you're given like an array numbers of n positive integers right and then for each of the integers you can perform any of those two operations if the element is even you can divide it by two if the element is odd you can multiply it by two and then the deviation is the array basically the deviation is the maximum difference between any two elements in this array basically the deviation is the max is the difference between the maximum number and the smallest number in this array after this operations and it asks you to return the minimum deviation right minimum deviation among all those kind of results right so and here are some examples here so let's say we have one two three four and uh as you guys can see so the current deviation for this one is three right which is four minus one is three but if we divided four if we divide four by two then we have one two three two right then the deviation is what is 2. but then we can continue increase the this i increase i by basically double multiply two with resistance with this one here which we have two three two and then finally we have the our final answer which is three minus two is one so that's the first examples and similar for this second example here right basically we uh we increase this one to two and we decrease this 20 to five right and then the final answer is three so for this problem you know the uh since we have two ways you know so if you make some observations right basically if this number is even it means that it cannot be increased anymore so because the even number can only be divided by two which is can only which means that an even number can only become smaller same thing for out number odd number so an odd number cannot become smaller he it can only become a greater by multiplying with two right so and since we have these two options it's gonna be hard for us to uh to maintain these two options at the same time right operations at the same time so the way we're solving this problem is that we have to fix one of those problems or one of those uh conditions and then we would we'll either would either through we'll try to let's say if we fix the uh the max size and then we'll and then would basically will try to decrease the uh the maximum values right and if we fix the uh the smallest values and then we'll try to increase the smallest values either way it's fine so base and the way i'm doing here is basically i'm going to maintain like a priority queue which will stores the uh which will maintain the maximum value and then i do it by initializing by uh by converts each number to its biggest numbers first so which means that you know if this number is like is a even numbers then it's already at its maximum values then i'll just simply insert into that priority queue but if it is odd numbers as i can just uh so with this number the maximum number for this out number will be uh will be outnumbered times two that's going to be the maximum value for this number right and then i do this after the first four loop here i have a priority with all the biggest numbers for each of the digits right and then in the front from here i'll be i'll try to uh basically decrease the maximum numbers from this priority queue right by half while maintaining the minimum number as well and then when we uh then what's going to be the exit point which means that you know we're trying to we keep trying we keep uh decreasing the uh the maximum values by getting the current maximum value from this priority queue right and then let's see if the current biggest number from this priority queue is the even numbers and then we know okay so we can simply uh do a divided by two because we know we can decrease we can change the current maximum values by dividing this current max value by 2 and then we'll push that the new value back to the priority queue but if the current max number from the product queue is even numbers let's say if it is seven then we know okay so there's no way we can decrease seven because for every seven we can only multiply by two then we can simply break the while loop but if this is six and then we'll just we can simply uh divide it by three and then we will just uh divide it by two now we have three and then we'll push this three back to the priority queue and every time when we have a new numbers here we'll also uh like update the minimum values because that's how we uh we get our we get the current deviation of the uh of the array so um i know i don't know if i explains clear enough but uh maybe i'll try to explain a little bit more so like i said you know the priority queue here right i'm maintaining like the current maximum numbers the current max numbers for the for this array right i'm using the prior queue because that's the priority will only take a long log n time to update the current max number right so and i'm also i also need to maintain like the minimum numbers right so i'm for the minimum numbers i'm just going to use like system i'm just going to use the uh variables to maintain that so at the beginnings i'm going to convert each of the digits number to its biggest possible values and then i'll push it into the priority queue so that i'm sure i have the uh i have the maximum values for all the possible uh numbers by doing these two kind of operations and from there i can just safely try to decrease that max numbers and then while maintaining the deviations right the minimum number and plus the deviation so in nums so if the num divided by two equal to zero which means these are even numbers then we can simply uh i'll just do a heap q dot heap push right priority q and i'll just simply push this number because we i know that's going to be the answer the sorry that's going to be the max value for this num and then i also maintain this minimum numbers um the uh the minimum dot num right else it's a odd number else right else it's a odd number which means we need to multiply the number by two if we push dot priority q dot num times two oh by the way sorry so since i'm maintaining i need the maximum value from this particular but in python this product by default it only can give us the minimum numbers that's why i need to do a minus i need to reverse this the signal at the sign for this number so that the priority will give us the uh the biggest number right same thing for this thing i'm also going to maintain the minimum dot now the number is num times two right that's going to be the so now after this after the uh this first while loop here the priority queue probably zero right the product of zero and the minus right of course minus priority zero will be the biggest not the biggest possible numbers right for this uh for this nums here and then all we need to do is that just that we will just try to uh decrease that number right one by one so i'm going to have answer equals the system dot max size and then the uh while the particle is not empty right we have current so the current is what is the uh the minus uh the heap q dot heap pop right because this is going to be the current max numbers and then i'll do a minus right so every time when we pop that out right we'll update the answer right answer dot is going to be the minimum of the answer dot current minus the minimum right this is the current our current deviation because the current one is the current maximum and the minimum of course is the current minimum and then if the current divided by two is not empty right it's not zero it don't we know that the current is odd number means that there's no way we can continue we can decrease our mac the current max number anymore right and then we can simply do a break here otherwise we push that back right hip dot priority q and then we do a minus current divided by two right and then after that we don't forget to max to update minimum right minimum is the minimum dot minimum current divided by two right and then in the end we simply return the answer all right so if i run the code do that oh here okay if i submit yeah okay so it's passed right so how about the time complexity right so the time complexity i think for this part is pretty straightforward that's just o of n so we can ignore this part so the most significant running times right it's right here i mean the so the way we're defining this we're calculating this thing is like this let's say we have n here right so n is the length of nums here and is the length of nums and since we're doing like this current by two right let's say the max m is max of the numbers right so how many i mean how many numbers we will be they will be putting into the priority queue so we will have at most we'll have like uh so for each number so anyway so the worst case scenario each number will be putting into this will be put into this priority queue one time right and for each numbers we have n here right and each number it will be decreased i mean by half and then it will basically push back to this product queue again so that's going to be what n times log m right so that's the uh the total numbers the total number of elements we will be pushing back will be pushed into this priority queue because we have n numbers and each number can have up to log m i mean new push right and then the uh so the last one is what the last one is the uh within the while loop we have like the heap pop and heap push right and each of this will take what will take log end time right because the worst case scenario will have n in its priority q and then this the uh the hip hop and he hit push will also both take a log n so that's why the total time complexity is this it's n times log m times log n right and space is what space is just o of n because we will just have this particle which would take like at most o in space yeah i think that's it i mean i think this problem is pretty tricky because you know the uh we you have to find out the uh how can you fix one side basically right you have to fix either the minimum possible values for all those numbers or the maximum possible values of for all those numbers in this case i use the maximum possible numbers and then once you have that one you can try to decrease that max numbers one by one right while maintaining the uh the minimum number along the way by you by using a priority queue uh yeah i think that's it for this problem and thank you so much for watching this video guys and stay tuned see you guys soon 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 |
664 | hey what's up guys this is jung so today uh let's take a look at lead code problem number 664 stringed printer so this one is a very interesting problem so you're given like a stringed printer and the printer follows following two special requirements so the first one is that printer can only print a sequence of the same characters each time and second you know at each turn right the printer can print new characters at any of the locations and then it will cover the original existing characters which means that it's going to overwrite the uh the existing characters so and here are some examples right so we have examples one here right here we have the target is aaa bbb oh sorry and here you ask your job is to count find the minimum number of turns the print turns so that we can get the uh this input the final answer and in example one here right we have a and bbb so the final answer is two why is that because i mean there are like different uh multiple approaches for this one so the explanation this one gives you is to print the three a's all together and then print b after this right and another option is like to what we print six a's in total and second time we print three b's starting from here right so this will also give us the uh the same result here and the example two here right so we have like uh aba right so in this case uh i think it's kind of obvious that it's obvious that so we print three a's first and then the next turn we just print one b right in the middle that's why we got uh we got a two here and so there's a hint he says the length of the given stream will not exceed what exceed 100. so actually this one is a very pretty strong hint right it means that you know the time complexity for this problem should be o of n cubed but okay we can just ignore this one for now but so let's think about the strategy right i mean at the first glance this problem is i think it's really kind of uh confu a little bit confusing and hard to get the point right because they're like different ways right we can print any letters any same sequence of letters at any locations so how can we approach to the final answer i mean i think one of the ways to approach this kind of problem or not you know what especially when you don't have any clues is that you know maybe try to find just the stupid just the worst way or the stupidest or the most naive way to print this result so what's the most naive way to print this the result that is we print the letters one by one right so for example we have an aba here so the first time we pre we print a second time we print b third time with print a and this will always guarantee us we can print out the final answer right and but this will not give us the best the minimum turns so from there on from here i think the next thing is that you know how can we uh improve this to find a better strategy actually i think the example two here it's a pretty good example that can it's kind of obvious to us that you know is if we have multiple numbers right uh multiple like letters for have the same letters i think the approach is that we may want to print those letters first so what i mean is that you know the uh so we have a let's say we have a xx right then so let's say we have another a here right um yeah so it doesn't really matter like what the others uh letters are at the moment so i'll oh let's take a look at these two letters here so we have two a's so what's a better strategies other than print the letters what uh one by one is this what is we basically will try to print aaa right we'll try to print all a's here because in this case we can cover right we can cover the uh basically we can get two a's in one turn and then the remaining parts is that we just give it to the uh and then the next one will try to print the remaining parts whatever it's left right what's what average left right in the middle and then we have another parts here that's the remaining parts we also need to print and at this moment i think for i think it's we can define like a dp here right so the dpij means from i to j the minimum turns right print from i to j the minimum turns what's the minimum turn to print the letters from i to j so for the state transition function right the uh you know so this one is obviously the most important one so which means that you know we have a dpij equals to what equals to the uh the dp i let's say that here we have a k right i j k minus 1 plus d p k plus 1 to 2 j the second part is kind of obvious right because we have we need to print them anyway that's the k plus 1 to j so for the first part um so what k minus 1 is also obvious but y i right y i not i plus 1 right i think some people some of you may have the question is that you know okay since our maybe our strategy is to print uh this aaa first right and then we'll try to print the middle one so why not have like a dp of i plus one k minus one and then plot plus one right so that's gonna be uh maybe and that's another valid state transition function but that's not percent true so why is that because you know let's say we have like okay yeah here's a good example we have a aaa let's say from a to eight they're like they're all a's so let's say the uh the those four axes there are they're all a's so let's we have i and j here right so if we're using like this kind of dp i plus one right i plus one k uh k minus one and then we do a plus one in the end so we have this one basically we're seeing okay we're assuming we're going to print two eighths two eight that's gonna take one turn and then we're gonna try to print the middle ones right but either keep doing this a here so what we have we will have instead of one here we'll have like maybe three because actually for all a's the what's the gonna be down so for that's gonna be one because all we need is to print it once because we can cover up all these kind of scenarios of sorry other letters but if this our state transition function is something like dpi plus 1 k minus 1 plus 1 basically that's not always the case no it makes sense you know if the uh if the number is something if the lighters in the middle is something like a b c d a i'm sorry b d c right so if that's the case you know so this i plus 1 k minus 1 plus 1 seems fine right but that's only covers some cases but for not all cases that's why we cannot define a state transition function like this because we have like this kind of uh aaa case okay so that's why the way we're defining the state transition function is that you know it's like this so we're not considering that plot plus one because we don't know if that will be an additional turn for sure or not so what we can say is that you know since this a and a they are the same right so to print from i to j is equivalent to print from i sorry from i to k is equivalent to print from i to k minus one because you know it's kind of obvious right because we have another a next to k minus one if we take like let's say three times to print from i to k minus one so we should also extend we should also print another a until k because this a and a they're the same so we should like uh cover this a i mean as well that's what these are like the dpi k minus one means you know since we're defining this uh state transition function like in this way and we can cover this case right as you guys can see here right so to print the print this a to a is equivalent it's the same as to print this a to this a and then this one is the same as from to this a and then to here right and in the end we only have one that's why this state transition function works and yeah i think that's basically going to be our state transition function and this part is kind of obvious only the only thing we need to be careful is that you know k minus one might be uh greater than j right so let's say if the a is in the end right so if x so if here if we have a here so then there's not there's nothing uh next to a here so this part should be zero right so we can just simply do a check yeah and that's basically the state transition function and like i said you know that's only the scenario when we have like a matching letters with the same i here that then we can use this state transition function right what if there's no a's at all what if there's nothing to be matched with a how to handle that case right because here we're saying that okay we're saying we have a k somewhere uh okay i like after i hear there's a k so that we can uh we can split this dp but what if there's no another a at all then what's gonna be that how about that one so for that one we're going to be a 1 plus or going to be a dp of i plus 1 to k and then we do a plot plus one sorry i plus one two to j so this one means that you know the uh if there's no uh matching letters for the eye sliders then we have no other options but to print these sliders by itself so print by printing the letters by itself we have one right and the remaining since we're only printing these one letters the remaining string is from i plus one to j yeah so that's basically the final stage transition function here and yeah we can start coding here cool so and so we have n right equals the length of s here and then we're going to define a dp right so dp since we're getting the minimum i'm going to initialize everything to this uh to the max system maximum for it's going to be a two dimensional uh array here right and oh i think one thing i didn't have to mention that is that there are some base cases so the base case is like if there's only one letters right it doesn't really matter what letter it is so it's going to be always one turn to print that letter that's why we can initialize some basic cases here basically from i from 0 to n here we can always initialize the dp i to i with to the value 1 so means that you know to print each letter separately we always need one turn okay so basically that's we have a we have already handled all the length equals to one case now we can basically start looping through from length too okay oh by the way so the this looping the outer loop is the length is a common technique if we want to uh loop through the uh all the combinations for like the range i to j basically from the outer loop is the uh is the length for the string i and j and then the inner loop we can simply do a we can simply loop through i from n minus l plus one that's going to be all the possible uh locations for i with the length l and then we can easily calculate j gonna be i plus l minus one okay and like i said so the first case is the first one is to print ice letter separate separately so if that's the case we're gonna have like two for j equals to l plus sorry dp i plus one j and then we plus one i mean like i said you know we can check if there's anything uh matching the ice ladders uh and then we can have like if outs but another way of doing this is like we're always assuming we have we can print this letter separately that can cover that case so later on we can just use this one to compare to get as a base case to get the minimum result so now the next thing is that for k in range of i plus one sorry i couldn't hear what you said sorry that's my uh that's my theory and so here the reason i do i plus one is because let's say we have a here right so we have another one since we have already considered the uh to print the isolator separately case now the next one like i said we need to find another matching ace after a right other than a here that's why we have to start from this is i right that's why we need to start from i plus one and we stop from to the j so if the ice i is equal to the sk then we just do the state transition function dpi j is going to be a minimum of dp i j dp i k minus 1 right plus dpr k plus 1 j right but like i said since the k plus 1 could be greater than j here so we can sim we can simply have like a if else track here so which means that uh we do this if j is greater than k right else zero yep and so here in the end we simply return the dp 0 to n minus 1. that's our meaning for the entire string what's the minimum turns we need to print that um yep so let's try to run the code so this will accept it let's submit oh yeah this there's a special case which means that um if not s right so we simply return zero yep um yeah so it passed and yeah i mean for the time complexity i think i thought i think we have already uh i'll talk about that it's going to be a 12n cube because we have a three nested four loop here um yeah i think that's pretty much for this problem you know i mean i think to be honest this one is pretty it's gonna be a little bit tricky to come up with the state transition functions right and also uh you have to be inside for exciteful enough to notice that you know we have a different scenarios and also how can you uh do this state transition function so that you can handle this like uh all a cases yeah they're like a bit several corner cases you need to cover and yeah just to recap right so we start with trying to build the strings uh like naively by uh printing the letters one by one and then along the way we figure out if we have a two letters that are the same so we should print all them together that's the that's how we get this uh dp i j equals to dpi k minus one case and then the this the second part is it's all kind of obvious and another common technique is for this kind of state uh problem is that you know for dpi and j we always uh gonna basically tr try all the possible uh split points right you know on this uh in this range and then we try to split them into two parts and then among others about all those possible splits we'll either get a minimum or a maximum so in the end we'll just need to return the dp from start to the end yeah cool i think that's pretty much i want to talk about for this problem and yeah thank you for watching this video guys stay tuned see you guys soon bye | Strange Printer | strange-printer | There is a strange printer with the following two special properties:
* The printer can only print a sequence of **the same character** each time.
* At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
Given a string `s`, return _the minimum number of turns the printer needed to print it_.
**Example 1:**
**Input:** s = "aaabbb "
**Output:** 2
**Explanation:** Print "aaa " first and then print "bbb ".
**Example 2:**
**Input:** s = "aba "
**Output:** 2
**Explanation:** Print "aaa " first and then print "b " from the second place of the string, which will cover the existing character 'a'.
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of lowercase English letters. | null | String,Dynamic Programming | Hard | 546,1696 |
907 | That Lakshya Khan Today's List Problem Admit Card Number 90 700 Savre Minimum The Latest Word Problems But Most Minimal Is The Minimum Element Of Savre The History Contact Us Given Here For All Facts About Animals And Wonders From Which It Is To Find All The Service Of Governor Andrew Strauss Thoughts In Every Element Has To Be Right Next To Not One Element From Side To Side With Fiber Bees Sutra 12542 It's First To Understand What You Want To Know 200 Latest Effect Three Years Old Is After All The Observer Research Start Reel Vikas December Place Fix Soe Three Layer Pendant Three One Aged Tarzan The Same For Mouni Benefit Hai And This Video Back Disha And Dasha Bales Matter Pending Set Up Till Element Superhit Sample Survey 4800 Nishan More Suit For The Atharva Veda S That suzy add all of them together and in this manner with all the way from the beginning death and water in the middle of the month that do you notice any pattern in the stability updated on that is find a pile real you might see pattern the latest you Can this example set the latest clock the last row message send a great for all disha balance idea and tagged 400 you see the results problem share button oneplus two plus on star plus 200 oneplus two might be coming from here And for class 4 is the additional but some rate is problem relation between hadis dros my latest write to understand what du place all about us the software consulting also service idea and tagged aap article number and jobs which are needed for ladies vs none is so is Beach Co And The Other Day Series What Is The Number 10 Loop Four Indies Series The Previous Song Again For What Is The Best Place For Abs Envelopes 2.25 1513 So Subscribe To My Channel Switch Off 's Split Sample 's Split Sample 's Split Sample Wear Look In at 4 p.m. Two Wear Look In at 4 p.m. Two Wear Look In at 4 p.m. Two how to is the previous less amount of and other results which were getting mirwaiz contributed by all the service under-21 but what about the service thought did after under-21 but what about the service thought did after under-21 but what about the service thought did after 2 and before unfolding of and improvement friends our is 540 ki and k noddy previous less amount For its 2nd semester adapter to for dam male enhancement minimum amount exploited 5.44 many more shampoo same that is the 5.44 many more shampoo same that is the 5.44 many more shampoo same that is the synonyms pay at one plus 2 and subscribe 2 years in this forest and understand your mother that and they can probably due to formula of wealth i suresh Bhatt of fod result of and is equal to result of two plus 4 - 200th comments from forest current 4 - 200th comments from forest current 4 - 200th comments from forest current tax to is the end of the previous multiply the current amount current account I let channel like this one super element came we define result Of Is A Result Of Character Of Previous And To Subscribe School A Plus I - Index Of Previous Lives A Plus I - Index Of Previous Lives A Plus I - Index Of Previous Lives Or Equivalent To Any Previous Cases For Here And To That Aap Sonth Or Hair And To Here And Will Be Multiplied By Different Elements Volume 100 Agency In This amount results from the previous minimum balance amount to be Additional Services Minimum Here we get the previous Lewis and Equal Element Wikinews Method of Monotonic Talk on a Sumo Tonic Stock Is We Special Can Talk Over All Elements of Annual Decreasing Order Today Also Increase In And This Crack Between The Marine The Amazing Strictly Non Decreasing Order I'm Soft And Foreign Information We Can Go To Are Coding Panels And Start Your Day With Solution Bluetooth Dance Super Walking Dead Solution Beach Sexual To-Do Super Walking Dead Solution Beach Sexual To-Do Super Walking Dead Solution Beach Sexual To-Do List Of Previous Loops In Taxes For every index india rep 200 first form and create tarf previous luis are any length office are this gandu se mess are not length initially amphitheaters - 1the means for every element the different previous initially amphitheaters - 1the means for every element the different previous initially amphitheaters - 1the means for every element the different previous less indexes guddu minus one main tera buddhu should also in a slice of Result is a result there was born in phir bhi result for every morning depending dad I think so you are reminded in this country is not liked and felt s05 default that hindi and water uniform total sum of result is good to love answer a love Letter To Create Stock Taraf Distance Guddu Monotonic Do It Suji Monotonic Tag Cloud Calculate The Best Places In Some For That Neetu Run Life Through All The Elements Of The Amazing And Listen That Dainik Vilaval Bhai Loop Insight And Improve Will Run As Long As This Tag Is Something that this condition number one and five one to front on Vivo defined the a talent which included in this element edit of forest at a you slept yr balance side effect stock and strike on length minus one that sex that is great and share my brothers condition Start vape potion morning popping latent adhi element end stop this track is great dane air off side this current element swift everything what we will withdraw all the writer of the please subscribe to i just night we element which means this is the condition subject Ali broke the smile loop slow adams was the state topper on thursday was nav third is point bread current element the current extra is 200 finally they dress hall you should be over will have a list of previous less elements and caused by default vitamin e slide my Minus one two judgment switch don't have previously this elements which are already a day minimum set the index level day will have - 1st previous index will have - 1st previous index will have - 1st previous index and tell what is left a tour of all above cross the length of the year nov20 election hair oil length that end I Plus That And Those Criminal Formula Data Ego And Prevention Tips Time To Get An Election Result Of A Good Result Of The Amazing Result Of Previous Lunar Eclipse Id - A That Dad Glass Of Water Should Support In The World Are Indians In The Previous Loop Latest Current wali hai hua tha kya pata tha and finally Bigg Boss returning the total of 10 result are surat dot s u cleared the exams page and monitor hai waste oil and front soon ok shuddh resham mein aa typo ki kya pisis looking good lets Pray for example test cases this day walking five lakhs after mid-day that all right it's not working why ok chup vikas abhi 128 motor switzerland equation radhe-radhe gyan sansar should be model of radhe-radhe gyan sansar should be model of radhe-radhe gyan sansar should be model of india 272 plus app hai yaar seriously model project on Effect of How To Connect With Girls Name Slightly Different Remedy Share Subscribe Thanks Alot First Time With Me This Point Please Like Subscribe And | Sum of Subarray Minimums | koko-eating-bananas | Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104` | null | Array,Binary Search | Medium | 788,1335,2188 |
1,353 | hey what's up guys this is chung here uh so this time uh let's take a look at another lead code problem 1353 maximum number of events that can be attended right so basically you're given an array of events with the start and end the time and you can attend an event i at any day where the start time i basically if this as a current date if this event is still in progress right and but remember that you can only attend one event at a particular day here return the maximum number of events you can attend right so obviously this is another segment tree problem right basically you're given like a different segment and you need to do something to come up with a result right so usually when you do a segment tree problem you know it's very it's a very common way of doing it you either sort by the start time or stored by the end time right but in this case let's take a look right so what's what does this one what said what's the difference uh about this problem right what's the difference is that you know most of the or the other segmentaries problem as long as you're doing something let's say you're in the middle of this meeting one you cannot do the same you cannot do medium two or meeting three until the meeting one's finished right but in that in this case that's the difference that's the different places here let's say you start from one here right at day one here but it's day two right okay uh yes day one day two yes okay so from day one you attend meeting one right and from day two uh from day two you uh you're but you're still in meeting one right but in this case you can jump you can go to meet meeting two as long as you stay at that meeting for one day it doesn't really matter so at meeting at day two here you can join meeting two and at day three you can join uh meeting three so in this case you can jump you can join three meetings uh i'm gonna yeah let's try let's take a look at this problem here right it's like zero one okay so let's take a look at this example two here there's one and two right event one and event two is two and three right one two three when the three is three and four and even four right it's one and two again right so this is day one right so to stay right one two three and four right so in this case let's say we're on day one right where day one we can pick any of this even one or even four to uh to attend right and then on day two right let's say on day two what kind of options do we have right on day two let's say let's assume we take that we on day one we uh we attend uh event one right and then on day two we have two options here right we have we can either join we can either attend event two or event 4 right because both of those events they are they're in the range of the in the range of day 2 right but which one do we want to attend right it's obvious right we want to attend which at the event whichever ends the earliest right i think that's kind of like a greedy uh idea here so every time right so basically since we're going to loop through the uh the days one by one right because we want to know what's the biggest event we can attend so that's why we need to loop through the days one by one here basically on each day right on each day we check on this day what is the current ongoing or what in progress meetings right and among those meetings we just get the uh attend the earliest one the no the one that ends the earliest right and then on the on second day on the third on the day three we'll see okay what are the available meetings uh on day in day three right and we just keep doing it because every time we just greedily always attend the meeting that's ends the earliest so that it's kind of intuitive right because we want to end uh attend a meeting that ends first then we can then we have the other we have chance because otherwise if we take the meetings ends er later and then the ones and earlier might be already finished so that we won't have the chance to take to attend a meeting so that's why every time when we have we can uh sorry so when we can join the meeting on the day we always try to join the median that ends earliest i mean basically before it's finished right and then for the ones that will be ending later we'll try to join them later on the later day if they finish then that's fine because we couldn't join those at the same day right um yeah so first uh since we're going to uh join the meetings one day per day by day right so we need first we need to sort the events by the uh by the start date right and then on each day right on each day we'll get all the available meetings when i say available i mean the all the ongoing meetings on this day right and then we'll try to get the ones who ends the earliest how do we do that right we it's we can use in that case we need to sort that those events by the uh but by those like available meetings in the ascending order right so which means we will be using a priority queue because in the priority queue the first one will be the ones the first one is always the smallest right that's a basically minimum heap right and then every time when we see a new day here we'll add all the available meetings to that priority queue and then we'll just pop that meetings from the top right every time we can pop a medium from the top it means that okay we're turning a new medium right basically then we'll be uh adding our uh final answers by one and in the end we just return that answer okay so let me try to code these things here so first uh like i said first thing is that we need to sort by the uh by the first element right i think if we sort by the first element we don't even need to specify the key here i think we can do a key here lambda x uh x zero right i think the default one will also sort by the first one but anyway i'll just do this so and like i said uh we'll be uh like looping through each of the day here right so uh i'll try to get total days here total days from the maximum right um total days will be the biggest one from the end date right that's our total days of all the events right it's going to be uh event uh maximum yeah it's going to be array here right events event sorry event one right that'll be the end date for event uh in ring in sorry in events right so that will be our total days here and we'll just do a uh you know we can do a for loop here uh we can do a for loop to loop through each of the day here right but in that case we'll be having some uh we'll do we'll be doing some unnecessary uh things here let's say if there's a gap right let's say there's a event one here and then the event two is somewhere here right let's say there's some gap days here right then we'll be uh we'll be keep doing the for loop here and uh let's see so instead so what we'll be doing is we'll be using a while loop here so that we can skip some we can fast forward the days right if there's a gap here because we because with a for loop we have to loop the element one by one at least in python so and then we're gonna do we're gonna have a date right day equals to zero and then basically while right while days less than the total days here right so let's see what we are doing here we are oh yeah sorry uh we also need like to create a priority queue uh this right to store the uh the current uh in improv in progress medians right so basically if right now i'll write this like logic from this here right if the priority q has some values right and then we just do we know we can we cannot attend the meeting right answer uh from zero right and then we do what we just uh basically we just our append uh the uh we'll just attend that meeting right so when we attend the meetings basically we'll just pop right pop that uh sorry keep hip q dots heap pop right basically will pop that meeting from the queue because that means the meeting is gone right we don't have to attend it anymore and then we pass answer increase answer by one right return answer here okay the other one before doing that like i s like i what i we discussed we need to add right we need to add all the uh in progress meetings okay day plus right so basically for the current day right while basically for we need to loop through the event right we don't need to loop through the event by uh if the start date is smaller than the current date and then we know okay the current event is in the has already started right basically while the day let's see the event date um yeah i think also since we don't want to for each day right we don't want to uh um we don't want to like add uh look through the event from the beginning right since we look through the event we loop those two events with a sequence then we can have like a index right of that event because as long as we add this event to our priority queue uh there's no need for us to uh to loop through the events again right because it's already in that priority queue we know we have already processed that right so that we can have like we need to have an index of the after the next basically the next uh event right we can have like index here index right to have zero instead of zero here that will tell us from the in the next day right we can only we only need to check from that index of the event right we don't have to go from the very beginning here so basically while what about the uh the events right the events of index the index of the start time right if it's uh smaller before or smaller or equal to the current date right that means okay so this event is in that uh is in the range right so we just add priority queues not priority queue uh heap q dot heap uh push right and this priority queue sorry this priority queue uh so we'll be adding the what's that the end time right to this event to this uh priority queue that events uh index and one right and then that's that so we only uh so now after adding this thing here we also need to remove discard all the events have been finished right because i said because remember this priority queue only stores for the current day right on the current day what's the in progress events right and then we can ensure we can if we only store that and then we know the first one will be the one we uh we want to uh attend right if we don't discard because when we move to the next day it's possible that some of the events which we have had already been pushed into this priority queue may have had already finished right if we leave those uh finished event in the priority queue and then when we try to attend that event if we don't remove them we might have end up uh ending attending an event which had already been ended right so that's why on the on each day besides adding new available uh events to this like priority queues we also need to remove right well that's basically uh while uh event sorry well priority queue right the zero well zero is like what if zero has remembered in the priority queue we stores the end event right so if the end event is smaller right then the uh than the current day then current date right that means we uh we need to pop right the priority queue um and since this is the priority queue right so p q 0 will always be the smallest basically the pq 0 will always be the earliest and the time of all the events in this priority queue that's why we can do a while loop right to check if any of the queue in this priority queue has already been has already ended right then we can just pop that thing we can just do a what we do uh hip q dot hip pop right so basically we just pop that thing because that's how we discard the scar ended event right so here we're adding a uh in progress event right um day right so um i think we need to do some check here so while well pq right uh sorry while p q if the priority queue has a value end right and this thing has it's like otherwise we'll have like a exception here and here uh this thing here while index right because after we add this thing here we'll be basically moving the index by one right and then since we're every time we're moving to the end in case we're moving this index to the very last one right so let's do a well index uh is less than the uh otherwise if we reach the end that will still plus one the next time this event index will be out of bound right less than a length of events right yeah and let's see uh let's see i think this should and yes okay let's see if this will work cool oh sorry yeah this top thing we need to use the pre the passing the race cool so yeah basically this thing works right i mean it works anyway so the thing is we can do some uh simple improvements here like i said uh yeah i actually i didn't uh fast forward these things let's say if there is like um basically if there's a gap right if there's a gap which means if the priority queue is not it's like it's empty right if the priority queue is empty what do we just uh fast forward we can fast forward this day to uh to the next available events right basically that would be the next available event will be the index right it'll be indexed with other of the current next event right will be an index uh sorry events event index uh of the start right that's the thing uh here so we also need to check if index right is smaller than the length of events and not right basically if there's not nothing in the priority queue that means we got nothing to do on this day right so we can we don't need to uh fast forward a day one by one we can just fast forward to the next available event but this is like a minor stuff here you know it's optional i think this thing still should still work yeah it still works it doesn't give us a lot of improvements but this thing is like optional here option so basically the key idea here is that well first we need to loop through uh on each day and on each day we uh we first we use this priority queue to store all the uh the in progress meeting on that day right and then the way we're doing it because we are we're basically we're looking through all the other the events starting from that from this current indexes and if that in event start time start date is smaller it's earlier than the current date then we know okay this meeting should be this event should still be in progress on this day right and then besides this one we also will need to discard right the ended events and then once this two step is finished then we know all we have left in this priority queue are the candidates right the candidates on this day that we can attend right and oh so sorry so and this one more thing is it index it will also make sure we'll we won't be attending the previous previously already attended meeting in this case right because and we always we only add these things uh once right and every time we attend the meetings we are we pop this meeting basically we remove this attended meeting from this priority queue so that will that can make sure we're not attending the meetings twice right and then we are basically back to this if statement so now the priority queue was will have will store the events that we have which we haven't attended but uh are still in progress and then from all those available uh those valid candidates from those candidates we will pick the ones that will be ending the earliest right then we'll increase the answer by one and in the end we just do a day plus one right and just return uh okay cool i think that's pretty much all about this problem yeah okay i hope you guys enjoy this video and thank you so much for watching it and i'll be seeing you guys soon bye | Maximum Number of Events That Can Be Attended | maximum-number-of-events-that-can-be-attended | You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`.
You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only attend one event at any time `d`.
Return _the maximum number of events you can attend_.
**Example 1:**
**Input:** events = \[\[1,2\],\[2,3\],\[3,4\]\]
**Output:** 3
**Explanation:** You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.
**Example 2:**
**Input:** events= \[\[1,2\],\[2,3\],\[3,4\],\[1,2\]\]
**Output:** 4
**Constraints:**
* `1 <= events.length <= 105`
* `events[i].length == 2`
* `1 <= startDayi <= endDayi <= 105` | null | null | Medium | null |
1,669 | foreign let's read out the question quickly try to resolve it okay and put list two in their place the blue edge and notes in the following figure indicate the result okay what they do is zeros to five okay is 3 B is 4 list 2 is this okay output is 0 1 2 fine okay I got this 26 seconds okay so what it said it will there will be three parameters sorry four parameters list one and list two so there are two lists to be received will receive a and b as an integer value which indicates in the list one that uh which all notes needs to be removed and basically needs to be replaced with a list two so what it says a to a25 O from a sorry two to five so it's from 2 to 5 we need to remove this in this example so answer will and this will be replaced with list two so 0 1 then list two okay this is how it starts so what it says at least one that length by fourth a will be greater than one and less than equals to B list one dot minus one okay so it says that uh a or b a zero or one provider the RMA starts list okay this one okay foreign it's too big the opportunity thanks again A minus one is your name is foreign hey foreign B is also for less than equal to 4 yes foreign Point third dot next I'll do list two again yeah next okay Dot is the opportunity 2 0 1 2 or at least 2 then 5. 012 list two wire file equation for example discretion accepted zero one two is two then five yeah two or five to save manage zero one any list two then six zero one two is two and six oops whoa it got accepted 61 out of 61 test cases okay thank you bye thank you | Merge In Between Linked Lists | minimum-cost-to-cut-a-stick | You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively.
Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place.
The blue edges and nodes in the following figure indicate the result:
_Build the result list and return its head._
**Example 1:**
**Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\]
**Output:** \[0,1,2,1000000,1000001,1000002,5\]
**Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
**Example 2:**
**Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\]
**Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\]
**Explanation:** The blue edges and nodes in the above figure indicate the result.
**Constraints:**
* `3 <= list1.length <= 104`
* `1 <= a <= b < list1.length - 1`
* `1 <= list2.length <= 104` | Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them. | Array,Dynamic Programming | Hard | 2251 |
222 | Hello friends today I am solving liquid problem number 222 count complete three notes Here we are given root of a complete binary tree and we need to return the number of nodes in that tree a complete binary tree is a tree where um the tree has a two children except the last level and the second last level where the last level are the leaf nodes with no children at all and the second last level may have um one or no children at all and um all the child notes all the leaf notes are towards the left as possible so here we know we can see that uh root note here has two children and the SEC and this is the second last level this level has this one has two children this one has only one child right and the re all the leaf notes are towards the left as much as possible so uh basically the left uh tree is uh kind of like always feel if the right tree has at least one node um so we need to find now the number of nodes in this tree and what cons the constraint that we are given is that we need to find in less than o of n time complexity well um in of and time complexity which is a linear time complexity we could just easily do that by traversing each of these node one by one using a DFS solution but since we need to find a solution with less than that o of n Which is less than linear time complexity so uh well for that solution to identify we need to know uh like features of complete binary tree so let me just show you here in any uh given level at any given height the root node is in the range water repair Edge and root nodes at last level is at this um is included inclusive of uh inclusive in this range so at this height so basically this is at height zero this is our height one and this is at height two so in this height the number of notes is from zero one two to the power of two right which is equals to four so basically it's from one to four uh these are inclusive um so similarly in this level as well now we know that if the tree is filled which means that in a given level the tree has all the notes um nodes so the ha the number of nodes in that level is equals to 2 to the power of the height which is here equals to 2 to the power 1 which is equals to 2 right so similarly in this case it's 2 to the power of 0 which is equals to one if we had uh one on one more node here then the number of nodes here would be 2 to the power of um an H which is the height equals to two so it would be four so basically what we need to do is we need to find uh a tree such that the left uh we need to find um we need to find a tree it could be a sub tree here such that the left the height to the left and the height to the right are equal only in that case um the number of nodes will be equals to the height of that tree node right um so here since the height is not equal so what we do is now we divide our um uh whole problem into sub problems that is we divide our tree into two halves so um now I go to the left half and then find the height here is equals to one the height towards this also is equals to one so what I do is um I find the level of these uh of these notes which is equals to one right depth of this node is equals to one um and that and the depth of this node is equals to zero for this sub tree the left depth is equals to one so once I find the depth here um uh I can know the number of nodes here is to the power of n which is equals to two and then since um I'm also taking the root node into consideration this node into consideration so I'll add a 1 here um and in similarly I'm gonna do the same in this case but here the left um left height and the right height is not equal right so I go to the left and then this becomes my new sub tree and the height here is um equals to zero so 2 to the power of 0 equals to one so the number of note count here is one and here there is no node so it's zero so basically when I return back here I add it I add a 1 to the result um so the total number of nodes here will be close to two and then here I found the total number of nodes equals three I go back here I add a 1 to the result from the left note and from the right node so my total number of nodes is equals to 1 plus 3 plus 2 equals to six here now let me show you a case where um I have uh one One More Level here so suppose I have one more node here then I have a few more notes here so basically these trees are full as well so this sub tree is full here Dan what I do is for this note um I found the find the left um height in the right sub tree height so to find the height um I move towards this note and then I go downwards so I calculate the number of steps so basically I'm Moving Two Steps right so this is at height two and this is at high two one and this is at height zero so now to calculate the number of notes at height 2 x 2 to the power 2 which is equals to four and then uh now I know that I have two more parents okay so I have parent notes Here uh which but uh the number of count is equals to two right so initially if you remember I had um for this level I just did to the power one plus one and that gave me the total number of nodes in this sub tree but for this sub tree where I do to the power 2 which gives me the number of notes here and then only just doing one doesn't give me the total number of notes in this whole sub tree right foreign so basically I'm gonna change this whole algorithm this whole calculation to 2 to the power of um n plus 1 to the power of h plus 1 minus one so what happens here is now my height here is two so I do to the power of 2 plus 1 which is equals to 3 here which gives me a value um 8 and then I subtract a 1 from that so what I get is a seven so E7 the number of counts here let's see I have four notes Here four five six and a seven yeah seven is the number of count here so that this will be the formula that I'm gonna use so now let's dive into our code um so what I need is first of all I need to check if the root note is equals to null if he has a return I return a zero and then I need to calculate the not height of left sub tree I pass the left of the root and left and then out of the right sub tree cool uh so to calculate the height I actually need a function height and I pass the node and then I also check if equals no okay if not because now then return a zero eels uh the height equals to one for this node and then for each of the next node I'm just going to pass move to the next node and increment my height so basically for each of the next note I am increasing my height and then finally return my height okay it's basically not the next note but the um side to which we are moving the side yeah so side will be either left or right and then finally once I get the um height left height so this is basically the high toes left and the heights towards the right these are not equal here if they were equal height if those were equal then I would return the number of nodes in that sub tree which would be equals to the power of height plus 1 minus 1 right so what I'm gonna do here is a bitwise operator so um I'm gonna use bitwise operator so this bitwise operator will actually um uh is actually a power of two so um like in bitwise operate in bits one when I move um shift towards the right uh basically um I'm adding a zero so this is equivalent to two right and when it's 100 it's equivalent to the power 2 which is equals to four and so the number of zeros I add to the bitwise operator is equals to the powers of equivalent to the that many powers of two so I'm just doing that thing here using bitwise operator if not if the height is not equal then um I'm just gonna um do a recursive calls I'm gonna divide the whole uh problem into solve problems so I'm gonna divide this into these two sub problems so the number of counts of this node plus the number of Counts from this sub tree plus a one so this one here is for the root note Plus the number of count of the uh left sub tree Plus the number of count of the right sub tree will be my final result so let's run our code uh okay I just defined this let it's not good if so talking about the time complexity here um since what I'm doing is I'm only traversing either towards the left or towards the right so my whole uh whole um problem is divided into two every single time so for this note my problem is divided into two right into this half and this half for this one it's divided into two so every time my problem is divided into two so for this one so basically it's log off and for first division for the second division is log off and so in total it's log of n um Times log of n hopefully that was useful helpful thank you | Count Complete Tree Nodes | count-complete-tree-nodes | Given the `root` of a **complete** binary tree, return the number of the nodes in the tree.
According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
Design an algorithm that runs in less than `O(n)` time complexity.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** 6
**Example 2:**
**Input:** root = \[\]
**Output:** 0
**Example 3:**
**Input:** root = \[1\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5 * 104]`.
* `0 <= Node.val <= 5 * 104`
* The tree is guaranteed to be **complete**. | null | Binary Search,Tree,Depth-First Search,Binary Tree | Medium | 270 |
226 | everyone welcome back and let's write some more neat code today so today let's solve a pretty easy and popular question invert binary search tree so all they tell us to do is invert a binary tree and what exactly does that mean so let's say that this is our initial tree to invert it is basically what you can tell in the output right so the root stayed the same but you can see it's two children which were left child two left or right child seven were swapped right so seven is now on the other side two has been moved right so basically we took these and then we swapped them and when they say invert the binary tree it's a recursive definition so take a look at this subtree right you can see since we moved it to this side that's where it is right but notice how even these sub trees are different now right one was initially on the left and three was initially on the right but now three is on the left and one is on the right the exact same thing happened with this tree right it was moved over here to the left side but then its children were also swapped right so nine was moved to the left six to the right so when they say invert the binary tree what we're saying is visit every single node in the tree right and every time we visit a node take a look at its two children and swap the positions of the children right so in other words if we're given a tree look at the root node and take its children and then swap the positions and then recursively run inver binaries or invert tree on the left subtree and run invert on the right subtree so it's a recursive definition so we can solve this problem with recursion we can do a depth first search whether it's pre-order or post pre-order or post pre-order or post order it doesn't actually matter a depth first search will allow us to solve this problem recursively so this problem would probably be a lot more annoying if it were iterative but luckily we can do it recursively so we can first check the base case so if the root is null then we can return null we don't have to continue otherwise what we're going to do is swap the children so we're going to save the left value root.left in a temporary variable then root.left in a temporary variable then root.left in a temporary variable then we're going to replace the root.left value with replace the root.left value with replace the root.left value with root.right root.right root.right and then we're going to replace the root.right value with the left value root.right value with the left value root.right value with the left value which we know is now stored in temp so after we swap the nodes all we have to do is now recursively invert the subtrees so we can invert the left subtree and then we can invert the right subtree so by doing self.invert tree what we're so by doing self.invert tree what we're so by doing self.invert tree what we're doing is making a recursive call to the function we're inside and once we have swapped the roots children once we have inverted the left subtree and inverted the right subtree we know we're finished so then we can return the root so there it is this problem is a relatively short code it's a very good problem to kind of understand the basics of depth first search and tree problems in general and it's actually a pretty popular problem and if you weren't able to solve this on your first try don't feel too bad take a look at this trivia there was a very good engineer who actually failed this problem in their google interview but his career still turned out pretty fine so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon | Invert Binary Tree | invert-binary-tree | Given the `root` of a binary tree, invert the tree, and return _its root_.
**Example 1:**
**Input:** root = \[4,2,7,1,3,6,9\]
**Output:** \[4,7,2,9,6,3,1\]
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,3,1\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | null |
287 | yo Chuck what the Chuck is up YouTube in this video we're going to be going over leak code 287 find the duplicate number the thing that stands out to me about this problem is the constraints are pretty intense so we start with an array of integers containing n+ one integers of integers containing n+ one integers of integers containing n+ one integers in the range of one to n inclusive so what does that mean in English that means if the highest value in our array is four we're going to have five elements in our array so that would look like this so we here we have four as our highest value and then notice we have five elements because of the pigeon hole property which states that if we have X amount of pigeons and there's not enough holes to fill those pigeons then we know we're going to have an intersection or a duplicate value in this case it could be two On's for instance and the array is probably not going to be sorted as with the problem statement here but just know that there's always going to be a duplicate value likewise if the highest value in our numbered array was five we would have six elements in our array so something like this six elements um we wouldn't actually have a six because remember we're just going to one to n inclusive so that would be where we would slide in our duplicate value okay so that is how the numbering system works here and how that is explained notice also with our constraints we're unable to modify the array of nums so we can't sort this list of numbers to help us find the duplicate that's going to make it a lot harder also we can only use constant extra space which means we can't make another array to for instance we couldn't just scan our numbers and then push our duplicate into another array for instance and return that uh newly created array so that also makes it quite challenging okay with that said I'm going to show you the trick to this problem there is a definitive trick and let's go over and hop to the code right now all right so you see I've copied the function from the problem and we have a array and it looks like gets duplicated on the value three so how are we going to approach this problem well the way you need to approach it is you need to set a pointer to fast and a pointer to slow so what I'm going to do is just make a variable called slow initially set it to index zero and then also make a pointer called Fast and set that to zero as well the idea behind this problem is you're going to have a slow pointer which traverses your array one node at a time and then you're going to have a fast pointer that traverses two nodes at a time so when I say node I'm just referring to an index of your array so I'm going to make a while loop and I'll set it to some um condition that will always be true and I'm just going to update the values of my pointers in this function so I'll say slow equals nums at slow and then fast will Traverse two nodes whereas slow is just traversing one node fast will Traverse two so notice I'm doing the same thing but then now I'm actually passing the value of that first uh node traversal into my indices or my index and that's going to make me go twice as fast okay and then I'm going to say if slow equals fast I want to break okay let's run this code and I'm actually going to return slow just to see what it is and let me clear this because I was messing around earlier but let me just run this code and it looks like we're coming across three on the number that we meet at let's make sure that fast is also three okay so what does this mean they both equal three but what does that mean well the again the slow pointer is traversing one node at a time and the fast pointer is Travers traversing two nodes at a time conceptually it's pretty easy to understand how the slow node is progressing through our array but it might be kind of confusing to understand how the fast uh pointer is traversing so I want to write it out for a second so imagine we start at zero with both pointers slow is going to be one at index zero right and then fast is going to be one at index zero but then it's actually going to be two because we're traversing two nodes and that's that nested uh index value we have here so we start at one because we're at index zero with both pointers but fast will actually take the value of that initial um zero index zero and then go to the next one over which is two because two is at index one so that's kind of tricky but you can kind of see the logic there so let's keep going so now we're at Value one at slow if I go to index one that's actually two now so I'm going to go to two fast I'm starting at index two which is 01 two that's four and then now I'm going to go to four index four which is three right here so I could say three and then slow I'm starting at index two so 0 one two which is four I'll say four and fast I'm starting at index three which is three again and then I'm going to three which is three so I'm just notice I'm kind of like stuck on three now with the fast pointer and I'm going to start at index 4 with slow so if I go 0er 1 2 3 4 that looks like it's three and then with fast I start at index three so 0 1 2 3 and then three is telling me to go to three again so I'll be at three so 0 1 to three which is also three so at this point they're equal to each other and we're going to break out of the loop so let's console log that to prove that this actually happened so I'm going to console log slow and pass in the value of the slow and then also fast and pass in the value of fast so if I run this code you can see the logic we just had it's um it's not showing you the last transformation but if I put the console log statement down here you can see where we align right so what's happened here is we've actually created a cycle and or a loop this problem is called Floyd's cycle or you get it's called like the tortoise toris and hair I don't know that's probably not how you spell tortoise but it's a known problem where you end up having a loop and these values will keep looping um Forever on each other because there's a the pigeon hole problem like we talked about before where because there's a duplicate value in this um uh length of array remember our max value is four and we have five elements therefore there's going to be a duplicate that duplicate causes a uh loop or a ccle like this so obviously we're breaking at three because that's where they equal each other and if we didn't have that case this would go on for infinity and then would crash our computer right but let's keep going outwards and seeing what would happen if we keep going with these pointers so fast is just stuck in this infinite Loop of 3 right with slow I'm at 0 1 to three which is also three so slow actually got caught in the same Loop and the same cycle and this is going to repetitively do three so here's where the magic of this algorithm happens um now we have captured the node where there is a cycle and that is what we need to uh solve this problem so I'm going to make another pointer now called in it and that's also going to be set to zero notice that slow is set to index 3 right it's still set to index 3 Let's Get remove this console log statement so um I'm going to do another while loop same idea I'm going to have a condition that's always going to be true and it's always going to be firing now I'm just going to copy this slow code or the slow logic which traverses just one Noe at a time remember fast traverses two slow just traverses one and then I'm going to do the same thing for in it and I'm just going to Traverse one node at a time and I'm going to say if slow equals init break okay now if I return slow what happens we get our duplicate value right so this is pretty much the answer to the problem but what is happening here and why does this work okay so you got to understand that slow the first Loop we did was just to determine the node in which there is our cycle we want to find where the cycle starts and that is at index 3 as we've established in it is just starting like slow did initially and working through the array so let's walk the dog and see what these equal it should be pretty easy because they both are traversing one note at a time so it's not really that confusing to see what value they become but let's say we've got three and zero at the start so if I go to index 3 that's 0 1 2 3 that's three and it's just going to go three forever right within it we start at index one and then index one is two and then 2 0 1 2 looks like it's four and four is 0 1 23 4 which is three and here we have our connection where they both meet right so the interesting thing about Floyd's algorithm is that it basically knows that if you start at the uh node which is the cycle and then you have another pointer start at the beginning of the node list they're eventually going to hit each other because remember this is a loop where um slow is stuck on three forever it's just looping on three So eventually in it is going to cross paths and collide with the slow like imagine the uh a graph where two lines intersect that's the same idea here so this problem is um has a Time complexity of O of n it's linear time but the constraints of this problem make it so you pretty much uh have to use this algorithm this problem is tailored for you to use Floyd's algorithm which I think is kind of unfair because if you were never exposed to this chances are you're probably not going to solve this in linear time of O of n so that is the problem itself I hope you guys enjoyed this video if you found it valuable please be sure to like And subscribe again it might be kind of conceptually confusing to understand this logic at first but just know that first while loop is just to grab the location or the node or the index of the start of the loop and then the magic of Floyd's algorithm is that now that we know the start of the loop we can Traverse one note at a time with both pointers and they'll actually end up hitting each other truly incredible okay thanks for watching guys I will see you in the next one | Find the Duplicate Number | find-the-duplicate-number | Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive.
There is only **one repeated number** in `nums`, return _this repeated number_.
You must solve the problem **without** modifying the array `nums` and uses only constant extra space.
**Example 1:**
**Input:** nums = \[1,3,4,2,2\]
**Output:** 2
**Example 2:**
**Input:** nums = \[3,1,3,4,2\]
**Output:** 3
**Constraints:**
* `1 <= n <= 105`
* `nums.length == n + 1`
* `1 <= nums[i] <= n`
* All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times.
**Follow up:**
* How can we prove that at least one duplicate number must exist in `nums`?
* Can you solve the problem in linear runtime complexity? | null | Array,Two Pointers,Binary Search,Bit Manipulation | Medium | 41,136,142,268,645 |
417 | hello everyone welcome to my youtube channel and the question for today is pacific implanting water flow all right so what we have over here is the question where in which given a matrix m cross n of non negative integers representing the height of the each unit in the continent like pacific ocean what touches the left and the top edges that is the left and the top edges is the pacific and the atlantic ocean touches the right and the bottom edges so here we have atlantic and here we have pacific all right and in between the cells that are given as a height all right so water can flow in four directions and so what is the main reason for the heights given is that the water can throw from one height to another only if it's equal or lower all right yeah only if it's equal or lower that is a very important condition over here so let us look at this like this is specific and this is atlantic ocean and these are the heights that are given to us in a form of an 2d matrix and water can only flow from uh height that is you know uh that is bigger to lower because water can flow from only high to lower late not low to high rate so that's the same thing that we that what that is given in the question as well so water can flow from uh height that is bigger then to smaller one and yeah so and it can flow in only four directions not technically it can flow in up down left or right direction all right so if we find the list of the coordinates where water can flow to both pacific and atlantic ocean so we have to find the coordinate from if we uh you know place some water drop or something like that over there the water will flow to both the oceans all right the pacific as well as the atlantic ocean we have to given the coordinates all right we are not given their heights but we have to return the coordinates all right so coordinates because coordinates are unique height can be you know repetitive so our answer would be you know wrong in the case that's why the question is design like we have to return the coordinates all right so one note given over here is that the order of return coordinate does not matter so basically it doesn't matter uh it's not like we have to return the electro graphically smaller one or like that so we have just to return the coordinates and both m and n are less than 150 so the maximum size could be 150 all right so yeah that's the question over here and let's see the example over here that's given to us and in this example what it's given to us that these coordinates so what is zero four is zero one two three four and zero so this coordinate already if we place water at this point definitely if it's at higher end it will flow to this and it will flow through this so it can flow to both oceans all right and yeah and the other coordinate that is given to us is so 1 3 so it is one thirty okay zero one three that is seven all right so water can flow to this side and it can flow to both oceans like this it touches this and it touches this all right so that's the main thing over here okay and also let because the they have encircled the points so for this one why is this point is included because the water can flow from here to this ocean and from here to this ocean all right so up down left right all right and only the heights which are lower than that all right not the higher height all right so yeah so why this point is not in our answer guys because the height is 3 and all the adjacent sides are like say we it can flow this side but it can't float this side because all the heights are greater than that it's five four so it cannot flow from three to five or three to four all right so that's why it's not included in another it's not like we have to give a path from that particular point we have to give up points from where if we you know throw some water it will meet both the oceans so that's why 3 is not included in our answer over here and it's not marked like this so yeah i hope this example is clear to everyone and there are no constraint given so we will assume that these are general constraints because they have written some constraint in the these only that the numbers are non-negative that is they are positive non-negative that is they are positive non-negative that is they are positive and the size are less than 150 and the order it doesn't matter so it can be zero as well because it's not mentioned in the constraint we will cover this test case as well if mentioned in the constraint that the minimum range from the mrn would be from 1 to 150 then we can skip the part of having a null matrix but it's not specified over here so we will assume that we can get a null matrix all right so yeah that's the question i hope it's clear to everyone and a basic hint for this question would be a graph approach alright because a matrix is a kind of a graph only and yeah so and we have to find you know these that these are like connected in a way so it would be a graph question only and let's see how we are going to solve it all right so let's see the approach for this question and yeah this is the question and we will see the approach with the help of an example first and it would be much more clear how we are going to solve it all right so this is an example over here so what we do is simply the way we have to locate the points from which we start and we reach the both oceans and we can only move from uh and we have to give the point from which we start all right not the path from the points that's a very uh basic thing that should be cleared while we write the code for this question so the idea here would be not to start from the points but to start from the ocean all right and as we as i discussed earlier it's similar it's a graph like question so basic graph traversals algorithm can be used over here all right so that shouldn't be any concern so what to use so we can use both bfs and dfs uh i'll implement bfs because it's much of a iterative solution than a recursive one and very easy to understand sometimes people have difficulty in dfs because it's a recursive solution but that doesn't concern it that can the main concern is the approach that we will be use using to solve this question all right so as i said earlier we will not start from the point but we will start from the ocean what i mean by that is that given a matrix like this we have over here is i think a pacific is there an atlantic is here right so what we do is that because these point can directly be covered with the ocean because these points can cover the atlantic and these points uh sorry these points are specific and these points in cover atlantic now we have to find the common points all right so the approach that was given to us in the question that we have to go from higher tile higher high tile to lower time all right as we are using the backward approach or the opposite approach so what we will be doing is we will be going from lower height to higher right all right to find out the points and what we are going to do is we are taking these two points from the in our queue and we're gonna apply bfs at them and we're gonna find the points similarly we are going to do the same thing keeping in mind the points will only be added to the queue or i have the at the list where we are storing them only we then be visited only and only then when they move to a point which is higher than them not lower than them all right so because this condition was when we move from point to ocean all right point to ocean now we are moving from ocean to the point we are using the this approach ocean view point all right so this super this thing uh which we would be keeping in our mind all right after suppose we have got some values then we will select for the common one all right now let's try to solve this question and let's see what we can get all right so yeah i have marked over here with this blue at the passage equation point because here is the pacific ocean and we can move from suppose three point to this point and this point because it's of equal or higher length already similarly we can move from this point this one this point and this point we cannot move from this point to this point because it is of low length not this one can be covered from here so yeah these are all the points that are covered from the pacific similarly i have done here for atlantic because these are the point that touches the ocean so this can be covered directly from now we will apply our algorithm because it's a higher right we can cover it said lower we cannot cover it all right now we have the now what we have to do we have to find the only the common points all right how did our algorithm be opposite that we check from every point it would have taken a lot of time this algorithm now saves the time and cuts our complexity even to you can say half from the algorithm where we traverse every point all right now after that we can have the common point so here i have marked the common points with yellow so these are the common points and at the end what we have to do we have to just return the coordinates all right so i hope this approach is very much clear it's a very easy approach what we are using here we are just doing the opposite we are going from ocean to the points and we calculate both the points from atlantic as well as specific and at the end we return the common points because only the common points can let us do both the oceans if we start from them all right and if we start from any other point we cannot get to those and we either get to pacific one or at least we cannot get to both of them so only the common points will get all right so yeah this is the approach we are going to use for every you know every traversal like for pacific and fraud atlantic we will be maintaining two queues for visited like that because we don't want to go in a infinite loop if we don't know what points we have visited and what we points we are about to is it all right so we are going to maintain a queue for both of them separately and i hope this approach is clear to everyone and it would be much more clearer if you have still got some doubts it would be much more clearer when we see the code for this question all right so now let's see the code for this question yeah so these are the points because we can move in a specific coordinate so i have taken these points in as my directions and this is a general principle if we solve any problem for traversal as well we keep the points where we can move inner array initially and we apply our algorithm so this is general the number of laws number of columns these are nothing this is our main function which will which have the coordinates all right so and we have to return a doubly linked uh list arraylist all right integer value all right so we have put a check for zero because if it's an empty array or it's zero then we simply return empty as the answer because we have to return an error list so that's why we have written an empty release we have haven't returned values like null or 0 because the return now we have taken the number of rows and number of columns like that now here we have maintained two queues one for pacific and one for atlantic because we are applying bfs approach over here so we have we are using queues had it been dfs approach we have been using star alright bfs approach and now we are adding every point that covers the pacific ocean and the atlantic ocean alright how we are adding them because uh these are the points that will cover the pacific and these are the point that will cover the atlantic so we have applied a loop like that because at all these point we will begin our bfs approach all right because these points will be initially set to the queue and a bfs would be applied so how many nodes are with how many values are visited we don't care we just cared for the common ones that are visited by both all right so what we do is we uh initially offer these points for pacific and these points and landing that is done over here and now we have employing our uh deployed our bfs code which is written over there that's basic simple logic bss code and after that when the result will be uh covered in both where basically are the coordinates that are true because i have taken a boolean that will jump yeah to its visited and false if not visited and we will and at the end we'll compare the common ones so i have the traverse hole of the array if both of them are true that means they are visited in both the loops that is they are visited by pacific and that as well as atlantic so yeah i will pick that one and add it to my final answer and at the end i will return that value all right now let's see the code for the uh bfs approach all right so here is the code that we have used for the bfs approach all right so it's a simple code we have taken a matrix for determining whether it's visited or not and it's for the same number of rows and columns that is of initial method and yeah this is a simple bfs code while the queue is not empty we will simply pop the element and yeah we will mark it true and we will go in the directions and we will check that if the point doesn't you know exceeds the matrix if it doesn't exceed the metric then we continue and if it hadn't been visited then also we continue and yeah now we only and only at those points that we move from lower to higher because we are moving from ocean to the point we are checking for lower height to higher right had it been the opposite had it been we have been checking from the points to the ocean then we have uh just simply reverse this check all right and at the end if all these conditions are satisfied if because we are covered over here then what we do is we add it into our final queue and at the end we return our regional because when the cube will be empty and that means we have to reverse every point and yeah and the visited array are the boolean reachable array or the visited array uh reachable in this case would be set uh initially values will be set to true or else all right i hope this driver function or the bfs code is also clear to everyone let's try to submit this code as you can see it's accepted so if you have any doubt regarding this question or you have any doubt you can ask me in the comment section and if you like this video please like it and subscribe to my youtube channel for more such videos thank you for watching bye | Pacific Atlantic Water Flow | pacific-atlantic-water-flow | There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`.
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_.
**Example 1:**
**Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\]
**Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\]
**Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below:
\[0,4\]: \[0,4\] -> Pacific Ocean
\[0,4\] -> Atlantic Ocean
\[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,3\] -> \[1,4\] -> Atlantic Ocean
\[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,4\] -> Atlantic Ocean
\[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean
\[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean
\[3,0\]: \[3,0\] -> Pacific Ocean
\[3,0\] -> \[4,0\] -> Atlantic Ocean
\[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean
\[3,1\] -> \[4,1\] -> Atlantic Ocean
\[4,0\]: \[4,0\] -> Pacific Ocean
\[4,0\] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.
**Example 2:**
**Input:** heights = \[\[1\]\]
**Output:** \[\[0,0\]\]
**Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans.
**Constraints:**
* `m == heights.length`
* `n == heights[r].length`
* `1 <= m, n <= 200`
* `0 <= heights[r][c] <= 105` | null | Array,Depth-First Search,Breadth-First Search,Matrix | Medium | null |
878 | Hello All Activities Problem Darkness to Conscience Bill to Ignore Actually a Problem Number to Take Down I'm Forever 125 Given Magical Number What is the Magical Number Magical Numbers of Positive Anti-Aging Effects Divisible by Positive Anti-Aging Effects Divisible by Positive Anti-Aging Effects Divisible by Either A and B Tight So It Means The Ephesians NDA Big Tits Milk and Bones When We Want to Consider Difficult Number of Whom You Want to Give U Don't U Find and Magical Amazing Question An Answer Is Tubelight Model Celery Number One Word You Can Decide Examples 2351 Do the Second 123 The 1431 Notice For And The Cockroach 1262 Subscribe Important Question Unauthorized In The World That Aaj Yadav Action Is Basically Subscribe Active Number Delete Number [ Active Number Delete Number [ Active Number Delete Number Number Subscribe Similarly E Ki A Yeh Tube Baby Vihada MB Sweater Previous Video subscribe The Video then subscribe to the That Mi Plus m20 But Now You Will Have to Work Out Na Way UP and Country in the World Is What They Are Looking For Na subscribe this Video give Viewers Subscribe to Channel Not Exactly What exactly and subscribe the Channel subscribe I want to find out what do you want to have a function which music festival all the best blonde 1669 macro in a that talent to be long as they celebrate this long knows very well known in the name Aaf KV Divide Ise Times Pe subscribe to the Page if you liked The Video then subscribe to the Page That This Model Also Not Subtraction Business S Per Department Me Patience You Can Be Positive Water Absorption And Take Long Speech On That Digestive Vitamins Programmed instructions subscribe and subscribe the inter range long and share and subscribe will subscribe to difficult binary search tree which is made na dharo and high-speed to The Amazing subscribe to ke liye dhaan rok laka di hai point arrested in love with you don't No Limit of the World Subscribe to the channel and subscribe this Video plz Divide Subscribe to Pimp Target Thursday Will Actually A That She Will Do Half Change Model Do Subscribe The Channel Please subscribe and subscribe the That Accept Person To Person Hundred Percent Call Member Short and Simple C Plus Solution of But Not Problem Thing Just Like This Important Relationship in To-Do Like This Important Relationship in To-Do Like This Important Relationship in To-Do List Now Research Away Joe Asaf Thank You So Much By | Nth Magical Number | shifting-letters | A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1, a = 2, b = 3
**Output:** 2
**Example 2:**
**Input:** n = 4, a = 2, b = 3
**Output:** 6
**Constraints:**
* `1 <= n <= 109`
* `2 <= a, b <= 4 * 104` | null | Array,String | Medium | 1954 |
37 | good morning everyone welcome to my YouTube channel and for this video let's talk about the subsequent problem to the Sudoku problem so for this problem we have to actually come up with our own like Sudoku server so we will look at two approaches for doing this problem here is the problem statement and as usual I want you guys to try this on your own before we look at our solution together like the traditional approach for solving this kind of problem like so this problem is similar to uh that end Queens problem I don't know if you have encountered that problem but they are exactly the same like though and so the first time I try this I use Backtrack on my own but I actually um encounter a really nice way of solving this problem I think from MIT course like a few years ago and just want to share that with you so in the description I will have a link to that to the professor's paper so backtracking as you know we try pretty much we try every single number and then if that doesn't work we backtrack we go to our previous step and then we undo our you know the changes that we made and basically we are doing like so this for using backtracking on this the time complexity will be like enormous like it is very huge and especially when you are working on say a very difficult Sudoku typically that means we don't have that many you know numbers like shown in those like our stoku that in that case the number of times we have to do backtrack can get really big so let's first look at the traditional way of doing this kind of problem so as you know here is the code I put this backtrack variable here so that when you run this we can see how many times our code actually had to do the backtrack and you can see that so basically we'll be iterating from like this guy zero comma zero all the way to 8 comma a and then we iterate move to the right and then see that this guy is empty so we try all the belly number say from one to nine and we notice that so in this case the first number would be one to four we try number four into here and then so they will be here so for e in range of one through ten so that there'll be one through nine and then in this case we check if it is valid or not so the first value number in this case would be what think this one will be two or actually this one will be one so we put one here and then we check and then we do we run this recursive function again that's the main idea for this kind of problem but as you can see this one is very slow right I if even if you use this code for the liquid problem you will still pass I think few years ago when I used like code very similar to this I was able to pass but it was rather slow and I think right now it might be even slower because the code typically has like it adds more new test case so I don't know how this would slow down but this code works so there is no problem with this however there is a way to speed this up so there is a way to optimize this code and let's look at the second approach oh also I just want to emphasize that you know we have this like inner block so we have about this three by three plug here so we can call this zero one two three four five six seven eight and let's say if you are working on this block like this guy and you want to know which block remember we have to check like this inner block to see if the numbers are valid or not in this case if you are say here then you would have to then we'll be working on this block right and then the way I do that is you use this guy so sector Type X sector top y so you're between three times I like this division by three so basically in this case let's say let's see if you try seven comma six so I is 7 so we'll get three times that three times two that will be six and then we would get three times two the so they will get a six so UB six comma six right here and then notice that we can do this so for that we add set top X and the set top X plus three so we'll be iterating from here to here and the same thing from here to here that will be given by set top y comma set top y plus three so tests for this code and there's really not much to do and then we have on our like this we have if I is equal to negative one then we exit we return true and then we do exit um I think that's pretty much it so let's look at the second approach this is our second approach but this is optimized how so the previous approach is how computers tries to solve this problem right but then for us human we do a slightly different way right if you if we say if we look at this we can cross out so we know that this one has to be one because when this is one when one is here then this guy for this row we cannot have one here when one is here this row cannot have one here obviously you cannot you can also not have one in this column but for now we only care about this inner block and then we look at this one again and we notice that this column cannot have one so you look at this and we see that well all these blocks are you know invalid for one and then this one is already taken this is already six so that means this one that one has to be one and then so that's the way of we reduce the number of times we have to run our you know backtrack function let's look at this one so let's look at um like really specific example what I mean by this so here we so instead of trying every possible combination we can determine which numbers are probably that every block like this guy this one for each inner block we would say like this three by three that's what I mean by Inner block we see which numbers are available in this case well what two three four five seven and nine so those are the available numbers and then for each inner block we determine which numbers are valid in the row and column and if we are left with a single number then we can place the number into the block so what do I mean by this means we will get say row set column set and then we will be using our python difference function between sets and then we can just get rid of this like redundant numbers and then when we are left with one number then that number goes into like here so let's look at really specific example see what I mean by this so if you look at this 0 comma zero that's the first empty Block in our Sudoku and we notice that so we'll be trying from one through nine and we see that five is the first available number and that is valid because well you may say well how about two comes before 5 but then notice that two is here so we cannot use two five is the first value number and then so we set that equal to five and then we look at all the other empty cell empty plug in our inner block this first block so we see this guy and this guy so those threes are empty and then we will store like the coordinate x coordinate y coordinate and then the missing number in our in this inner entire block so in that case we have two eight and nine so this is what I mean by this and then you will be appending this to some list here like that I will show you in the later code and we noticed that and then the next step will be we'll be looking at this one first zero comma one we check the rows of row zero comma one there will be this row and then those numbers are what one three five six seven and notice that our this set and then this set they don't have any numbers in common so there's nothing we can do we look at The Columns of zero comma one we notice that this is that's this guy then we have three five six seven and nine and we have nine as a common number so this one for this one nine disappears so we are left with two and eight however the length of this set is not equal to one so we cannot do anything we cannot put any our like we cannot make uneducated guess in here so we move on to the next one there will be this guy now for this guy same thing we look at the row and then the column we notice that the row of two comma zero it is one four six seven and eight the number eight is the you know the common number so a disappears from here so we are left with two and nine however Columns of two and zero we have three four five seven and eight and there is no redundant number right we are looking at this side this set and then we are looking at this set they don't share any common number so the length of this is still two and we move on to the next one we have one four six seven and eight and we notice that eight is the common number so a disappears and we have two and nine Columns of two comma two we have this guy and notice that this guy and this guy they have nine as a common number so we are left with two those the length of this set is equal to one so we set that equal to 2 and we do the same thing for like all these blocks right the remaining blocks and this is a lot faster than you know trying all numbers without making like this educated guess so that's two here and here is the code for that problem so one thing that so this part is you know we are basically trying to find all the missing numbers in our inner block and then here this part this is the part where we do like this part and then this part we are finding the so we are using this difference function and then we find the first row three which is equal to just which is initialized as a set and then we add all the numbers in here and then we use the difference function and then we try to you know get rid of this redundant number we do the same thing in the column and we try to get rid of redundant number if it is possible and if our if the set left is has a length one then we pop that and then we set it equal to you know the value here so in this case that's what I just did here this part and then we add this to our this imply one array so why should we do this well if so we'll be running this we will be making this educated guess and then if somewhere in the in down the road when our you know this Sudoku server uh cannot solve this then we have to undo all the changes that we made right if you look at the code here right so this is basically here so we so when we return then when we exit when we backtrack right this is the back track part we have to undo the changes that we made before we make the change to e some number then we have to make that change back to the like zero so we have to do the same thing however in this case it's slightly more complicated because we have to make unchanged we had to make like we have to undo the changes for all these like all the changes that we made under this imply one so that's why we have to store this all these changes that we made in our imply one array that's the key part and then if you look at this one I just pull this out from some like you know Sudoku app and this is the like the one of the really hardness problem and if you use the knife approach like the traditional backtrack approach the number of times we have to do the backtrack is nearly 2 Millions but if we use the second approach then we do roughly 60 000 so that's about 33 times faster than our Nike backtracking approach I really find this approach really powerful and let's look at the decode problem here is the code that is optimized for Sudoku problem and it's exactly the same code that you just saw and so let's I'm going to run this one should be fine or also I just want to emphasize that like the pseudocode problem that I worked on the input were just integer but in this case we have a we are given a um a string bunch of strings so I didn't want to like modify too much in this code so I did I took lazy approach to this so I basically just you know given this like board input I just made everything into the integer right and then like this dot I just change it change I just changed that to zero like this dot you see here like the empty block and then when you get the cook so when you use our Sudoku server we will modify our board and then we just change the port which is just a bunch of numbers integer back to the string so that's the step that I took I just didn't want to modify all these codes so let's run this so this one should be very fast and if you uh you can go to Apple App Store and then try to download say you know Sudoku app and you can try like all those really hard problems usually hard problems they are you know you are not given many numbers to begin with and then you can see the difference differences like really huge so anyway that's for this video and I will have a link down there to the paper that I found very insightful so that's for this video and hope you guys have a great day if my video helps you guys understanding this problem please subscribe to my YouTube channel and I'll have more interesting contents out there for you I will see you next time bye | Sudoku Solver | sudoku-solver | Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy **all of the following rules**:
1. Each of the digits `1-9` must occur exactly once in each row.
2. Each of the digits `1-9` must occur exactly once in each column.
3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid.
The `'.'` character indicates empty cells.
**Example 1:**
**Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\],\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\],\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\],\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\],\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\],\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\],\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\],\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\],\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\]
**Explanation:** The input board is shown above and the only valid solution is shown below:
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit or `'.'`.
* It is **guaranteed** that the input board has only one solution. | null | Array,Backtracking,Matrix | Hard | 36,1022 |
434 | The Festival My name is Adarsh Mishra This is what The Festival My name is Adarsh Mishra This is what The Festival My name is Adarsh Mishra This is what you are watching Dress this mark Today we are going to talk about number of Tintin's problem not Gheerat Dahi video on the list You can watch the video that you should not forget to subscribe this channel Subscribe must subscribe, anyone subscribe to that word here so that I can speak to you, here I have been given a system, what I have to do here is that at that time I have to see how many numbers of words are there inside it like I am here See, this is the word here, it will go from here to even if you use it in the family after getting war 5508, then please subscribe. If you want to use it, then you have to subscribe. Subscribers subscribe to subscribe here. Here, love you will go to the face, then it will go to forever, then the total is four, I have put it here and here, it is okay, but stop love music is different system, so here, like subscribe can be appointed, subscribe, it can be He is telling me that you will not have STD, its length can be up to 300, it can contain lower case, upper case and digits or it can contain as many punctuation characters as you can see, it is a special item, it can be all of these, okay Meghnad only. If the species character was of this type after grinding the juice, if it was ever off space, then here we use it, so please subscribe like we must subscribe here this subscribe, for this, Ajay, this is the way to make MP3. It will be spread here like this and then this remaining empty space will also come, so I mean we will consider it empty also, so if we are going to have it then I don't have to do this, for that, Noida first, whatever extra space is there from the left side and from the right side and With this, we have to remove them, trim them, smile while timing them, first we will use Hussain, after this we will use speed, only then our answer will come when we use the functions in agar, is it surgical, problem in the pattern, on this platform, friends, in this we have to There is no need to print it separately, but it has a function. If you have seen any of our stings before that, you have space. Okay, then whatever is in your mind, first remove the prescription. I have removed all the specials before that, which is my skin. What is left is that by going into it, our stomachs are separated on it, some of our weight is separated and kept in the list, the method is written here, should I use it daily, what will you do, speed up this trick. If you do this then its printing is in ABC space, BF picture send Radhe Maa, I will use speed, this is done, ABC people will break the given panel here also soon, so what did I do, I broke it from the middle, did speed, this is space and then find out its length. The answer will be two, so whose one is yours, so this is a small meaning, okay, there is a function, you can use it and how much time will it take, if you feel stupid then it explains it, travels in the whole list by subscribing to it here. Gives space, we are feeling extra in this but because just subscribe, it will be taken, so you have the method here, it is our simple technique, now we are going to use it here, okay, so the thing here is that we are stressed. No need to use, so in this place we will write the code here, now it will be exactly like this that if I tell you that you have written my ABC space difficult something then subscribe to this channel that I have this here, so here we will mean it. That is, before this, as many as you subscribe and okay, after this, run it again from here, okay, so we are making all these separately, so in this way you can do this by looking at us, now let's move on to this that I want to find out. It is being started again that you subscribe this subscribe the union now school subscribe it means house here you cannot do subscribe quit will use and by using constant space you are going to use songs person mosque account how many numbers will you do How much more will we provide from this pay, till then we call it account number, words, it is equivalent to the number of district subscribe, if you take them, then this subscribe video subscribe is nothing like this subscription of mine is here, this is my one, it is fine. Okay, I picked up the ginger for one more minute, maybe before there was even space, okay, then I remember doing something, it is getting clear that brother, if you want to get a character on zero index, if you want a heroine, any character. If you have to meet, it means that this is the beginning of a new segment. Okay, so what do you do? Call them, give them an increase, if you want to meet the character on the front, then it means that it is definitely going to be a labor world, isn't it? Good passage, how? Well, if you are interested, then set yours, if you try to find out, if you are interested, you will like - 110 subscriptions are about to start, subscribe here, if you have questions and hate others, this is our Ghaghra pension. Write that doing special will last till the end of the marriage because why would it be like this then first do as many of these and subscribe village means I subscribe I should be from here to there subscribe and I will subscribe ok after this see here But I have a boat in my head, that's why the point reached crore on some index, in this we say that subscribe and subscribe our channel, so here I have written that on the growth index of my sting, Divya is not that, space way soon. Increase that on the truck in the same condition, now write, if today we have something other than Twenty-20 of potatoes, today we have something other than Twenty-20 of potatoes, today we have something other than Twenty-20 of potatoes, then we will do a case of that case, we can check on them, then I said that for this team, I have written here if my It is lying on the eye of space and history, it is not lying on the eye of any character, there is nothing like that and if there was an option in this then I have used both of them here, I have used them here we have used them, so here you have to type. That and you have to use the space, use the cost, make it simple and if you use the function, then you have to take time which will give you extra, use this piece also and you do not have to use the touch here, that is the problem that we have a little trick. thi a jhal | Number of Segments in a String | number-of-segments-in-a-string | Given a string `s`, return _the number of segments in the string_.
A **segment** is defined to be a contiguous sequence of **non-space characters**.
**Example 1:**
**Input:** s = "Hello, my name is John "
**Output:** 5
**Explanation:** The five segments are \[ "Hello, ", "my ", "name ", "is ", "John "\]
**Example 2:**
**Input:** s = "Hello "
**Output:** 1
**Constraints:**
* `0 <= s.length <= 300`
* `s` consists of lowercase and uppercase English letters, digits, or one of the following characters `"!@#$%^&*()_+-=',.: "`.
* The only space character in `s` is `' '`. | null | String | Easy | null |
54 | in this video we're going to take a look at a legal problem called spiral matrix so given an m times n matrix so return all elements of the matrix in a spiral order so here you can see that we have a 2d array and we're basically given a 2d array of matrix and we want to return a spiral order of the um 2d array in a one directional array so that's the output and here you can see that we have going from this direction to here so first we're going right and then we're going down and then we're going left and then go up and then we're going to continue the spiral um and here's uh you can see here's another example so we're basically going from uh left to right um down so top to down and um right to left and then um down to up and then yeah basically just continue and there will be inner uh elements and we have to it um traverse as well so here you can see we have a little more bigger to the array so we could so the way how we're gonna solve this problem is basically just like i mentioned for each iteration we're going to traverse let me change the color real quick so for each iteration we're going to go from here to here right so basically the left all the way to the right then we're going to do is we're going to basically move down because after we traverse this part we're just going to strength shrink the array or i should say basically shrink it so that we can just only traverse from here all the way to here right so here we just have to traverse from here to here so in row 2 to row 4 right and then once we've done that we also have to shrink the um so basically shrink from the array so that we can only traverse from here to here okay so basically we're going from here to here and after we've done this we can shrink the array so basically we're going to only traverse from row three to row two okay so after that's done that's our first iteration and then we're going to continue to do this so we're going to um start from here to here after we go from uh column two to column three and row two what we're going to do is we're going to um start to start showing the array again so basically like these parts of the arrays are all gone we're not going to like traverse them again but what we're going to have is we're going to traverse from um basically uh top to down and now we're going so basically traverse this element right here and then we're going to traverse from right to left which is right here this one and then after that's done we don't have any elements left so we're just going to return the elements that are with uh within the two uh one directional array so let's try to do this in code i'll show you how we can do this so our first step is to create our list integer thumbs we're going to create a linked list because we don't need to access um a specific element in the one directional array we're just adding the elements onto it so and then we're gonna have our borders so in this case we have our left have our right have our top pepper down so we're going to define our borders right now so top is equal to 0 down is equal to matrix that length minus one so that's the last element in this case so this is the top this is the bottom right this is the left this is the right okay and now we also have our left have our right which is equal to matrix at zero dot length minus one so basically it's the last element of the sub array and then we're going to do is we're going to um basically we're going to um use a while loop and then basically what's going to happen is we're going to iterate first starting from the left all the way to the right so let's try to do this so integer i is equal to left but i is less than or equal to the right what we're going to do is we're going to add each and every single element onto the nums to the list in this case matrix at top and i so we're gonna iterate from the top so top left to the right after that's done we're gonna decrement rash sorry i should say increment top by one because we don't we want to shrink the top um down so that we can be able to move inside so move inside um or spiral um inwards and then what's going to happen is we're going to start to go from the top to down so now we're going from we iterate the top side we don't want to iterate this element 3 anymore we want to iterate this element 3 again so we just want to start it from here right so what's going to happen is we're going to starting from so i is equal to top so while i is less than or equal to um down then we're gonna do is we're gonna add our element onto the uh the list so in this case we're gonna say hi and then um and then the right so we're going to iterate from the top to down on the uh the right so index or yeah index right and we're going to move right one to the left because now we're done we want to shrink the top side so the top side and the right side and now we're going to move from right to left and once that's done we're going to shrink the down to down we're going to decrement down by one or i should say we're going to shrink the bottom border and then we're also going to eat right here and then we're going to shrink the left border and that's how we're going to do this and then what's going to happen is we're going to use a for loop again so starting from right about right it's bigger than or you go to the left what we're going to do is we're going to add each element onto the list and then we're going to move down by one so even so we're basically move down up so that we can so basically we're basically decrement down by one and then what we're going to do is we're going to iterate from down to up so like down i is bigger than or equal to top i'm gonna say i one second so i minus so we're gonna add our current element so on to the list and then we're just gonna increment left by one so that we can shrink the uh the left border and here what we're trying to do here is we basically have to have a if statement so if left is actually bigger than the right or if right it or sorry if top is actually bigger than yeah bigger than down now we're going to do is we're going to break the for loop right we're going to sorry we're going to break the while loop in this case so we're going to have this after each and every single for loop and then at the end we're basically just returning numbs okay so now let's try to run the code and submit and here you can see we have our answer so this is basically how we're going to solve the problem using a linear time complexity and n is basically big o of n and is the size of the matrix so basically how many elements in the 2d array and yeah so time complexity is big o of n | Spiral Matrix | spiral-matrix | Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]
**Example 2:**
**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 10`
* `-100 <= matrix[i][j] <= 100` | Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not. | Array,Matrix,Simulation | Medium | 59,921 |
1,599 | Had happened Hello friends welcome to my channel today appointed S tax problem list contest 1000 maximum profit of operating officer appointed 100 gram center subscribe channel 1234 more compartment subscribe Indian elections will rotate soft operation degree and torn Sudhir rotation it means running Cost ok to liquid and again play karo 4600 customer The Video then subscribe to the Page if you liked The Video then return 2 - 118 religious the provided the ok so let's example return 2 - 118 religious the provided the ok so let's example return 2 - 118 religious the provided the ok so let's example customers lots of your customers can influence the absolute and drop no passengers subscribe my Channel Subscribe To Quotations For Integrative Veer Verses In The Election 2012 Requested 6 - 649 Election 2012 Requested 6 - 649 Election 2012 Requested 6 - 649 Radhe-Radhe People Left And Subscribe Number Radhe-Radhe People Left And Subscribe Number Radhe-Radhe People Left And Subscribe Number Of People Is 700 Unknown Looters Have Degraded It 10 Second Tone And Second Seervi To * And Unauthorized No Finally Vighn Atithi 6828 To Like Subscribe And Subscribe 1111 Subscribe My Channel Subscribe 71000 Third Option A Great Soul How To Solve This I Love You All The Best Solution And Its Ultimate Solution So Let's Take A Look And Food Sources Of Functions Were Given A Minimum Proportion Profit Subscribe Button To Spoke And Id Maximum Profit Operation Adhir Wa Share The Answer Ronit Calculation For The Length Of The Customer Like Subscribe And Good Result Is The Final Report And I Will Explain What This Max 10 Rich And Doing In Passing Period Crop On Farm Current Generation Middle Aged SUBSCRIBE 10000 SO SOFT AND SUBSCRIBE BUTTON TO THE INDEX VALUE INTO THE RUNNING PROCESS VALUE SOUND SHIFT OPERATION AND THE WORLD STING OPERATION OK TOW GREATER THAN FOR DOING IT TOOK ITS CAPACITY WILL DO THE CUSTOMERS SHOULD FOCUS ON THE OPERATION SUBSCRIBE THE CHANNEL AND PRESS The Amazing Maximum Value Is The Current Profit Will Update You To The Point And Click On Subscribe Like And Subscribe Lage The Capacity Of Business Option Three Plus Points 75459 Distance Condition Loot Andhe subscribe our Channel and tap On The Amazing subscribe and subscribe the Channel - Running Cost Operation Subscribe Channel - Running Cost Operation Subscribe Channel - Running Cost Operation Subscribe And The Result Of The Return Of The Day Are Request To Gather Maximum Profit Should Win This Program Is Without That Either They Can See The Solution Accepted And Lips Look At The Best And Part Of What Happened Was That Lok Sabha How to Sew Around All the 136 Test Cases Should be Accepted by the Institute for Election Thanking You | Maximum Profit of Operating a Centennial Wheel | maximum-profit-of-operating-a-centennial-wheel | You are the operator of a Centennial Wheel that has **four gondolas**, and each gondola has room for **up** **to** **four people**. You have the ability to rotate the gondolas **counterclockwise**, which costs you `runningCost` dollars.
You are given an array `customers` of length `n` where `customers[i]` is the number of new customers arriving just before the `ith` rotation (0-indexed). This means you **must rotate the wheel** `i` **times before the** `customers[i]` **customers arrive**. **You cannot make customers wait if there is room in the gondola**. Each customer pays `boardingCost` dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again.
You can stop the wheel at any time, including **before** **serving** **all** **customers**. If you decide to stop serving customers, **all subsequent rotations are free** in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait **for the next rotation**.
Return _the minimum number of rotations you need to perform to maximize your profit._ If there is **no scenario** where the profit is positive, return `-1`.
**Example 1:**
**Input:** customers = \[8,3\], boardingCost = 5, runningCost = 6
**Output:** 3
**Explanation:** The numbers written on the gondolas are the number of people currently there.
1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 \* $5 - 1 \* $6 = $14.
2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 \* $5 - 2 \* $6 = $28.
3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 \* $5 - 3 \* $6 = $37.
The highest profit was $37 after rotating the wheel 3 times.
**Example 2:**
**Input:** customers = \[10,9,6\], boardingCost = 6, runningCost = 4
**Output:** 7
**Explanation:**
1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 \* $6 - 1 \* $4 = $20.
2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 \* $6 - 2 \* $4 = $40.
3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 \* $6 - 3 \* $4 = $60.
4. 4 board and 9 wait, the wheel rotates. Current profit is 16 \* $6 - 4 \* $4 = $80.
5. 4 board and 5 wait, the wheel rotates. Current profit is 20 \* $6 - 5 \* $4 = $100.
6. 4 board and 1 waits, the wheel rotates. Current profit is 24 \* $6 - 6 \* $4 = $120.
7. 1 boards, the wheel rotates. Current profit is 25 \* $6 - 7 \* $4 = $122.
The highest profit was $122 after rotating the wheel 7 times.
**Example 3:**
**Input:** customers = \[3,4,0,5,1\], boardingCost = 1, runningCost = 92
**Output:** -1
**Explanation:**
1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 \* $1 - 1 \* $92 = -$89.
2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 2 \* $92 = -$177.
3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 3 \* $92 = -$269.
4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 \* $1 - 4 \* $92 = -$357.
5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 \* $1 - 5 \* $92 = -$447.
The profit was never positive, so return -1.
**Constraints:**
* `n == customers.length`
* `1 <= n <= 105`
* `0 <= customers[i] <= 50`
* `1 <= boardingCost, runningCost <= 100` | null | null | Medium | null |
82 | Toilet And Asked Questions Remove Duplicate Mandsaur District In This Question In Given Or Started List And You Need To Remove Dost Element From The Reader Kissi Inverter Defeated Indra Leaves Means Frequency August Month In The Intellect Subscribe 1233 65 Subscribe Element Completely Liquid subscribe The Channel Please subscribe and subscribe Quiz Pick Up To Ko Math Hai Aur Ka Veer Notes In Range Of 0230 Volume Start - Hey Zindagi Liquid Volume Start - Hey Zindagi Liquid Volume Start - Hey Zindagi Liquid Ki Bigg Boss Ubal Gaurav Nau Seems Like A Typical Lips Problem Thumb Rule For Solving Equations Of Button Middle Age Video plz subscribe and subscribe the Video then subscribe to the Page if you liked The Video then Ek Dum Manipulation Kam Logic Comes Only One Day Multiplayer in the Latest and Greatest One Should Discord Thursday subscribe and subscribe the Channel Please subscribe and subscribe the Video then subscribe to subscribe our Channel subscribe The New Delhi Oscar Ramiro - 02 Classes New Delhi Oscar Ramiro - 02 Classes New Delhi Oscar Ramiro - 02 Classes Specified in Correct Clear Shot Also Something Ronit Interest Mila Volume Minimum Owner Alerts for B.Tech Volume Minimum Owner Alerts for B.Tech Volume Minimum Owner Alerts for B.Tech 3.5 Thursday The Internet subscribe And subscribe The Amazing subscribe and subscribe the Lutab School Quantum of Previous Word Next 150 Notification Heart Will Do Pinpointed Andhe The Best To And Loot Enter Gonna Enter 200 Will Reduce File There In Court And Will Increment Now Students And Will Keep You Updated On Tomorrow Morning And Move Ahead Inside Same Intensive Study Shift Please subscribe and subscribe to Aaj Kyun Zahar And Observe This Will Help To Remove All Notes From The National Interest Accused Inside Red Ribbon Veer 1000cc Avoid The Video then subscribe to the Page if you liked The Video then this point to and land water quality and current subscribe to the Page if you liked The Video then subscribe to the hai pet aur hai did not aur singla list otherwise this test dam 999 main college dal increase definite anil attached dot to hai main egg points this points no one will be the current attractive the current one positive Vibration one response to have list subscribe to parts that a previously pigmented rich and festival it did not agree with oo plant's main lead wave daughter current request to the Video then subscribe to subscribe our Channel with oo hu is the means loot key point Romantic Positive Episode Subscribe to Dahej channel Must Subscribe to Connect with Updated on True and Also Live Writer Logic subscribe to the Page if you liked The Video then subscribe to I Want to Implement IT Progressions Loop That In The Glorious Day Scores What Maintenance And The Amazing Spider-Man Per Maintenance And The Amazing Spider-Man Per Maintenance And The Amazing Spider-Man Per Loot Vid Oo That I Tribes Of Ko Finish Looks Good Loot WhatsApp Twitter Talk Time Complexity The Time Complexity Of Water Of Instances Of Writing To Completely To Only Works For Deaf And Dumb School You Not Giving Any Extra Space for Creating New List and Gautam Gambhir Video Conference on Ki Tanu Watching Video for Kids on | Remove Duplicates from Sorted List II | remove-duplicates-from-sorted-list-ii | Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,2,3,3,4,4,5\]
**Output:** \[1,2,5\]
**Example 2:**
**Input:** head = \[1,1,1,2,3\]
**Output:** \[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,Two Pointers | Medium | 83,1982 |
19 | given that link twist removed the eighth note from the end of the linked list and returned his hat how would you do this is today's video let's get into it hi everyone my name is Steve today we are going through a little problem 19 a very classic interview question regarding a link to list remove ant node from the end of the list let's take a look at the problem description first given a linked list remove the ants node from the end of the list and return its hat for example were given this linked list 1 2 3 4 5 and the N equals to 2 that means we removed the last second node from the end of the list removing the second node from the end of the list the linked list then becomes 1 2 3 5 the second last node is the node with value 4 then there is gap so we return the new hat no given 10 will always be valid the follow-up is could you do this in one follow-up is could you do this in one follow-up is could you do this in one pass the reason it's asking this follow-up that is because very follow-up that is because very follow-up that is because very straightforward or intuitive solution which is we can do in two passed first pass will just reverse from the very beginning towards the end and then we know the length of this linked list we know how many nodes are there in this singly linked list right and then and the second pass we'll just go towards the last towards the end node from the end of the list and then we just cut it off remember that technique we just discussed in the manual about delete a node in that singly linked list in that one we are only given access to the note that needs to be did it remember we talked about usually the technique is that we'll assign the note that needs to be deleted is previous nodes next pointer towards the note that needs to be deleted is successfully that way then know that needs to be debated is good because that's it's not linked to its predecessor anymore so it's good we can use that technique but basically back to the point what I was describing is the brute force are very into solution is to past wise to pass because first pass with Traverse from the start until the end of the mist that's one has we know the total length the second path will go through until total length minus n right then we'll just stop there and then we'll change the pointer that's to pass of course that's an acceptable solution is going to be accepted by the LJ but if you get asked the during an interview as a follow-up how the interview as a follow-up how the interview as a follow-up how the interviewer is asking you how can you do this in one pass well we have done through the problem description already one common technique for these remember that we discussed it in array problems in problems data that are associated with a race we discussed a two-pointer with a race we discussed a two-pointer with a race we discussed a two-pointer solution right we have a left pointer or right pointer another common variation of two pointers technique is that we can use a fast and slow pointer that this kind of technique are kind pretty often applies really well for linked list problems so in this problems specifically for this follow-up is asking us to do this follow-up is asking us to do this follow-up is asking us to do this in one pass the technique that we are going to apply is the 2.0 topic and going to apply is the 2.0 topic and going to apply is the 2.0 topic and we're going to use a slow and fast pointer let's take a look spoke we'll still use this example 1 2 3 4 5 and N equals to 2 let's see when asked by this problem 1 2 3 4 5 is the tail node that's it that's the last node and the question is asking us to delete the second node N equals to 2 to leave the second note from the end of the list in this case is full so the end result is going to be 1 2 3 5 as we just saw in the problem description 1 2 3 5 right there hole can we use the 2 pointer technique to solve this problem and just a quick thing which is a pretty standard way is another very common or classic trick is to use a dummy know which comes in super handy so in this case we'll initialize a dummy node say any random value minus 1 for example and then with this dummy node we'll have two pointers one we'll call slope on one first point both of them will start from demeanor and then faster as the name indicates will move fast note first fast no faster stands from Tammy note it moves on one step now it's pointing at the node with value 1 do we need to move fast no slow no at this point we need to move fast note why because we want to keep the distance between slow and fast no the distance between these two notes and a distance of n N equals 2 this n is the number that we would like to see to be deleted that note to be deleted from the end of the linked list so we'll keep moving fast because by now slow and fast the distance between them is only one and the note the end in this question is second is tune so we still will keep moving in right now this the distance between these two notes slow and fast is 2 which matches the end in this question right and then at this point we'll keep moving these two pointers will keep moving both boundaries previously we only moved fast pointer right we keep moving fast pointer until the distance between the slow and fast pointer equals to n at this point we'll keep moving both wineries why let's take a look you'll see that in just a second let's see we move both pointers right so slow what is at dummy at this position right now slow moves towards the right fast also moves towards right so in this way the distance between slow and fast it keeps AB - okay we'll keep moving it keeps AB - okay we'll keep moving it keeps AB - okay we'll keep moving slow and fast they both move at the same pace at the same time so the distance is no to you we pokey moving what's more then at this point we're going to stop so the break-up condition is fast dot so the break-up condition is fast dot so the break-up condition is fast dot next is now while fast dot next is not now we'll just keep moving why do we stop at this position what can we do at this position now let's go back to the question is asking us to give on a linked list remove the earth from the end of the list and return Issa the eighth note from the end of the list so right now the end of the list fast reaches the end of the list and this is the second note from the end of the list which we need to delete remember the tactic we discussed in the video delete node in the linked list which is to cut off this link and assign this link point to the to be deleted notes successor then we're done that's what we're going to do right then this one is gone the note would verify is gone because it's not part of this linked list anymore the link the it's only link to its predecessor is cut off it's gone and we assign the next pointer from its predecessor to this guy's successor right so this one is pointing to this then we're done as beautiful as that's it then we'll just return this dummy dot next which is this hat that's another use of keeping this demeanor or just because the problem is asking us usually for link list problems is asking us to return the hat of a modified linked list so we just returned a meet our next which is the new hat that's it that's the algorithm very simple and straight for now let's put that into the time complexity for that is just om we just go through this problem we'll just go through this entire linked list when every fast start next which is now which is doing the operation and then we'll just break out that's it space complexity is o one we don't need any extra memory all right now let's put the code into you let's put the algorithm into actual code let's see how we can do that so first well initialize a no minus one so we will have done that to you and Tammy note tell me no the next is hat that's how we associate the Domino with the given in list and then we'll have a slow note which will start from dummy and a fast note will also start from Demi and then all the trees remember the break-up condition is well remember the break-up condition is well remember the break-up condition is well as long as fast dot next is not equal to now we just keep moving which is Q movie first we'll move only fast while fast our next not equals to now first we only move fast right fast this is the line would just keep assigning fast our next tour is fast so then we keep moving remember in the very initial steps remember in the very net this is the very initial State or keep moving fast will mean fast until a distance between slow and fast is to write that's what we did and then how do we knew that what will I do is that we have will check if and it's smaller than or greater to zero at this point what we'll do is well assign slowed down next to slow only at this point so we'll keep Deborah Duck Creek will keep decrementing in will always keep decrementing in but only when n is smaller than or equal to zero will start moving slow that is at this point when n is smaller than or equal to zero slow the distance between slow and fast starts to begin and equal to n so at that point was done moving slow was done within both of them right both of them until at this point faster next which is now then we just break out of this while loop right so at this point what do we need to do what we need to do is to assign slows next remember it at this point this link is still there so we that's the whole reason that we can reach this note so slow done next dot next we'll assign this one to SLOS next that's what we did well assign this one we get this note first and assign this note towards the next pointer of this note that's what we will do here okay and actually we don't need to check whether snow done next is now or not because the because there's a note here they're given n will always be valid okay let's just do that slow next what a song slow down next but next here in the end will retain is just dummy done next that's it that's the entire algorithm that we'll put into the actual code let's hit submit and see all right accepted 100% it's just a one pass but accepted 100% it's just a one pass but accepted 100% it's just a one pass but we use the tactic of two pointers this way this will become a lot clearer and easier and we'll do it only in one pass that's a very common technique when it comes to linked list we use two pointers previously we discussed to use a left and right pointer but here we could use a slow and fast pointer which is super common and popular in linked list questions I hope this video helps you understand this problem and the solution to this problem how can you do it in one pass if you like this video just do me a favor I have that like button that's going to help a lot with the YouTube algorithm and also don't forget to subscribe to my channel I really appreciate it and tap the little bow notification so that each time when I publish a new video you're not going to miss out on anything really appreciate it see you guys in the next one | Remove Nth Node From End of List | remove-nth-node-from-end-of-list | Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], n = 2
**Output:** \[1,2,3,5\]
**Example 2:**
**Input:** head = \[1\], n = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[1,2\], n = 1
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is `sz`.
* `1 <= sz <= 30`
* `0 <= Node.val <= 100`
* `1 <= n <= sz`
**Follow up:** Could you do this in one pass? | Maintain two pointers and update one with a delay of n steps. | Linked List,Two Pointers | Medium | 528,1618,2216 |
438 | good evening everyone today we are going to do the daily record challenge of 5 February 2023 that is question number 438 find all anagrams in a string so anagrams are basically permutations of a string and we have done this question yesterday so please check out that video there will be a minor change in that code because in the previous question we have to return true or false whether it is present or not but now we have to return the index of the starting anagram index of the starting anagrams what I mean by that is let's see the example in the example the possible anagrams of a b c are so many possible like uh is CBA an anagram of it yes so we have to return the starting indexes 0 is the starting index we will return it then we come here then what are the other possible anagrams a b no because there is no e b and no b a b there is only single B then a b a not possible then BAC is the another possible anagram so that also we have to return 0 1 2 3 4 5 6 so we have to return the starting index of the anagrams so that is all we have to do and in the previous video we have seen how to find the permutations so we will change this code simply and we will get the answer we will use sliding window approach as discussed yesterday we will apply sliding window we will use two pointers the time complexity will be of N and space complexity will be constant of o2c we will just get a frequency of 26. please check out that video for exact logic and if you have done this permutation and string questions you can easily do this question so see what we have to change we simply have to change uh let's see what are this S1 is the smaller string now so here what we will do we will simply copy paste the code and we will change our S1 to p s 1 to p and s12p and we will change our S2 to s 22s S2 to S and instead of returning true we will return our answer let's create a vector answer and whenever our total characters were becoming zero that is we have found the window when we are knowing that this is the window so we will push our I to our answer and when we know this is our window we will push I to our answer so that is all you have to do just see the previous video and it is all easy see how these different questions are linked it is question number 438 this is 567 but both are linked if you can do this question you can read this question so everything is linked please keep on practicing so let's just complete this we will simply write answer dot push back hi we will post our answer and we will return the answer Vector let's just run and check whether it is working or not so yeah it is running let's just submit it so yeah it is accepted so it is as simple as that you just need to form a sliding window approach you will apply a while loop everything else is explained in that video the video will be in the comment section as well please like share and subscribe if you like the video thank you so much for watching bye | Find All Anagrams in a String | find-all-anagrams-in-a-string | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "cbaebabacd ", p = "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is "cba ", which is an anagram of "abc ".
The substring with start index = 6 is "bac ", which is an anagram of "abc ".
**Example 2:**
**Input:** s = "abab ", p = "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is "ab ", which is an anagram of "ab ".
The substring with start index = 1 is "ba ", which is an anagram of "ab ".
The substring with start index = 2 is "ab ", which is an anagram of "ab ".
**Constraints:**
* `1 <= s.length, p.length <= 3 * 104`
* `s` and `p` consist of lowercase English letters. | null | Hash Table,String,Sliding Window | Medium | 242,567 |
872 | hello hi guys good morning welcome back to a new video and this we a problem Leaf similar tree and we're going to see two variations of it as an first standard solution which everyone would know but then a one optimized one which you may or might not know or might you might get asked in an interview let's see what the problem says it says that consider all leaves of a binary tree from left to right order the values of those leaves form a Leaf value sequence so basically I'll consider all leaves of this binary tree and this will form a leaf order sequence so Leaf order sequence is 6 7 4 9 and 8 so I just want that this is the leaf value sequence of the above binary tree now they are saying that two binary tree are considered Leaf similar if their Leaf value sequence which is the above sequence is actually the same so if I have these two as the binary trees so if I want to know that written true if they are Leaf similar or not I have just written true or false then I'll just do one thing okay I'll just go and find out what are the leaf nodes get them in one sequence and then what are the leaf nodes of the other tree get also them in other sequence and then ultimately I can simply as you can see I can simply go and compare okay it is 6 7498 it is 674 98 oh yeah for sure they are LEF similar so that is the ultimate operation which I can do for us now um one basic thing which you have might have thought of is obviously that I just wanted the leaf nodes of this entire tree right and also the leaf noes let's say it is a T1 tree it is a T2 tree I want the leaf nodes of this entire tree also and just want to put these Leaf nodes in a vector I'll put them in a vector let's say this is a vector 6 7 4 9 8 and again 6 7 4 9 8 and then I can just Traverse and compare this Vector okay these Vector value should be same that is I can simple do so what I'm simply saying that I'll Traverse both the trees now traversing means a simple DFS traverser a simple traverser that and how a simple Travers looks like okay you call a recursive function DFS function in which you pass in the root node ini root node you have passed base condition is okay if the node is n simply return and if not then simply try for left simply try right that is a simple traversal condition now no now in this you can put in any condition maybe you want to print something you can print something you want to print here or here it can change it to in order pre-order post order and all in order pre-order post order and all in order pre-order post order and all that stuff so yeah this is a base traversal code piece of code which looks like okay great um now both the trees VI D will Traverse and then we get only the Lea noes but what Leaf notes Leaf nodes are okay whose left is null whose right is null that is simply a leaf node so whenever I am traversing and then if I reach okay let's say I traversed my tree okay I'm traversing and then I'll reach to a node so this line of code I will put here and then I will say that okay if I have reached my node left is equals to like null Ro node right is equal to null then I can simply return that node value or I can simply say just you have the leaf Vector right I have this Le Vector so simply push back this specific node value in my leaf Vector because I have got the leaf vector and that's how I can simply get this code done now as you can see that uh invers case or basically in any case I will have to travel on all the nodes because to reach the leaf node you will have to go onto all the nodes right so for sure the time is O of n now space is interesting it is actually as you can see it's a DFS traversal so DFS traversal it depends upon the depth or the height of the tree so I know that my DFS will go like this it will come back it will go like this four it will come back it will go like this so maximum dep is three 1 29 that will maximum depth so I know okay my recursive stack will actually be used and also my leaf because you know now I was making two new vectors Leaf vectors so that leaf space is also used so that's my time and space complexity although uh we will try to optimize this space maybe we can maybe we don't need this extra Vector but yeah we'll see let's quickly have a glance of the code how it will look like so I initialize two vectors leaves one and leaves two these will actually store okay leaves one will store the leaves nodes in the sequence of 31 and leaves two same for 32 now I'll simply call my DFS saying start from root one with this Vector As Leaves one I'll pass this vector by address saying okay push back the NES as you can see exact same tree traversal condition as we saw above if it is null simply return and just try for left just try for right and also now the condition which I wanted to add is that if both the left and right are actually null which means for sure it is a leaf node so just push back in the leaves vector and that's how I can make my leaves Vector for one of the trees and then the same I'll do for the other tree and then I will have leaves one and leaves two ultimately I have to compare that both the leaves one leaves two are equal and that's how I can simply get this Sol now the interview ask you uh bro can you improve this complexity you're storing all the leaf nodes right in a new Vector so why you would need a new Vector the first place you might not okay great um so what we can do is okay we can okay my ultimate aim was to just see that okay the first My ultimate aim was to just have a glance that the first Leaf node should be same okay then I'll compare the second Leaf node should be same okay great then the third Leaf node should be same okay great then the fourth Leaf node should be same okay great then the fifth leaf node should be same so rather than storing I can compare one by one also but how to do that's great um simply earlier your operation was done by recursion now do the operation by yourself push that node in the stack okay I'll push my node three let's say it is for my it's a stack one for the tree one stack two for the tree two so firstly I push my root nodes in my tree then as soon as I enter my stack I'll remove the top node I'll push the right okay I'll push the right I'll push the left and I just keep on repeating that okay then I'll remove the top node okay I'll remove the top node see this is removed now this is removed the top node then I'll push the right okay then I'll push the left okay then I'll again remove the top node okay in my hand right now I have six I have removed that but I have six as the top node then I have left sorry I have right no I don't I have left no I don't oh so it is a leaf node okay if it is a leaf node so simply return that stop your stack right now and simply whatsoever you had last just return that so you return the six okay so in this first iteration from stack one you have returned the six okay let's go to stack two and perform the first iteration okay again top remove from the top okay remove from the top push the right okay push the right then push the left okay sorry this is not okay push the left now again remove from Top remove the Top push the right okay push the right and then push the left okay push the left and then now I just simply okay again remove from the top okay remove from the top but see whenever I remove I actually maintain that in some variable again check the right oh I don't have the right check the left oh I don't have the left also okay no worries so this is a leaf node okay Leaf node was six only so now this stack one at the first cration will return six he will also return six so I can just say and compare oh bro it is a six so yeah for sure it was a same Leaf not is matching then I'll again have to continue I again have to continue okay then I'll as you remember last time my stack had two so I'll just say okay the stack top get two remove that remove okay removed then right side push okay right side push four left side push seven then okay remove from stack okay removed right side nothing left side nothing oh it's a leaf node so seven was our Leaf node okay great although I remove this I should remove this from here so now seven is from Leaf is my leaf node okay that is a return from this here itself a seven I'll remove from the stack right nothing left nothing oh seven is also from the leaf node great it is also a leaf node so simply my this Leaf node is also matching okay then continue so you will see now I just show you with the reference of code also so you will see that firstly I pushed my root node as you remember I pushed my root node in the very beginning right when this is done then I just check okay until my stack is empty as you can see until my stack has anything what I'm doing is I'm simply calling my this function DFS although it's return a DFS function but is it is not a recursive function it is actually a simple function it is not a recursive function right um it's a simple function which will actually just check okay what is the top of the stack it will just check okay top of Stack I will get that and store in a variable let's say node then I will check Its Right child as you remember I checked right child I checked his left child if any of them is there I'll just push them and then I'll just check okay if it is not there both of them then I can simply just do one thing okay bro um simply remove that uh or as in like just say okay it's a just simply return that and say it's a leaf node so if I just visualize you with the example itself same this you remembered so I'll just meize with this the example S1 and S2 and piece of code dry running that so you saw that I had in the very beginning I had to push my root nodes okay root nodes I pushed three and three again it will be same exactly same it's just for you to compare the code three and three I pushed now I just simply call my until my stack is empty while my stack is empty as you can see my stack is not empty it is having values so I just call this first function which is saying okay stack one use you pass the stack one to the recursive Bic to a function called as DFS again it's not a recursive function it's just the same naming convention which I followed now it should return the leftmost current leftmost element of the leaf how it will return it will go into this function again this will also keep on going until I have something so firstly I'll get the node so I just stored in my node value is three I removed okay my node value is three I remove that from my stack I if the left if I have a right child as you can see I remove that from start I had a right child right okay I'll push that again if I have a left child yeah I have also five so I'll push that also then I'll check okay if my both of them are null which means no bro uh both are actually there none of them are null okay simply then continue while equal true okay if it is continue then from the top of stack top is five okay remove that then check Its Right check its left okay right I'll check two left I'll check six okay right is there left is there great then again is it is both the Childs null both child oh it's not null okay cool simply continue top of the stack six see whenever I'm saying top I actually am saying it is top assigning that to a node so right now six is the node value same uh right and left um okay no right no left okay no worries if uh right and left both are null return the node okay yeah it is both are null so I'll simply return the node which was actually six so now from this DFS for stack one it returned the number six and the same way I will perform the operation on stack two and as you remember it will also return the six so you will see that it will six it will be six if they're not matching at any point of time I can simply return false else I can simply say that yeah it is matching now keep on continue while your stack is not empty so it will start removing other elements let's say it will remove two and then it will push my 4 and 7 then it will remove seven it will put my note as seven and then you will see that seven has no child so it will be returned as a next Leaf node and that's how you can simply Solve It ultimately your both the stacks should be empty ultimately your both Stacks should be empty because here I'm saying that until my both the stacks are non empty only then perform the operation so ultimately my both the stacks should be empty so for sure I'll simply say that if it is both the SS are empty I can simply return my answer now with this my time is still o ofn because I will still have to go onto all of my nodes but my space is actually of H only because now I'm only using my cursive stack and I'm not using I'm not again I'm not using any Leaf Vector again um if you are allowed to modify although it is not recommended to allow the input like to modify the input tree itself but if you're allowed to modify the input tree then what you can also do is you can try to build something like this and with this you would not be needing any extra space Also so it is fun is also possible but we are never recommended to modify the input so yeah that is and for easy question I think that is pretty much it I hope that you guys got it that how we can use stack to actually reduce the space and much it's much more easy to visualize cool bye-bye | Leaf-Similar Trees | split-array-into-fibonacci-sequence | Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._
For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`.
Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same.
Return `true` if and only if the two given trees with head nodes `root1` and `root2` are leaf-similar.
**Example 1:**
**Input:** root1 = \[3,5,1,6,2,9,8,null,null,7,4\], root2 = \[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8\]
**Output:** true
**Example 2:**
**Input:** root1 = \[1,2,3\], root2 = \[1,3,2\]
**Output:** false
**Constraints:**
* The number of nodes in each tree will be in the range `[1, 200]`.
* Both of the given trees will have values in the range `[0, 200]`. | null | String,Backtracking | Medium | 306,1013 |
953 | hey everybody this is larry this is day nine of the leco april daily challenge hit the like button hit the subscriber and join me on discord let me know what you think about today's forum uh vertifying an alien dictionary um yeah some another classes there uh but yeah i'm gonna find an alien dictionary so i you should do this live so it's a little bit slow fast forward 2x skip ahead watch another video whatever you need to do so okay let's see in the indian language they have english letters for them in possible different order of the alphabet is some permutation okay you're given the order of the alphabet return true of the given words are sort of like the graph of the in this alien language okay so that's not so bad we just have to see if it's sorted we have a lookup table uh essentially in an order and then we just um we can look for it one by one um so the cool thing is that we can only i mean you only need to look at adjacent um adjacent words because of the transitive problem i know that it seems like if you're in kamsa and uh and you'll probably notice that a lot of not mafi people say translated probably just say cool to sound cool but this is an actual thing of transit probably where okay if a is bigger than b and b is bigger than c then a is bigger than c right um uh if the transit property holds and this is true um and in a way um you know and because this ordering is going to be uh you know the probably holds for transit probably so that means that we only have to check that a is bigger than b and that b is bigger than c or if you want to put it another way uh which or w sub 1 is bigger than w sub 2 is bigger than so you only have to look at adjacent words for that reason so they don't have to do n square comparison so in this case n is 100 so it's not that bad but uh but yeah um and then we look at two adjacent words and then we check to see if the word that's earlier is lexographically smaller or earlier than the word that is in later so that's basically all we have to do so let's um let's get let's do it i think there is some um implementation of you know thank yous about this but uh but we can do it so let's do let's look up is to go to whatever for um index character in enumerate order we want to set lookup of c as we go to index so basically what this does is that it gets to the um get the rank if you will of the character and then we put it in a lookup table so that we could look at it all one time i think uh this is 26 characters we can actually even do better than that we can actually just um you know have a no have an array of 26 elements but i'm gonna do it this way for now because you would have to manipulate uh ascii and you know stuff like that um but so to keep it simple i'm gonna do in the hash table uh but this hash table of course is gonna be at most 26 characters so yeah um and then now we just have to go for you know for word um let's just say word one word two in sip of words word sub once uh this is a python shorthand to get adjacent words uh so every pair of adjacent words um it's actu i to say it's common-ish in um it's actu i to say it's common-ish in um it's actu i to say it's common-ish in python so we haven't seen it um i'll get used to it a little bit because it does come in handy and at least in context in uh in production code maybe it's a little bit more sketchy but i think it's still okay because these are all uh iterators so they don't actually take that much more space um but anyway like if you're worrying about it uh okay so now we have to go if uh let's just say let's just have a you know one is greater than row two uh then we return force it's first step we have to return yep and then otherwise if we go past all of them we return true and this is greater or equal i guess you want to be precise because actually no that's true i think grade is fine because if it's equal then it's okay though i don't know that it's yeah i mean then it doesn't violate the condition okay so yeah so definite we declare grade one grade two uh with one with two and then yeah and then now we just look counter by character again we're gonna um yeah um i mean we can definitely do is the same trick where we get character you know in word one with two and then if see if the lookup of c1 is greater than lookup of c2 we return true right because basically now we're doing a two pointers algorithm and we have to make sure that we go for the cases because that's not enough um otherwise if lookup is less than lookup of c2 um then we're going to already return true oh sorry we're going to return force um otherwise it's z quotes then we keep going and then at the right and what does this mean right well the two cases or three cases one is uh you know well what happened here is that the word is the same up to the min of the two words uh the length of the two words and then now the three cases one is word one is longer where two is longer or they're all equal size their equal size then it is force or if word two is longer is force so we just have to this is true if length of word one is greater than length of word two um i think that's the case that's why we have to write test and double check um but yeah so now we just have to put in more test cases this looks good but uh one thing i would also say when you're testing especially in competition you know one thing to notice is that this output is in binary right it's true of force it's boolean and what i mean by that is that sometimes you can get quote-unquote lucky and it matches your quote-unquote lucky and it matches your quote-unquote lucky and it matches your answer even though it is a wrong answer so you have to be careful about it this actually those one of the cases that i would have etched um but yeah but this looks okay so let's give it a submit and cross fingers cool uh yeah let's what is so what is the complexity of this right well this for loop is going to be o of n uh where n is the number of words because you know you could think about it as just having two pointers and they move uh they move together so that's going to be of uh n uh in terms of number of loops and then this greater function just also linear in the length of the word so that's going to be you know each word is or each character in each word will be looked at most twice once to compare to the word before and another time to compare to the word after so in that case you can kind of do the summation or amortized or whatever to get to say that this is linear and the size of the input where the size of the input is just it's not just n it's the number of characters right um where n may be the number of words but the number of characters is roughly n times m if you want to call it that where m is the length of the longest word but the words have different lengths which is why the phrasing is very precise um so and it's linear in the size of the input and of course as i mentioned before this is constant because there's only 26 characters you could also say it's off alphabet if you will be in that it is you know with the uh or all of the size of the alphabet which is all of alpha maybe which you know letter you want to use where alpha is the length of the alphabet so if you have you know uppercase now it's 52 characters or so forth right in weird order um so yeah uh so this so everything's gonna be linear time uh do i use any space no i mean other than this is constant space so yeah linear time constant space and that's all i have uh let me know what you think hit the like button hit the subscriber and drama and discord hope y'all have a great weekend and uh yeah stay good stay healthy to good health and to good mental health i'll see you tomorrow bye | Verifying an Alien Dictionary | reverse-only-letters | In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters.
Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language.
**Example 1:**
**Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz "
**Output:** true
**Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted.
**Example 2:**
**Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz "
**Output:** false
**Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted.
**Example 3:**
**Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz "
**Output:** false
**Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)).
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 20`
* `order.length == 26`
* All characters in `words[i]` and `order` are English lowercase letters. | This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach. | Two Pointers,String | Easy | null |
114 | everyone welcome back and let's write some more neat code today so today let's solve the problem flatten binary tree into a linked list we are given the root of a binary tree and we want to flatten it so that it turns into a linked list not necessarily a true linked list because you know this data structure obviously is made up of tree nodes binary tree nodes where each node has two pointers a left pointer and a right pointer but they want us to condense it into a linked list where we're not really making use of the left pointer right for each left pointer of each node it's just pointing at null the right pointer is what we're actually going to be using which is going to assemble all of these nodes into a linked list so this isn't too difficult to do but there is a catch the ordering of the linked list should be the same as the pre-order traversal of the same as the pre-order traversal of the same as the pre-order traversal of the binary tree now this isn't as bad as it sounds this is actually going to make things really easy for us and let me tell you why we know that a binary tree like this one is you know a recursive definition right a node a root node like this one could have children and then its children are basically also trees themselves right this is a sub tree the left sub tree and this is the right subtree when they say it needs to be the same as the pre-order traversal be the same as the pre-order traversal be the same as the pre-order traversal the linked list needs to be the same as the pre-order traversal what they mean the pre-order traversal what they mean the pre-order traversal what they mean is if we want to flatten this entire tree the root node is going to go first right because pre-order traversal uh right because pre-order traversal uh right because pre-order traversal uh processes the root node first so good thing is we don't have to make any changes to the root node then uh you know what is going to come next uh in our linked list to the right we want to do the pre-order traversal right want to do the pre-order traversal right want to do the pre-order traversal right so we want to process the entire left subtree meaning we want to flatten the entire left subtree uh first right we want to flatten this entire right subtree and then stick it right in the middle over here right in between the root node and in between the right child so once we flatten this thing it's going to go in between and then a pre-order traversal then will and then a pre-order traversal then will and then a pre-order traversal then will process the entire right subtree so then basically we want to flatten the entire right subtree in this case the entire right subtree is already flattened right it's made up of two nodes and it's already flattened because there's no left child for any of the nodes here so it's already flattened so really in this case our job is to flatten the left sub tree stick it in here and then we're done but okay how do we flatten the left subtree it's a recursive definition right so we're going to apply the exact same recursive algorithm here uh as we would on the root node so okay in order to flatten this tree first we have to process the first node okay this it's a root node so it's not going to change right pre-order traversal this node goes right pre-order traversal this node goes right pre-order traversal this node goes first it's going to stay exactly where it is then we're going to flatten the left sub-tree uh it's already flattened left sub-tree uh it's already flattened left sub-tree uh it's already flattened it's just a single node right so this node is going to go now that it's flat and it's going to go it's going to be stuck in between here the three is going to go here and then the right subtree here is also going to be flattened it's already flattened so no changes are going to be made here so really we're going to get rid of this node and instead have a three uh over here right so this is what the flattened is gonna look like then once we're done with that this is gonna get stuck in between here as you can see in the output uh that's you know that's what happened so all of that hopefully that logic that general recursive logic of this algorithm makes sense it basically follows a pre-order traversal basically follows a pre-order traversal basically follows a pre-order traversal now the only challenge that we're gonna have is when we do uh flatten the left subtree right over here you can see we flattened it and then we stick it in here how are we going to stick that flattened subtree or that linked list here well of course the root node which over here you can see initially it's pointing you know at its right child but we want to disconnect that pointer we want it not to point at its right child anymore instead we want it to point to its a left child over here right because we want to stick this in between so we're going to reassign the right pointer uh you know to be it's a little bit messy as i'm drawing it now right but uh you know cross this pointer out and then stick that right pointer to actually point here and then we want to change the left pointer and have it actually point to null right because the left pointer should always be null so that's what we're going to do to the root node and so the last thing we want to do is the end of the linked list right the end of the left subtree it should be pointing at this node over here right it should be pointing at the right child of the root node so the only thing we're going to have to remember is to actually get as we're doing this algorithm recursively we're going to make sure once we have flattened the entire left sub tree we have to return a pointer to the last node or rather the tail of the linked list if we have the tail of the linked list then we can connect that pointer over to the right child of the root node which is what we want to do because in the output you can see right this uh you know this linked list the left child linked list has to be connected to this which is the right child linked list right this is the right sub tree the right flattened linked list so in order to do that we have to make sure that we return the tail of the linked list so that we can actually connect these pointers so that's the main idea of the algorithm we are going to do it recursively because that's kind of the easiest way to logic through it but you can do it iteratively as well using a stack to traverse the entire tree but since we are traversing the entire tree uh the overall time complexity is going to be big o of n anywhere n is the number of nodes the memory complexity since we're doing it recursively we're going to have a call stack for the memory it's going to be the memory is going to be a big o of h where h is the height of the tree uh you know worst case h ends up being n but yeah so that's the time velocity now we can get into the code okay now let's get into the code so they do say that this function actually doesn't need to return anything all we need to do is actually just modify the input tree that we're given so we'll be given a tree node it could be null it could not be null we don't have to return anything but i'm going to actually inside this function define another recursive function called dfs we'll be doing the same thing with this function we'll be passing in the node so this dfs is what's going to flatten the tree flatten the root tree and return the list tail right because we do want it to return something that's the main reason i'm defining another function rather than just using this root flattened function because this function is not supposed to return anything but here we do want to return something because we do need to return the tail values as always with tree traversals if the input is null so meaning if we're given an empty tree or a null node then we can just return none uh reason we're returning none is because can't flatten an empty tree so the tail of the empty tree is just going to be null now is actually getting into the recursive case and you know before we even finish the function i always just write the recursive case and just assume that it's going to work so when we run dfs of course we want to run dfs or rather our flattened algorithm on the left subtree first and then we want to run it on our right subtree so assume that this dfs call is going to flatten the subtrees what is it going to return it's going to return the tail right so if we flatten the left subtree then we're going to return the left tail so let's assign that and if we flatten the right subtree we're going to return the right tail now last thing we need to do is actually connect our uh half you know our linked lists right so we're at the we're at a certain node we're at the root node right we have a left uh linked list that's been flattened and a right length list that's been flattened and remember we want to connect them now only edge case you have to remember is what if one of these lists is empty what's going to happen if both of them is empty then we don't need to do anything right if the right list is empty we still need to take the left list and then you know move it over to the right side if the left side is empty but the right side is not empty we have flattened the right side but we don't have to do anything because it's already on the right side of the root right and the left is already null so we don't have to do anything so the only case where we are going to do a uh insert operation is if the left tail is non-null right that's the only tail is non-null right that's the only tail is non-null right that's the only case where we actually have to do the insert now this pointer manipulation can get a little bit abstract so feel free to draw out a picture if you want but we're basically going to be following what i did in the drawing so remember we have a left tail and we want the next pointer of that left tail to be assigned to the current right child of the root right so root dot right so this is basically uh inserting you know attaching the left linked list attaching it to the right linked list and we also have to make sure that the root is also attached to the left linked list so we have to say root dot left b or root dot is gonna be set to uh root dot left right because this is the tail of the linked list right but we want the roots right pointer to be at the beginning of the left linked list and what's going to be the beginning of the left linked list it's just going to be the left child itself feel free to refer back to the drawing or you know draw it out yourself if you need to for this and remember the last thing we need to do is the root we want to make sure that its left pointer is set to null uh right so we're going to do that last obviously we're going to say root dot left is equal to null because you know we have to do it last because we are using the root.left's original value in this root.left's original value in this root.left's original value in this statement up above right and the reason why this line goes second is because we're reassigning root.right and because we're reassigning root.right and because we're reassigning root.right and we are actually using root.write in the we are actually using root.write in the we are actually using root.write in the line up above so this order that i wrote these three lines of code is not random we had to do it this way because we had to use the original values of the pointers before we ended up changing them but this is basically it this is the entire insert operation and then setting the left to null and we're only going to be doing that if the left uh link the left tree is non-null right and link the left tree is non-null right and link the left tree is non-null right and it's instead of even using left.tail we it's instead of even using left.tail we it's instead of even using left.tail we could even just say root.left is could even just say root.left is could even just say root.left is non-empty you know if this makes more non-empty you know if this makes more non-empty you know if this makes more sense either one is fine i believe okay and remember the last thing remember this dfs is supposed to flatten and it's supposed to return the list of the tail or you know the tail of the list so what is that gonna be isn't it true that the right tail you know the right sub tree's tail is gonna be the tail of the entire linked list or the entire tree like isn't that true that makes sense right the right tree's tail is gonna be the entire tail but what if the right tail is null what if the right sub-tree tail is null what if the right sub-tree tail is null what if the right sub-tree was empty then what's the tail gonna be okay in that case the tail is going to be the left tail right but what if the left the right subtree and the left sub tree were empty so these tails happen to be null in that case the tail is going to end up being whatever the root is right because the root is the only node it doesn't have any left or right subtrees so this is the order if one if this is null then we'd return this if this is null then we return this you know you could write some if statements uh depending on what language you're using but at least in python a little easy and neat way to write this code out is to do with boolean so uh you know just put an or in between each of these and the reason this works is because the way python evaluates it is if this ends up being non-null then up being non-null then up being non-null then last will be assigned to the right tail if it is null then it'll look at the next value and say okay is this null if it's non-null say okay is this null if it's non-null say okay is this null if it's non-null then this is what's going to be assigned to last if both of these are null then this one will definitely be non-null this one will definitely be non-null this one will definitely be non-null and this one will be assigned to last so and then we can just return last so it's you know kind of an intuitive way for me at least in a concise way to write this out so that's how i'm going to do it you could do with conditionals if you want and then all we really need to do is call the flattened function the dfs function passing in the root node we don't have to return anything because remember our root function flattened doesn't require us to return anything so just calling this function is good enough okay and actually just got a quick typo so in this line for some reason i wrote left tail dot next when we actually want the right pointer of left tail right because we're actually using the right pointers so sorry about that i hope that you caught it and it wasn't too confusing but otherwise let's run the code and it does work as you can see on the left side it is a linear time algorithm it looks like the time complexity isn't super efficient for whatever reason but i don't pay too much attention to that so i hope that this was helpful if it was please like and subscribe it supports the channel a lot consider checking out my patreon where you can further support the channel if you'd like and hopefully i'll see you pretty soon thanks for watching | Flatten Binary Tree to Linked List | flatten-binary-tree-to-linked-list | Given the `root` of a binary tree, flatten the tree into a "linked list ":
* The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
* The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.
**Example 1:**
**Input:** root = \[1,2,5,3,4,null,6\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)? | If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. | Linked List,Stack,Tree,Depth-First Search,Binary Tree | Medium | 766,1796 |
16 | Hello Hi Everyone One Second Welcome To My Channel And Were Solving Another Important Problem 30 Followers Have Already Like A Dasham Related Problems Like Subscribe My Channel Problem World Tour Of Declaration Page Numbers From Subscribe And All The Number Selected List Number 151 Target What We Can Do Inform All the Planets of the Solar System Target 100th Candidate Fennel Mingle Triplet 200 Run Extra for Life Oil Dry ginger 20 - Wash Element Canon Laid Loop Also ginger 20 - Wash Element Canon Laid Loop Also ginger 20 - Wash Element Canon Laid Loop Also Unlimited From Plus One to Nuvve and Third Loop from This Will Help to Generate All Know One Know what we will do about the appointed elements from we need to table from the abhimaan asam and strength and table subscribe from left to right in the Thursday acidification is from infinity and compare subscribe if you liked The Video then subscribe to Target I will also keep available Result will hold dialogue amid busy subscribe for you liked The Video then subscribe to subscribe Video Subscribe Carefully Subscribe 123 Number 90 Something Like 100MB Don't Worry About the Values Will 100MB Don't Worry About the Values Will 100MB Don't Worry About the Values Will Not Quetta and Solution Show What We Can Do for Solving Veervikram - 4 - Vwe First Solving Veervikram - 4 - Vwe First Solving Veervikram - 4 - Vwe First Number One Adhoi Nuvve Na Bhoole Aur Subscribe Ho Jayenge Is From The Start And So Will Be Plus One K From This Is From - No What Do We Need To Find From This Is From - No What Do We Need To Find From This Is From - No What Do We Need To Find Out Which Will Win Aaj Hum Handsome Within Himself Is Closed Down That This World Will Run Arrested After District Will Check The Same Condition With Bravery Defiant Reckoning Appointed And Will Have Two Point To Point Approach Subscribe And Share And Minus Plus Minus One Plus Two Subscribe Abhinav Bhaiya Target Vansh Smart Is Point Sunao Award You Will Meet - 3 Results Of Sunao Award You Will Meet - 3 Results Of Sunao Award You Will Meet - 3 Results Of Middle Know How To The Point Will See A Disc Friends Hum Kalyan Samiti In Which Is Lungi Target Achieve What You Want To Increase The Current Affairs 28 Shoulder That How To Increase Btu Increase Time Till Increase This Loop Target Subscribe Now To Receive New Updates - 4 Plus One Subscribe - 30 - - Verb - New Delhi - Subscribe - 30 - - Verb - New Delhi - Subscribe - 30 - - Verb - New Delhi - 110 I Urgently Need To Update Our Samvida Debit The Receiver Pimples Page 16 Updated On That [ __ ] This Is Vote Against Nitish Check [ __ ] This Is Vote Against Nitish Check [ __ ] This Is Vote Against Nitish Check Sameer Va Subscribe subscribe my channel and this I need to define jaayenge is from that i plus one and k is from and minus one here we can remove that liked The Video then subscribe to The Amazing Subscribe Thursday No Need To Play List Play That K - - 100 basis what indian That K - - 100 basis what indian That K - - 100 basis what indian humor answer hindi result very agile scrum liquid compile and was given test according to wrong answer overhead instituted of - vishesh-2010 subscribe can we minus - vishesh-2010 subscribe can we minus - vishesh-2010 subscribe can we minus plus one amazon shopping subscribe to that agency near death experience let's trial summit to Then good accepted what is the time complexity of this code APN severe running one for folk Sudhir and 2.0 code on Thursday a very easy language and spare some places in Bihar during various demands met a fierce fighting back log subscribe and subscribe the Channel thanks for watching | 3Sum Closest | 3sum-closest | Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.
Return _the sum of the three integers_.
You may assume that each input would have exactly one solution.
**Example 1:**
**Input:** nums = \[-1,2,1,-4\], target = 1
**Output:** 2
**Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
**Example 2:**
**Input:** nums = \[0,0,0\], target = 1
**Output:** 0
**Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
**Constraints:**
* `3 <= nums.length <= 500`
* `-1000 <= nums[i] <= 1000`
* `-104 <= target <= 104` | null | Array,Two Pointers,Sorting | Medium | 15,259 |
24 | hello everyone welcome to clash encoder so in this video we will see the question that is swap nodes in pairs so this is a linked list based question and it has been asking a lot of interviews for many companies for the fang also and for other companies as well so this is a medium level question so let's see the problem statement then we will see how to solve this and different techniques and then at last i will show you the code for this problem in c plus so let's see the problem statement so given a linked list swap every two adjacent nodes and return its head so it is saying that we are given a linked list so linked list is one then one is pointing to so it has a value and a pointer so which is pointing to the next element one to two and two to three and three to four and we have to swap every two adjacent nodes so we have to swap the nodes in pairs so that is two will be swapped with one three will pitch five through four so you can see the output will be two one four and three so these two elements are swapped and these two elements are swept so and return its head so head will be now swapped head will be two so two will be set with one and it will become the head so we have to return the head and you must solve the problem without modifying the values in the list node that is the nodes themselves must may be changed so that it is their question is that we cannot change the values so we cannot change the value in this node by changing it with two and this with one so we have to change the actual nodes or swap the actual nodes and change the links between them to give this output of the swapped nodes and let's see the constraints on this problem so it says that the number of the nodes in the list is in range 0 to 100 and node value will be from 0 to 100 so this won't be any useful for the value uh this you can simply we will actually we don't need this constraint so let's see so i can think of one case actually you can see we have to swap the elements in pair so if what if we get the odd link please this is for the even so for even you will have every you will have each element for every element that means you will have a pair equal number of pairs but if you have you can see the let's see these cases so in this case you can see we are given an empty link list so we will simply return empty and for this one so it is odd case so we will simply done one so that means that if we are given a number of uh number of nodes in a linked list is odd then we will swap the even number of elements but the odd will remain as it is so what i am trying to say is if we are given one two and three so there are three elements so we will swap one and two but we will leave three as it is so output will be two one and then three so that would be one of the case so let's see how we can solve this question and also if uh the interval when interval tells you or tell you this problem or ask you this problem then if he may not tell uh that uh you cannot change the values then you can start the problem by saying that you can actually change the values in the nodes without swapping them so you can start with that problem then he will give you the constraint that you cannot change the values but you will have to change the links or the actual nodes also have the actual nodes so then you will start with the problem the actual solution so let's find out how we can solve this so i have made this representation so you can see this is our input one two three and four these are the pointers one is one two and this is the output that we want two should point to one should point to four and four should point to three so let's see how we can do this so actually if you see how we can make this output so we will have to process nodes in pairs so if you see we will we cannot start the uh processing the linked list as one linked list so we will have to uh process first two nodes we have to change the links between two and one and this will also involve actually changing the link between the third node also which will not be swapped in this pair because the new node should point to the next node otherwise this link will be lost this two pointing to three if we swap this one and do so let's see how we can do that so if you have solved a reverse link list so you may get the idea of how to solve this but if you see now what we have to do is we have to do three steps so first we have to swap the link between two and one so we have to change this to here and this one should point to three so it should point to three so this is a simple thing that we have to do but for doing that if you see so if we do this so we can we will lose the uh we will lose the pointer to two actually the pointing at the node pointing to head basically we need the head also so what we can do is we can simply create a new dummy node which will point to the head so this is a dummy node which will point to head and i will tell you the solution which will be simpler one we can simply use two pointers to solve this problem first we will create a header node new node dummy node you can say and we will keep we will make a new pointer which is previous pointer which will point to this header node and we will make a current pointer which will point to the actual or the original head node this is our current pointer so now first step will be our first step will be to change the pointer between the previous node to the two because this needs to be head so at last we will not return this dummy node we will return dummy dot next which will return the actual header or the actual linked list so let's see so first we have to swap or we have to change or cut this link and make it point to two so this previous should 2.2 because 2 will be the should 2.2 because 2 will be the should 2.2 because 2 will be the starting of the new linked list or what we have to return the output so to do that this you can see the current is 1 to 1 so previous should point to current snags so this previous next which should point to currents next so our first step will be to cut this link so we can simply will do previous dot next should point to currents next then again now we have to do the next step because basically we change this pointer so one is also one two and previous is also pointing to two so we don't need this link so you know that in the output one should point to three not the not in the output but in the first app one should point to three because we will have to change this to pointer to one two should point to one in the output so we need to uh some node which should point to three to maintain this as a single linked list not break the links so let's see how we can do that so basically if you see previous is pointing to 2 and 2 is pointing to 3 so we need the 1 2. 3 so how we can do that so basically if you see previous next is 2 and 2's next is three so we can simply change the link by changing this currents next so currents next should point to this previous next dot next so then this link will uh become so this there this would be the new link so now we don't need this link will be this thing will break so you can see this link will break so now we have done two steps we have changed the pointer from previous to two and then one to three so now we need this to this is useless now you can see two is point three and one is also pointing to three so we need to point to one so see we can simply do that but you can see by changing the link uh using same pre previous uh previous pointers next that is two and two's next which is this link should point to current so this will point to current now our linked list will become like previous this is previous 2 is pointing to 1 and 1 is pointing to 3 and then 3 is pointing to 4 so this now this is the previous here is our current so this is the first step now we have to again perform this step to reverse this links these links as well so for that we can simply do that we will have to simply change the pointers this we will we have to do this all this in a loop so let me also write the steps so i will copy the steps also so it will now let's see the this steps and see uh run it on dual dry run on this example so first we will create uh so i have not written that step but we will create a dummy node which whose next will point to the original node that we will have to return as output so dummy node will point to 2 at the end of this loop so that we have to return so we will create a dummy node which will point to 1 and we will create new pointer that is previous pointer and point it to the w node first and then the current will point to the head node you can see this will point to the head node so now when we start this loop so you can see current is not equal to null and current next is not also not equal to null so current next is also not null and this is also not known and why we are checking these two conditions as i have already told this is for the even case and this is for the odd number of nodes if there are number of node so current is not null but currents next is null so there that means that one is there but two is not there so we cannot swap single element so we will simply turn one so this loop will actually not return and this is also the base case so before writing this condition you will have to check if the head is null then simply return the head if that's next is also null then also simply return the head so we will if there is no element then return head if there is a single element then also return the head because we cannot swap null element or we cannot swap a single element so let's continue the trident so you can see these conditions are satisfying so over while loop will run so previous next will point to current snags so previous next is this so this link will break and it will point to current stack so current sects is 2. so now it is pointing to two so now in this next step you can see the currents next will point to previous next so previous next is you can see previous next is two and two's next is three so this link will break currents next this link will break so we will simply break this thing and it will point to three so you can see we have done two steps so we have broken this link and one is pointing to three and previous is pointing to two now we will follow the third step to point the 2 to 1 because 2 is also going to 3 and 1 is also 0.23 is also going to 3 and 1 is also 0.23 is also going to 3 and 1 is also 0.23 which is not useful so now we will remove this link and you can see previous next so which is previous nexus 2 and 2's next was 3 so we will make this to 0.21 so now we have done make this to 0.21 so now we have done make this to 0.21 so now we have done these steps now our output is you can see previous and it is pointing to 2 is pointing to 1 and 1 responding to 3 and three is pointing to four sorry for the unwriting so yeah so zero is pointing to a two and you can see we have successfully swapped these two nodes and we will have to continue doing this for all the other nodes while the condition is true so to do that what we have to do you can see these two steps are for in actually incrementing the pointers so this previous should point to now the current so crown current is one as you know current was pointing at one so previous should come at one okay this will come at one and the current will go to currents next which is three current wise is here and now it will point here so now you can see now uh you here you can see the previous is at one and this current is at three now same steps will occur now one will start pointing to four which is currents next previous will start pointing to four and then the uh this four will start pointing to three and first of all we will break the link basically currents next which is three four so three will actually start pointing to previous next which is null here so three this pointer will point to null because three is at a last element so this is not pointing anywhere you can see in the output so it will be becoming null in this condition this 3 will point to nothing so it will become null so it will break now we have to now point this 2 is 4.4 you we have to now point this 2 is 4.4 you we have to now point this 2 is 4.4 you can see and 3 is null so now to point this four to three this is the condition you can see this is the step previous next dot next so which is uh once next four and fours next which is null and will now point to current is on three so four will start pointing to three and at last we will get our output you can see uh sorry this is not the uh this will be two one and yeah two one four and three and at last when this loop ends we will simply turn previous next as the output so our output will be previous next so uh the time complexity actually for this will be o of n because you will be simply traversing the linked list one time so the time complexity will be of n and the space complexity will be o often it will be constant because we are not uh creating any new linked list so we are simply swapping the links and we are creating just a constant or you can see just a new pointer so which is counted as constant so it will be same for any length of the linked place so let's see the code i hope you understand this so let's see the code support will be in c plus so i've already written the code so i will explain you so it will be similar to the algorithm that i have shown the steps so you can see so this is our function in which we have to write the code so here we are given the head so it is of type list node which is having two values value and the next pointer so now we will check if head is not head is null or heads next is null so these two conditions are for these two cases you can see the base cases are already provided in the question so if it is null so we will simply return the head which will be null only and if there is a single element then we will simply turn the head also again help because we cannot swap the simple a single element so you can see now we will create two point uh this new first of all we will create a dummy node so this new head is a dummy node so it will point to uh it will yeah here you can see this previous so previous will point to new head as i told in this step so uh yeah so here you can see previous is pointing to the first it was it is pointing to this dummy so it we have initialized it to a dummy node and the current will point to head so head is one so current spanning to one so now we have to start our loop while current and current snakes is there so this is for the even case and this is for the odd number of nodes case now we will follow over three steps first we will break the pointer or we will make the previous point to the currents next so this pointer will start pointing to two which is once next currents next and then we will break the link between this current next and we will make it point to the three which is two's next or you can say previous next so it will point to three now and now again we as we have to change this two and ones pointer also so we will make this two point two one so that is that can be done by previous next which is uh previous next two and two is next is uh this link was broken and it was made we made it two point two one which is current then again we have to continue for other nodes as well so we will increment our pointers in each iteration of these two so previous will come to current position and current will go to the next element and again the same steps will start and at the last we will simply turn this dummy node this was the dummy node so we don't have to return this so we will return dummies next so now let's submit this question so we'll also provide the code in the description so i will highly recommend you to first solve this problem yourself and quote it and then if you are not able to then you can go through the solution and then write the solution yourself again so you can see it was submitted successfully and you can see it is faster than 50 of the solutions and it took less memory than seven point six percent of the solutions so i hope you like this video and this was a iterative solution and if you want me to make the solution for the recursive uh way then yeah please write down in the comment section i will also make the video for the recursive solution thank you for watching guys do like subscribe and like share this video with your friends thank you for watching | Swap Nodes in Pairs | swap-nodes-in-pairs | Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[2,1,4,3\]
**Example 2:**
**Input:** head = \[\]
**Output:** \[\]
**Example 3:**
**Input:** head = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 100]`.
* `0 <= Node.val <= 100` | null | Linked List,Recursion | Medium | 25,528 |
1,361 | hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 1361 validate binary tree nodes you have n binary tree nodes numbered from 0 to n minus 1 where node of i has two children left child of eye and right child of i return true if and only if the given nodes form exactly one valid binary tree if node i has no left child then left child of i will equal negative 1 and similarly for the right child note that the nodes have no values and then we only use the node numbers in this problem which just makes this question even more annoying so let's look at some of the examples that lead code provides us and think about whether or not this is a valid binary tree so in this question as we can see this is a valid binary tree why well there's only one root each um you know node has only one parent and it has at maximum kind of two children so this is a valid tree this one however is not a valid tree why well this node three has two parents two and one we can only have one parent for a node so this is not a valid tree what about this one this looks like it could be a valid binary tree but notice that this direction here is bi-directional which means that we bi-directional which means that we bi-directional which means that we essentially have a cycle in our tree here and you're not allowed to do that typically in trees you have you know a parent which has a left and a right pointer but you don't have a pointer up to the parent so this is not a valid tree so this question is more of a question of building your binary tree which is the first step of this question is to actually you know build the tree or at least build whatever you can of it because we'll see that there's a lot of edge cases here so we're going to try to build the tree and the second is going to be to validate whether or not our tree is actually valid and there's going to be three edge cases that we want to watch out for the first edge case is going to be cycles right this is the case where a child points to its parent and then the parent points the child obviously we can't have that the second thing we want to watch out for is actually going to be multiple uh multiple roots oops multiple roots right what if there's just another node kind of like 2 floating out here and it's not connected to anything obviously this is not a valid tree because you have multiple nodes that could be the root of our tree so this 2 isn't connected to anything and therefore we want to watch out for that so we want to make sure essentially starting from whatever we think the root of our tree is we want to make sure that we can actually visit all the nodes in the tree that we have given to us and if we can't visit all of them then that means that there's one kind of just floating in space and therefore it's not a valid tree and the last thing we want to watch out for is going to be multiple uh parents whoops parents and obviously this is this case here where three has two parents which is not allowed this isn't a graph so we can only have one parent for each node and the only node that's allowed to have no parent is going to be whatever our root note is because obviously the root does not have a parent it is the entry point into our tree so that's what we want to do we want to build the tree and then we want to validate it and we want to watch for these three things as we go through it's quite a meaty problem this question is more about the edge cases and how you handle them as opposed to the actual logic actually validating the tree isn't that bad it's just making sure that all three of these things are you know not violated that makes this question annoying it's more of technically difficult to implement than it is actually conceptually so let's go to the code editor and type this out it is quite a long and meaty question so we're gonna break it down line by line i'll see you in the editor okay we are in the editor and we need to write the code for this remember that we essentially need to build a binary tree and validate whether or not it's valid given the criteria that we have so we don't have the time in an interview setting to actually code up you know a binary tree class and then a binary tree node class and all that nonsense um so what we're going to do is we're going to mimic a binary tree by simply using a dictionary to mock the binary tree and what we're going to do is we're going to have two dictionaries one storing the relationship between parent to children and then we're going to have children to parent so that way we know all of the relationships in our tree so what we want to do is define those two dictionaries so let's do that so we're going to say parent to children we're going to say collections dot default dict list and obviously it's a list as the value because a parent can have multiple children and then we're going to have child to parent and this is going to be a dictionary and that's what we need to do so now we actually need to build the graph so remember that n represents the you know each individual node and then left child of i guess i where i is one of these n nodes will represent the you know left children for that node and then the right children for that node so we're gonna say four node in range of n so we need to build our graph uh sorry our tree we're gonna say that left is going to equal to whatever left child of node is and then we're gonna say the right child is going to be whatever right child of node is now remember that a node can have you know an empty left or right child so we need to account for that so we're going to say if left does not equal to minus one and remember minus one is if the node uh has no left child we're going to say okay if there's a relationship then we need to say that parent so the parent of our node is sorry the parent is the node and the child is obviously this left so we're going to add to our parent to child relationship we're going to say the node is the parent and we're going to append to it that we have you know a left child now what we need to do is we need to actually double check that the parent is not already part of the child to parent dictionary for you know this node left here because if we have that then we have a cycle so we're going to say oops uh let me not mess up my indentation here we're going to say if left not in child to parent we're going to say child to parent of left equals node and what this is doing is making sure i think i said cycle earlier sorry disregard that essentially what we're doing is we're checking if this node is not already in the child to parent dictionary if it's already in there that means that this node left has another parent and we're in this case here where a node has multiple parents which obviously isn't valid so if the node is already in the child to parent dictionary that means that it already has another parent and therefore we have two parents that's not allowed so if it's not in there that's fine we can add it to the dictionary but if it is in there then we simply need to return false because we have the case where we have a multiple parent situation and that's not allowed so we're going to do the same thing for the right node we're going to say if right does not equal to -1 so basically right does not equal to -1 so basically right does not equal to -1 so basically if the right child exists then we need to reflect that in the parent to child dictionary so parent children of node we're going to append that right child and again we need to make sure that this node right doesn't have multiple parents we're going to make sure that this node here is its only parent so we're going to say if right not in child to parent we're going to say child to parent of right is going to equal to the node otherwise we have the case where again we have multiple parents that's not allowed we're going to return false so at this point we have built our tree and we have taken care of the case of multiple parents here we can be sure that at least the case of multiple parents is taken care of so we don't have to worry about that going forward now what we need to do is make sure that there's no nodes kind of just floating in space unconnected to anything else for example like we say we had this tree here which is valid but what if there was a node like four just floating out in the distance here then this would not be a valid tree because all of the nodes are not connected and now we have like two roots the four could be a root and the zero could be our root so therefore we need to check that only one node in our graph actually has no parent so what we're going to do is we need to figure out what our root candidate is because that's where we're going to start our search through the final you know graph to make sure that we can actually visit all the nodes so we're going to say root candidate is going to be none and we're going to be double checking that we can actually visit uh sorry that there's only one node that doesn't have a parent because we can't have multiple routes right so we're going to say four node in range of n we're going to say if node not oops not in child to parent basically if the node is not in child dependent which means that this node doesn't have a parent remember that the root node is the only node that's allowed to not have a parent so if the current node that we're working with is not in the child to parent mapping that means it's a potential candidate for root candidate but not so fast we need to make sure that root candidate is actually none because if there's another node that could be the root then therefore we have found two nodes with no parents and therefore we have two nodes that could be the root and that's not a valid tree so we're going to say if not root candidate that means that we haven't already found a root candidate so we can say root candidate is going to be equal to our node otherwise if we've already found a root candidate and now we found another node that doesn't have parents we have to return false because that means that there's two potential root candidates and that's not allowed so we're going to return false here so at this stage we have essentially found a root candidate but turns out we haven't actually found a root candidate because it's possible that there is no root candidate so we actually need to check if root can candidate is none basically if we weren't able to find a root candidate for some reason then we need to return false so that will take care of finding the actual root now what we need to do is make sure that starting from the root we can actually visit all the nodes and we don't get caught in some sort of infinite cycle here so we want to use a visited set to basically keep track of the progress through our tree because remember we're using graphs on our graph here sorry we're using uh dictionaries so we could potentially get caught in an infinite cycle if we were using you know just a standard graph so i keep saying graph if we're using a tree data structure then we'd only have the left and right pointers we couldn't go up the tree on accident but since we're using this dictionary based uh way to represent the tree then we could accidentally get caught in some sort of cycle so we need the visited set to actually tell us where we've been otherwise we can just use a standard breadth first search traversal to actually build this graph tree sorry i keep saying graph uh we're gonna say q is going to be just a standard uh q here so we're going to put in the root candidate because that's typically how you do a breath first search through a tree you start at the root and then you just visit all the nodes so we're going to say while q so basically while we have something in process we're going to say that the current node is going to be equal to q dot pop left and we're going to say visited dot add whatever the current node is now what we want to do is we want to visit all of the children from this current node so we're going to say for child in parent to children so the parent node is our current node and we want to visit the two children we're going to say if child uh let's see child to parent of node um does not equal to the current node so basically what we want to do here is to check whether or not the node that we're actually going to uh its parent is actually the current node um although i think this might actually be extraneous because we've already checked for the double parents but i'm just going to leave this in and i'll double check at the end if we actually need this but essentially we just want to make sure that our child node here um oh sorry this should not be no this should be child so we want to make sure the child that we're working with its parent is actually the um the current node that we're at so we want to make sure that there's that relationship actually exists uh and if it doesn't if this child's parent is pointing to something else for somewhat weird reason then our graph is the graph our tree is not valid and we need to return false here like i said this question has so many edge cases and so many ways where you can get caught in a trap that it's really annoying and you're gonna have to be very careful when implementing this if this you know statement uh doesn't fire then we can continue through processing so we're going to say cue the append child and that will basically go through the entirety of our tree here and we'll be able to validate it that way and the last thing that we need to do is we just need to return whether or not the length of visited equals to n so basically when we did our full traversal through our tree d were we able to visit all of the nodes and if we weren't able to visit them all then something went wrong somewhere and this is not a valid tree so let me just run this make sure that i haven't made a syntax error which i seem to have uh line 13 if left oh not in okay there we go and okay cool let's submit this and it works cool uh let me just double check that we actually need this line here because i think we already checked for that uh let me just double check this kind of debug it as we go and okay cool so we don't actually need to check whether or not the child's parent matches the current node because i think we already do that up here making sure that the actual relationship is fine so um yeah that you can get rid of that line actually or you can leave it in it doesn't really matter um okay cool so what is the time and space complexity for this god-awful problem so for this god-awful problem so for this god-awful problem so to build the graph is obviously going to take you know big o of n time where n is the number of nodes in the graph so that is going to be the you know part there to find the root candidate we're going to have to go through a range of n and again this is going to cost big o of n time and then to perform your bfs through the tree is also going to be big o of n where obviously n is the number of nodes in the tree so your total run time complexity is going to be big o of 3 n but we know that asymptotically this is the same as big o of n so we just write big o of n space complexity wise we have these two dictionaries which basically map the uh relationship between all of the um nodes here and i believe in the worst case what could end up happening and i'm not sure on this one is that every node is connected to every other node in the worst case which means that our space complexity could be in the worst case big o of n squared because every node uh would be connected to every single node so it'd be like a weird graph structure where like every node is connected to every other node and in that case it would be big o of n you know n components times n minus 1 connections we get big o of n uh let's see big o of n squared uh space complexity for this one because of how complex the graph could potentially be um in that worst case so i believe that is your space complexity i'm not a higher 100 sure um i think that would be the worst case where your graph is like connected like that uh if that's not possible then it should just be a standard big o of n um but i think to stay on the safe side i want to say it's big o of n squared where basically each node is connected to every other node in the graph therefore you get that you know big o of n squared space complexity in the actual graph structure here that you have to store so that's going to be how you solve this problem just to recap because there's a hell of a lot you need to do here the first thing you need to do is build this graph i keep saying graph i'm sorry it's a tree we build the tree here and we want to make sure that each child only has one parent we need to make sure of that we need to make sure that there's no cycles in our graph and we also need to make sure that there's not multiple roots in our graph so this part makes sure that we don't have the multiple parents and it also builds the tree this part makes sure that there's no multiple roots and then this part makes sure that we can actually visit all of the nodes and don't get caught in some sort of infinite cycle because if we got caught in a cycle then our because we have the visited set we would break out of the iteration early and we wouldn't actually visit all of the nodes so that is your three things that you need to check here be very careful with this problem like i said there's a lot of edge cases there's a lot of places you could go wrong when solving this problem i would really make sure you understand what each line does and why we need it because it's very easy to forget this especially if you see it in an interview uh let's see who asked this question um okay it looks like facebook twice but this okay so this question i don't think it really gets asked too much if you get this in an interview you know just hopefully you remembered build the tree validate it and you want to look for cycles multiple roots and multiple parents but it seems like it barely even got asked and this is like six months to a year ago and people only reported facebook twice so most likely this question is not being asked because of how infrequent it is i would trust this leak code um frequency numbers pretty well um but otherwise yeah just be very careful with this one there's a lot of edge cases make sure that you catch them all otherwise you're going to be in for a rough time if your interviewer expects the perfect solution which this question as you can see took me a while to figure out so that is how you solve validate binary tree nodes quite an annoying question but really not the end of the world it's a medium an annoying medium but it's not that hard if you enjoyed the video please leave a like and a comment it really helps with the youtube algorithm if you want to see more videos like this please subscribe to my channel i make a ton of leak code videos and other videos about working in fang so if that interests you please subscribe otherwise thank you so much for watching have a great day bye | Validate Binary Tree Nodes | tiling-a-rectangle-with-the-fewest-squares | You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree.
If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
**Example 1:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\]
**Output:** true
**Example 2:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\]
**Output:** false
**Example 3:**
**Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\]
**Output:** false
**Constraints:**
* `n == leftChild.length == rightChild.length`
* `1 <= n <= 104`
* `-1 <= leftChild[i], rightChild[i] <= n - 1` | Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m). | Dynamic Programming,Backtracking | Hard | null |
407 | try again 47 traveling where he wanted to given an m-by-n matrix are positive to given an m-by-n matrix are positive to given an m-by-n matrix are positive and girls representing the height of each units now in a 2d elevation map compute the volume of water it is able to trap after waning bottom M and n are less than 110 the height of each unit cell is greater than 2 and less than 20,000 I'm gonna consider this map oh 20,000 I'm gonna consider this map oh 20,000 I'm gonna consider this map oh yeah so it's like a dirty 3d version or 2d version of a height map I feel like I've done this before though not this one but like I've actually done this in real life because back in the day we're playing with maps hmm Wow M where m is less than an intern ok and each element is less than 20,000 which you could almost than 20,000 which you could almost than 20,000 which you could almost discrete nice well but a lot of people like solving this one 861 I should have used to bathroom first there but well I mean if this is the hardest problem then maybe it is a bad idea I could we use top yeah so yeah I haven't been here in the beginning to chat look there's an emoji now you know how that I don't know how that works actually bit I don't know how I still don't know how to work that I don't really look into it but I mean conceptually this is what I usually understand I don't think everyone agrees with that but the question is like what's a queen way of doing it right like this could be some weird like breadth-first search east of maybe even breadth-first search east of maybe even breadth-first search east of maybe even in pine mm-hmm can you do binary search how does it help better yeah that's like that yeah exactly that's why I'm thinking of in terms of find out that I mean by binary search like can I like you know in step down incrementally yeah but I mean I think like this is also one of those problem where like in the theory is not that hard right but like it's gonna be so many edge cases and like you have to calculate the boundary first and then you have to calculate what's inside and then you have to make sure that all your searches are kind of on the same level it's actually reminds me a little bit of but not and it could not in the easy way like one of those the game go the board game go where you have to like surround them and then get to we move stopped at inside but not really or something like that but uh it's not yeah it's just very hardware matically right like we could I think like the algorithm point everyone has a general idea like and it's just all about the edge cases I dunno I'm gonna use the bathroom then who if I'm gonna stop this I don't think I could do this very quickly wait really dad to d1 I guess I should practice that then alright because you never know it means I'm impossible it's just very annoying uh as well okay I think for each I'm just trying to also think a slick way well you know easy to implement way to kind of figure this out and okay so we could and you talk to me is great and so we could treat the boundary as so I think that's what I'm gonna end up doing no and then just we each one just here what is my how do you declare a boundary I'm sorry hundred ten can I might artists like well what does it mean to be contained when you do it when you're made of a deaf where search it means or the know or Wi-Fi search or just search it means Wi-Fi search or just search it means Wi-Fi search or just search it means that so you do it especially I knew you just look at the it's Morris like how does it take a count of one as it just leaks way yeah I mean I'm just also just trying to think about like what does it mean to be contained like how does it know that's meant to start and just go I guess if it doesn't reach the boundary yeah okay um I think I would just do that and do one on each cell it's a two star 10,000 and on each cell it's a two star 10,000 and on each cell it's a two star 10,000 and at that first search so like that's linear so that's 10,000 squares I'm a de linear so that's 10,000 squares I'm a de linear so that's 10,000 squares I'm a de Tolosa we have to do so we have to do this like yeah I mean it's still only a grammarian okay let's figure that out that hmm I'm Richard I guess I'll start by doing something really naive and then figure out how to optimize as I go and I guess as long as it doesn't reach the boundary then that's okay I accept is backwards is it somebody matters I'm consistent 20 times nu times 10,000 okay yeah I'm pretty screwed 10,000 yeah you're right quiet I need to 10,000 yeah you're right quiet I need to 10,000 yeah you're right quiet I need to be quite for a search I was ringing initially deaf research but 10,000 a initially deaf research but 10,000 a initially deaf research but 10,000 a I should be Stack Overflow area oh I wasn't thinking about backside but I think you could I mean in your case you could play do a binary search on the Mac side BAM well maybe try to do something a little bit clever I think that's the I think one thing is that in the example the in example the lakes if you will other in the same height but I think that's not actually generate the case right but you have one that's like well even just this picture you can't see me pointing at it I don't know why I point at it but uh like on the right side reviewing it's just like one unit down then it still at the same answer but it's not the same height Oh No looky here no it was definitely interesting you oh yeah I don't know if I could do this on a live interview and that's maybe like given an hour to so I just keep going let's just vote at this height and this is hard actually I mean I guess everyone knew that but so I'm at the one what is the boundary put a 1/2 DB but 2 what is the boundary put a 1/2 DB but 2 what is the boundary put a 1/2 DB but 2 is still high yeah also I just realized that when someone was using the term for Phil that's literally maybe a pun yeah I think that's what I'm like trying to think what that means like you definitely like put in a number and then like okay maybe I need to maybe that's what I need a binary search I can't do it I think I'd a missing that n times m times x and was up I had some other ideas but right now I'm not sure it's right here you want just to co-opt it to me want just to co-opt it to me want just to co-opt it to me how do you like how do you know that you can also like throw the two and not worry about it you know that's like a minute huh mini ho maybe I just do the math on the number of cells that underneath and then just assume that this would already be under it okay that's probably that idea not super sold on it to be honest it's popular actually one two four yeah then you would hit the boundary and then get that for search or by first search in my case would just have nothing and then the answer would be probably nothing right just like so no this is not that's the height that you want times space that are affected okay really max and Q it and so I don't keep track of what I've seen so this will actually just one infinitely yeah that's kind of what I'm doing but in a weird different weird way yeah see this yes it's like 1 2 1 ok let's try to some of the stuff that you say sisters now I can't find it we'll go over that so I'm just looking to chat and try to find it okay three two let's see if this is pointing it should be zero okay that's right mm-hmm some other educators that's right mm-hmm some other educators that's right mm-hmm some other educators this is like really tricky they're just doing one look like that's a twenty thousand one that borders and then just betting in the middle and it see what happens so definitely my car is that way I know just tell me at least one more case with us wrong and it just happens to be way and I shampoo patina meeting all the same I should get something that's four times bigger than what it should be okay type a bug in my code I feel like the have the right idea I just don't have I just have to hash stuff this is the same height then we've done it before every good we could work but they're all different than if this would be right put that test as well then okay maybe not so actually but that could so we started adding input so my code is where I Daniel and the fourth one but not the third one which is fine okay that is true because I just double count some stuff it was doesn't mean to tell me it is part of the same Sun that is the same height of okay and that's the only case where that double counts oh let's see okay that's cool I'll keep that in mind okay am i confident enough to submit it yet I mean I think in terms of code it's okay we receive it once time limited that's the only concern I have and I'm too lazy constructed big text oh well okay I may be an empty away which is fair mm-hmm I be an empty away which is fair mm-hmm I be an empty away which is fair mm-hmm I might feel like I've been good about testing that today but maybe not on this one cuz how to do whatever about it I mean if this works then I'll explain my solution by the time limits exceed it oh man how close am I huh well 37 to 40 I think this is I think my coat is ready but I need to figure out a way to optimize it slightly more and hope that if this was an insight and this is the Bossman's maybe by I mean - this is the Bossman's maybe by I mean - this is the Bossman's maybe by I mean - ends at where n is ten thousand square so yeah like cutting it close where I was hoping yeah and also made with C past and maybe it is as fast enough I don't know it doesn't even tell me how cuz usually just have one test case it tells you enough hmm so yeah okay so I do have to do something smarter than locate every cell then an N square thing it is and this don't athletes my question is yeah so this is like slightly optimized version of the one to hype you cannot follow what can I do better on this one I mean it Allah made a layer of em so how do you like I'm a mom one how can I tell that three is the true border and not the two apparently disco wasn't so bad I guess I just need to be linear time better for sure I would starting today okay well I think maybe the other way to think about it is maybe same thing is what I did on the last one which is instead of thinking about things sticking in them from inside out I could think about things I'm outside in and if I'm trying to your lemonade borders what does that mean like I stuck him aboard and I like that one get me how do I walk down to one and maybe set it to the way you move out maybe I would do some scanline thing like we did with 1t trapping waterway okay can you do them now that I think about it can you just do the one deed well thanks I still want to solve it can we decompose this with do I don't think about having one thing data yeah I can't you just weird topography stuff Chris even though you're in this section things can be low and then tactics out okay now Nick you can really the other way to go is just the outside-in method maybe by mmm I'm just now I'm just trying to think about how to formulate it hmm but this is how you would do a proof for someone their window but yeah they say my description is that for each so I just do a breadth-first search up to just do a breadth-first search up to just do a breadth-first search up to that height and then basically you just take like a cross section of that number which just correct but it was definitely a smaller way so hint nope no hints Thanks look normally scissors in my submission history right so I mean I don't have to worry about losing this code fit like we've got assessment times are crazy I'm just I'm trying to say hey wait a minute I'm telling foam lay down as well you could buy my way of thinking about it maybe a little bit is that instead of like walking there inside stuff and finding out you know maybe I mark the outsides toughest like not good or something like that and then slowly we'll get to the middle where you just look at it in terms of the borders something like that I'm not saying it that well yeah I'm still trying to wrap my head around what that looks like to be honest so that's why I'm not articulating it that well and we start on the lowest first and like they say this is one start at 1 what does that mean you know mind you talk it is adjacent and it's three and four okay well today we'll we is bigger than just neighbor so and you always get to do it first okay I think I have a general idea then please ask me questions to explain if I don't know okay I mean let me try to hack something up and then I will try to explain it and keep asking me because I have an intuition about it but I had to really articulate it but okay I don't have to lead it everybody's the beginning parts having that forest fire let's say jeribai I get the first one more glass don't count some corners meet Edison actually whenever possible like a thing just cleaner now we just go further to test right we got something you do clean up slightly sometimes but now your CV now because we prioritize by the lowest height if you see any on the border you're gonna only see higher Heights especially the beginning but we have a boy is he safe or no support at some expense but we see three okay I think I have a better intuition about it too I had to think about how to replicate it like it's one thing to know how to figure it out and it is another to like well by serious form again in like two months how can I figure it out other than just remembering the answer which is helpful but not necessary Nessus sufficient and even put into too yeah he's my one you it's gonna like that maybe even more by something I'm in the hole no there's the pen okay that's where I'll meet white glue me I don't relax the originals because then you first time you see it time it's everything dad on the outside already processed so I just so 3 mm test 2 don't the packets which now has an expensive so a full same thing that's all that's missing this one right so one of the two or so one in one or one soo yeah I mean that's what I do I mean I vote in a funky way but yeah just this equation should only happen if height is bigger than the height map or lower then I missing one relax someone should hearing some one of these edges shifted up one I guess I hit up this one happens first so then this happens first and his hits up this one so it's seen that okay I think I see why it just a case but I didn't wanna get someone a border first today or maybe this relaxation is make sense so now it's getting party of one up in here but because just got a party of one so it should be party of three okay that makes way more sense okay how do I fixed it Oh uh yeah I mean I think you caught me about it's doing it yes exactly okay let me see if it works for I click test cases suppose I mean I would say I do like this from I don't know if I would have 26 minutes ago okay so much faster I'm gonna tie this one it's tiring with 26 I mean that's to me 20 minutes to do it again so it took me I don't need any I'm saying yeah how would that explain it no worries and I'm gonna try to make sure I understand it as well so I took actually a little bit less than an hour which is I guess okay but part of if Venus okay so yeah so I think the other way I was thinking about it so my own solution was one where like we're taking cross section so at every possible and every possible point we try to throw it to that height and then some aboard it or the chorus section then chunks to get the answers at that time they made it because that was n times M Squared which I guess 100 is a little bit big and I was hoping that was squeezing maybe in see buzzes okay fine not her still well it'll be pretty tight I mean even now I'm pretty tight so well I got away I was thinking about is like inside instead of like pinging inside like a lake over your cold oh my god this is my Lake how do i flood fill so then like I don't reach outside I did the opposite thing we're okay if I'm on the outside how do I it's not of what feel per se don't do the words are interesting but it basically is like okay so we have stuff from the outside how do we get things in right and the big one there is kind of well one is that I used to probably cue just so that as I think it makes because you can think about it and like okay this is the level that I'm falling and you start from the lowest because otherwise it gets a little weird maybe no that's the way I talk about it and then once you get into an int and then I put everything on a border on it queued in a priority queue so it's sorted and then you just keep on going through the bottoms until you've reached an inner one and in the one is going to be the first time because we already put everything on a border in and everything that's not in the border will be a possible hole or lake a possible place where you could trap the water so that means that if you so if you're already at a height in which something interior is shorter than it meaning that you know you haven't seen it yet but it's shorter than you know that means that this is dam instead uh for that space that's inside everything surrounded is at least that height right and everything else is higher because but almost like a I would say almost like an induction thing if like I it's very hard for me to kind of visualize it so please bear with me and keep asking questions I you know I have patience it's just that no articulation there's a little trickier but given inside square right the first square that is going to be you know like I say relaxed in the sense that is like the BFS but like dice true a type relaxation like the first because we do this like sorted by height the first cell that is going to be the next to two cell that's interior that's also shorter it's going to be the shortest of the neighborhood surrounded like surroundings that make sense think that good stuff but once that's the case yeah you count that is that height which is what I forgot to do for a little bit but and then you kind of also count down as pink one coat on the border way creeping in and then you kind of keep doing that and you're always so if you have an interior cell that is lower than you know a surrounding height it will always be at least that high all right okay I know I'm not explain let me see if I could find a way to regionalize it okay I'm just like you want some ASCII map ASCII boy at least okay so let's say you have something like this right so the first few other versions like okay I'm just going to use it x2 kind of like okay we have to kill all these stuff so we done all the ones and once I clearly know next to stop that a taller way and then now I'm just covering pace a bit we could contrast it instead of me just well you know and then now we do the twos so that this too is okay I want a border that is right so all the tools are kind of just done now and like and everything surrounding is bigger so get that okay this is where it gets interesting is when we once we do - gets interesting is when we once we do - gets interesting is when we once we do - we it doesn't really matter which we get or win in which order even but so let's just go this one right let's say would you use a circle so let's say just three so now you're doing this and you're like you look around and the next to it is a two-way and in this case this - is a two-way and in this case this - is a two-way and in this case this - it's obvious lesson three but it means that because that this is the first time that the two is being added to the queue damn instead on a border - like everything surrounding it is at - like everything surrounding it is at - like everything surrounding it is at least three wait the stab one kind of make sense at that point because if like I said it's almost kind of like an induction type thing where if there was a two in the border then this rep reached already right like that's a if there's a that's it like in a parallel universe where this is - this parallel universe where this is - this parallel universe where this is - this is actually a - then this would have is actually a - then this would have is actually a - then this would have happened earlier and then this we have gotten relaxed earlier right and because that is in the case by you know because we sort it and that's like the order we processed them when we have just demonstrate and with everything that like if there was a way to get to this cell that's dent we would have already happened but because it's the way then that means that everything is now that means three is like the border of your current cell so that makes sense and because of dad well you just kind of difference right and since it is 2 so you have 1 2 the count because this should be hiked worried and then now you could say you could think about that is like now you're flooding it from 2 to 3 so you could even effectively change this cell to cell today which is kind of what we do without changing the height back so I guess you know change to a height map but we add that to the we push it to the key with that with 3 instead and now this done and then now this is your new kind of state for the map and then now yet you also prior to curing in some way doesn't really matter what it could be this one it you know it's a party key right like Eddie's in this case it doesn't matter maybe another pump because now this is on the border right now this is your new map and I say you do this one then you know that so you do this one so this one gets processed as part of like two surrounding things so then now test case done and now this is a toy and then let's say that she's just to tease real quick and now you did this one and the same way you just plus two because now you haven't you know you and a thing and it just plus two to it right and that's it and then now you keep on processing and everything it's already in the priority queue I think so yeah so that's kind of - it's not an explanation that's kind of - it's not an explanation that's kind of - it's not an explanation where's a walk-by it's a step-by-step where's a walk-by it's a step-by-step where's a walk-by it's a step-by-step and yeah I mean that's it's like let me know that's a okay another explanation for but uh yeah it's not I mean it's definitely not an easy problem so I mean I think but I think that like it's just a very hard part on an interior I don't know if I could do it to be honest fashion under pressure like now I'm not really under pressure I mean I got one solution that it's not optimal and maybe in an interview that's what I would have gone with and that's good enough I mean I don't know if it's good enough for path but it's good enough for me in that like you know that's how I could solve it and I could explain that part too but uh yeah sometimes you just get unlucky and problems if you in an interview I don't know what to say to that in general even but like sometimes you have bad day sometimes yep good days and sometimes you're in T really gives you an insane problem sometimes they give you something that maybe not even insane just like yeah something that you're more familiar with familiar where for whatever reason maybe you study the night before and Karen oh lucky yeah I mean sometimes that's part of the process I know what to say about that before this point yeah so what is the complexity so just M times n times blog times and I think because that's the size of the queue that's the space and time because you do every cell once you know - some born new tracking but that's know - some born new tracking but that's know - some born new tracking but that's constant number of times and yeah like I said if you get this other thing I don't know I would say this one yeah I mean I don't know sometimes it is I mean I it is just a hard problem I mean there's no way around it I don't know how to justify this one but yeah I mean it is kind of fun but it's I mean I think the and the coding is not that bad once you understand it in theory but you know that's not it that's not easy to understand and I don't know if I could have I mean I think some the way I came about it is kind of and this also has a little bit luck on my side as well is kind of one thing that I've been coming oh this thing for myself and you know some of it you have to figure out a way to be south refraction so refracting about it have a way to self-reflect it about it have a way to self-reflect it about it have a way to self-reflect it is kind of like one thing I noticed when I study and when I kind of like when I don't get a problem right what am I getting a wrong one and this happens for sim in a couple of ways similar things like a dynamic programming even this happens a lot more for me where some problems are not symmetric meaning a lot of problems in dynamo well maybe not a lot of theories in these kind of coding things a lot of problems are symmetric and dynamic programming meaning you could go forward or backwards but some problems you can only go in one direction and I'm and very often I forget to go to our that well I forget to even think about in the other direction and that's something that I'm trying to think like it's still a way to kind of do the opposite of what you want to do in a way that makes that gives you properties that makes sense I don't know if that's I don't think that's like a really actionable thing for anyone other than the future Larry who kind of look at this farm again because I hope I forget it soon but yeah I think like sometimes like an analogy would be like you look at a straight form and you're going from the beginning to the end but maybe sometimes it's easier to think about it from the end to the beginning right especially when you do like growing window in some case it was not going when they're sliding windows or a two-finger algorithm or windows or a two-finger algorithm or windows or a two-finger algorithm or whatever you want to call it sometimes it's easier to think about it going from left to right sometimes it's got easier to think about it from right to left so it's not quite I mean this is not quite analogy but that's what I was trying to think about how to do with kind of like okay you know doing this stuff for search for each one and try to figure out what's on the border like I just couldn't think of it I just couldn't get it right like I mean really we were here for like maybe not dialogue that long but like a good amount of time watching me trying to figure out how to get around that thing about like okay if I'm in a lake how do I find out the boundary right instead I was like okay let's spin myself in the head around my head it's been the palm on his head and that be the palm yeah I spin the problem on his head and be like okay what does it mean if we play first search or something like that from the outside right and that's kind of how I got to this thing eventually I mean you kind of watched the tapes it took me a couple of minutes so it's not like I was like ah yeah that's now it's obvious and I was like well like how do you do it therefore search for breadth-first therefore search for breadth-first therefore search for breadth-first search from the outside way and that's how I got a take a look at this just Kirstin image and I was like well I guess you're you know like at the tree I know that I want to go inside but how do I want to make like how do I know that tree is the right level and then I think from dad I was like okay well if we put something where we go on the border and like going from the lowest up kind of almost like filling it up one by one maybe then you know maybe that's how the way I do it I mean I was playing around with so I was in like great Catherine about it I think another way of thinking about it is yeah like for each cell on the border you're throwing it up to the nearest neighbor incremental E or like kind of I mean in it's not quite how I express this but like but you can think about like oh you're Emily or the once at the same time because like that's a the water and they're like that's a the ocean level sea level yeah the sea level is going to one and what does it look like the sea level goes up to two what does it look like and then so forth progressively and eventually you go find a hose and I just and then it's that idea and then expressing it in code in a way that allows you to code it in a queen wave versus like you know some kind of fold up that goes for the entire finger the entire time and then keep track of what's on the outside and water inside or something like that yeah anyway I think that's my finger about this problem hopefully if you are interviewing you don't get this one I think that's a little bit too high for me though it's way I think it's kind of fun but you know on an interview may be fun is not what you optimize for | Trapping Rain Water II | trapping-rain-water-ii | Given an `m x n` integer matrix `heightMap` representing the height of each unit cell in a 2D elevation map, return _the volume of water it can trap after raining_.
**Example 1:**
**Input:** heightMap = \[\[1,4,3,1,3,2\],\[3,2,1,3,2,4\],\[2,3,3,2,3,1\]\]
**Output:** 4
**Explanation:** After the rain, water is trapped between the blocks.
We have two small ponds 1 and 3 units trapped.
The total volume of water trapped is 4.
**Example 2:**
**Input:** heightMap = \[\[3,3,3,3,3\],\[3,2,2,2,3\],\[3,2,1,2,3\],\[3,2,2,2,3\],\[3,3,3,3,3\]\]
**Output:** 10
**Constraints:**
* `m == heightMap.length`
* `n == heightMap[i].length`
* `1 <= m, n <= 200`
* `0 <= heightMap[i][j] <= 2 * 104` | null | Array,Breadth-First Search,Heap (Priority Queue),Matrix | Hard | 42 |
452 | So today we will do the problem of minimum number of burst balloons. It is a medium level problem. Once you read it, people will understand. So we have made some starting point, so this is the diagram, so this diagram of points is correct, so it is 10:16, you and the correct, so it is 10:16, you and the correct, so it is 10:16, you and the rate. Is 16 17 whose height we do not know, okay, our start point and okay, we will leave some arrows from the This diagram is important. If you had made this diagram then you would have faced a lot of problems as to what to do. Right now this problem is needed so the date which line is right then this is the answer return. You have to do it now if You will think that what we are doing here to find out the minimum number of is that we are trying to see how much is being intersected. Right, here if you are tu and six which is common, here this is the common part and here this is the interval of two. If you look at it, this and this is the common part or we will take any two if they intersect and its interval is three. Basically, what is the problem that we have to see the intersection of two points or two, its interval. Common internal is okay. If we get the common interval, then our answer will be as many rights as there are common internals. So now if you see, this is our input, so it is not an input but here it is sorted, right, so first think you notice that whatever inputs have to be sorted, right. Once we sort it, we will unite it. Right, from one and six, we have 2 and 8. Right, so here we will do this one and this one from both, in the coordinate, if this is D, the common region from here is one. Hey, if you give pulse then both will go, okay, so this is it, so what we have to do is that in all the points given, we have to make a new ray to see the interval and whatever number of points remain, that is its length. We have to return right because now we have got two lengths right one and tu six and 10 * 12 so if we return this length then 10 * 12 so if we return this length then 10 * 12 so if we return this length then date it is R Answer Okay so what will we do now we will see the remaining points that weather. One and six, what will be the remaining seconds? We have to check in the sorting list whether there is travel between dem in it, so now we will direct for that, okay, we will do it from one because we have already kept one pulse, so we will check from one now. Is if you look close always start ka maximum and ka minimum starting ok understand previous and meaning which previous and what will be our start right first index we also had to check that we have basic what we have to do is minimum Take the right of both, hello mini, if this value comes out then this is our one. Okay, back to the second number of the previous element, minimum and previous and commerce, what will be the meaning of what will be in this how, minimum is six and out of one and tu, maximum is tu. So you and six are stored in our output. Okay What does it mean that you and six are here? If there is a common part then right, what if it was 7 and 8? So now we should have two values in the output. So now we should have two values in the output. So now we should have two values in the output. If we have equalized the code then we will submit this solution That's it, you can optimize something else too, you can do it but this is one of the solution, ok | Minimum Number of Arrows to Burst Balloons | minimum-number-of-arrows-to-burst-balloons | There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_.
**Example 1:**
**Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\].
- Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\].
**Example 2:**
**Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\]
**Output:** 4
**Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows.
**Example 3:**
**Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\].
- Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\].
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `-231 <= xstart < xend <= 231 - 1` | null | Array,Greedy,Sorting | Medium | 253,435 |
452 | hey what's up guys John here and today let's take a look at another difficult problem yeah let's continue our little journey here number 452 minimum number of arrows to burst balloons okay so you're given like a range of up along so for each belong it's a 1d one demand dimensional like coordinates basically the balloon doesn't have any y coordinates only the axe and the pallone hat either as a belong has a range in the x-axis and you can shot you can the x-axis and you can shot you can the x-axis and you can shot you can burst up along by an arrow as long as the arrow is in the range after belong so each balloon consists of start and end for example here we have a we have four balloons here right let's do a quick joint here so from 1 to 6 right that's the first belong second one is from 2 to 8 right two to eight third one alright there's like 7 to 12 right seven here 7 to 12 right the last ones tend to say 10 to 16 turn 2:16 right so and you need to took how 2:16 right so and you need to took how 2:16 right so and you need to took how to write a program to find out what's the minimum arrows you need to burst all the balloons right so in this case you can as we can see here the minimum arrow we need is two arrows right basically we can shoot you can shoot anywhere between two and six right becomes true de niro right somewhere in here right to burst balloon these two balloons right and then the second arrow will be shooting from right here somewhere here right between turn 12 then we can post bursts the rest belongs all right so as you can see as you guys can see it here we already join this something like inna did in a certain sequence right so with this kind of problem you know with the range of the this the race with a segment with a range of a race we hurried to a sorting right either by the start or by the end and this problem can be solved in both ways right so the first approach let's do a sort by the start right so let's assume if we restored by the start of the balloons right and every time I said I and when we loop through the and will be keep maintaining like a star and the variables to record the current endings right so that every time when we see a another balloons right we check if there if the current balloons start time is still with is still in the range of end right basically the start times it's not greater than the end then we know we can burst this belong with the same arrow right and then until the start is has it has a bypass the current end then we know we need another era of the purse the current one basically this is a kind of like the similar is greedy idea here so basically we are with the first arrows return the first as many balloons as possible if we can't then okay then we know we need another arrow right and similar idea of is the is sorting by the end of the balloon right same thing here if we sort by the end of the balloon here I think we can do it's a little bit simpler because we know we don't need to worry about the to maintain that a little bit easier to maintain the end here because if we sort by the by start time right and let's say we have a one six right one six let's say the second one is there is two four right if we sort by the start time and every time we see a like another balloons we also need to update our current end right because since now we see us another end here we need to get whichever is smaller because if we are maintaining this one trying to includes disap along inside our first arrows now this one will become our new end and let's see if there's a lot not another five to two to ten here right okay so our basically what we're saying that the first arrow can only burst balloons until four right because we voices is smaller than 6 so we update that end and then when next time when we see the 5 here we know we needed a second another arrow to burst it but if you're sorting by the end if we're sorting by the end of the balloon all we need to charge is the it's the beginning it's the start off the balloon if the start belong is it's in within the range after its end then we know we can purge that belong otherwise we just shoot another arrow both way works I think sort of from start is a little bit more intuitive because that's the that's how most people think about this problem right we start from the first one and then we just burst right as many as we can okay cool let's try to call this thing right and the first one will be stored by the start time so if we sort by start time it's sim we just need to do a simple store right because by default this sorting will be stored from solve is the first element right so we don't have to do anything extra regarding the sort function here and we don't have an answer here and so initially I'm gonna initialize with one here because the self because at the first we will need to initialize this end here right and we can call the previous en right current end and we do current end right current end and we do a so the first thing was going to be the starting of the going to be the first element right and the end that will be our current end since we are assuming okay since we're assuming we always have an answer here we need to do a check here if not point right if not points then we need to return zero because we are assuming we have a point but if there's like an edge case if there's nothing in the point here we just simply return a 0 here so now we have this right so now it's simply do a for loop here right for loop for point in points right so we for each point here we simply check if this if the start okay if right if the point start right that's the start will be 0 is less than we smaller it's not greater than the current end excuse me if it's in Vaes in the range right if it's the current one has not bypass the current end we just do what we simply do all we need to do here is that we know we can burst this disp along with the current arrow right all we need to do is we just update the current end right like we said since we need to keep the minimum end for other belongs we can burst so far right minimum current end and they steer to the sorry the point one right house right I also was house if the point is outside of the current end then we know first we need another arrow right second the current end will be simply the point one because there's no need to maintain it because we know basically we're starting with a new arrow right and in the end we simply return like the answer here you know this should just work yeah for some reason my internet speed the word elite called website is kind of slow it takes longer time to submit the code yeah you really should pretty quick yeah cool it works so basically that's the first approach where we will be stored in by the start time right but for the if this if you sort by star type other than just compared with the start and end to chat if the current arrow is in the current point is in the you know in the range of current arrows we also need to somehow and maintain this end right okay cool that's the first one and how about second one second is pretty straightforward only the difference here let's say we store the right since the TiVo store is sorting by the first element and now we are going to sort by the second one so it's going to be the key we're going to write a simple lambda function here and there is ax X what right so now we're sorting by the second element same thing we'll keep everything the same here but instead here right with so and we don't need to maintain this thing anymore right and we just simply do a check here similar thing here right we just do a I'll remove this which is simply to a if point zero right if the starting point is it's outside of the current end of the current and right then we know the we need another arrow right class one and of course we need to maintain this just update this current end with a point one right yes it I think that's it for the first sorting by the / end outfit up sorting by the / end outfit up sorting by the / end outfit up along it should just work yeah cool so I think as you guys can see the sodium by the end is a little bit easier not easy I mean it the code is a little bit simpler than the assorting right start time right because if we sort by the end time since we are guaranteeing the end time is from smallest to the biggest there's no way to maintain the end time anymore all we need to try to leave all we need to check if is the start time it will start time is it before the end time right if it's not then we just we need another arrow okay cool I think that's pretty much it is for this problem I hope you guys enjoy the videos and thank you so much for watching it and I'll be seeing you guys soon bye | Minimum Number of Arrows to Burst Balloons | minimum-number-of-arrows-to-burst-balloons | There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_.
**Example 1:**
**Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\].
- Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\].
**Example 2:**
**Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\]
**Output:** 4
**Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows.
**Example 3:**
**Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\].
- Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\].
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `-231 <= xstart < xend <= 231 - 1` | null | Array,Greedy,Sorting | Medium | 253,435 |
1,770 | hey everybody this is larry this is day 16 of the september leeco daily challenge hit the like button the subscribe button join me on discord let me know what you think about today's problem uh i am still in dublin or at least i'm back in dublin uh i just drove for a long time from belfast uh you've this is where the intros from uh yeah i hope you enjoyed that intro i'm really tired right now it's about like 1am with a lot of drivings um hopefully this farm will be okay uh let me know what you think okay today's farm is 770. 17.70 maximum score from performing 17.70 maximum score from performing 17.70 maximum score from performing multiplication operations okay so you're given nums and multipliers and you want to perform exactly m operations okay so those don't match each other or the number the size don't matter don't match uh and there's m of them and we want to perform all of them so choose on the i operation you take the beginning or the end okay we turn the maximum after our m operations okay so i think this is probably just gonna be uh dp is what i'm thinking of uh let's see m is 10 to the third so what how many so one thing that you may ask is how many uh what's the pr or what's the complexity right i think it's very easy to kind of confuse yourself with the complexity for this one that may be the tricky part i think this one is pretty okay so let's go um uh yeah let's uh let's do this i'll show my dog process a little bit more quickly so definitely as i write the code so we'll go over it um let's kind of write it as uh i mean this is still going to be dynamic programming we're going to do it top down just to illustrate but let's do it as dumb as possible say um and of course i say this with uh um a little bit of a dynamic programming background so if uh so definitely if you struggle with this one try easier dynamic programming problem first try to figure out how to not just solve them but also really get good at explaining and understanding the complexity that's what i would say first and this one i think has a fun uh analysis so let's take a look so let's just say we have max okay fine max score we have left we have right you know just to show how many things we used and then m index right for the index for multiplier okay and then okay so i mean we write it like i said we write it as naively as possible uh let's see i just want to make sure that m is smaller than n i thought i read that but i wasn't sure so basically we take the beginning and the end right so basically the um yeah so if m index is equal to m then we return zero right if we run out of m's otherwise we have two max scores we can do right we have left plus one right and we don't have to worry about checking for stuff because it won't go uh over right that's the idea and this is the other one and we choose the left we add the score of numbers up left times m index is not true obviously uh and then the other one is num sub right times multiplier multipliers m index right um so this is left score if we take it from left this is right score and then we turn max of left score right score and i think that should be good so then we set it up by uh you know just do it zero right all right let's run it real quick right so this looks good uh just to make sure i didn't have any typos or anything silly i've been doing that a lot lately so don't so let's not assume that you know uh that was going to be good okay so that's uh let's just create a little bit more um this should time out because we haven't memorized um okay i mean this should time out so it seems like my theory is correct um and the reason is because now it's it does like this two to the end thing um and then we reuse a lot of things right so you know uh let's do a time complexity really quickly let's say that we know how to memorize um and we do a time complexity right what are we doing well left the way that we usually say is okay left can be 0 to n right can be 0 to n m index could obviously be 0 to m so and time complexity is going to be equal to or total time maybe total time complexity is equal to uh time per input times number of inputs right you could do unit analysis there and check out and of course if you say time for input is going to be o of one just because you know that's where we memorize these are all one operations uh and then numbers number of inputs is equal to o of n squared times m that's from you know these n and m and then you go okay well if i did it this way clearly this is 10 to the fifth times 10 to the third and that's no bueno right um so that's first thing man i'm just wondering why whether i got it wrong because that would be funny if that was the case uh should be okay but yeah should be okay um okay well the for the first thing to kind of re-analyze this sorry i just want to re-analyze this sorry i just want to re-analyze this sorry i just want to make sure in my head a little bit because that would be really sad if i explained the wrong solution for like 10 minutes and then i'll be like oh wait i miss him well the first thing to notice is that left doesn't go all the way to n right if n has way too many numbers it doesn't matter because it's bounded by m so same logic here uh and we can reduce this to m cube right um if we let's say we do it to this right um the second thing to kind of recognize is that even though this has three um three inputs what is happening there right um one way that you can you know mathematically see this is that you know left plus right is you go to n or something like this um which is like we said is bounded by m so let's just say left plus y is equal to m right then now well then what does that mean uh well left first right doesn't equal to m per se but it will start off that way and then how did i say this sorry i know what i'm oh i think i do maybe i'm wrong but i'm trying to kind of find a way to explain it in a understandable way and maybe that's another but well the full formula i guess maybe we can think about it this way the full formula is that um let's say we use m indexed right so m index is you know uh let's say numbers used is to go to m index plus one say right uh or maybe just m index actually yeah right and also left plus uh let's just say m minus right because we can forward the middle numbers which is another way of saying it so that now we're bound left plus m minus y is also equals to u number used right so here maybe i could write it in a queer way right so numbers used as you go to m index numbers use is also left plus this thing so you know why not set it to each other right um and that's pretty much the idea uh for this one and as you can see you know you could do some mathematical things so um you know we move m right and then now we minus m left on the whatever side uh you know and now we have this formula what does this mean right well that means that you know um we know what m is m doesn't change we so given two of these variables we know the other one that's the basic idea that i'm trying to prove here right if we know any two variables then we can find the other number so that means that now instead of m cubed the number of inputs is equal to m squared and now 10 to the third uh squared is just uh you know 10 to the six which is a million so that's basically the idea on how to get this to work um also again python maybe too slow we'll see but that's basically the idea uh yeah so that's uh let's kind of figure that out and now let's just say we keep track of left and m index just because they're easier to use so then now we have cat or is cash is equal to do times n plus one four two m plus one uh and then cash is just equal to none right uh you can set it uh let's get rid of this so that it's easier to use i'll just put on the bottom so at least if you could look at it if you really like but uh yeah okay uh yeah so now it's just about the caching and then now if has cash left and again left cannot be greater than m just because you can use more than that right so we don't have to worry about hopefully we don't have to worry about our balance i might have off by ones pretty bad about those but anyway it has cash then we return has cash left index otherwise has cash um index is going to true also this is i got a wrong year to return to cash not the hass cash obviously uh and then now cash of left index is equal to this thing and then we just return the cache hopefully this is fast enough but this is fast enough for the test input anyway uh see much faster i wonder because a million is always a little bit sketch on the code to be honest and quite fun especially memorization we will see let's give it a quick submit oh wow last time i did this it was very slow so we'll see if this is time limited it might be that the code is silly and make us time limited anyway but this is generally the idea and it should be in theory good but we might get time limit because the code is silly okay fine and let's do so without saying you won't cross uh i mean i think i could uh i could write it top down but still that's a little bit sad what did i do last time yeah i wrote a top down huh and it still took nine seconds huh there's still a better way this is such a leak code silliness hmm this is such a lead code silliness because a million should obviously be fast enough but uh yeah maybe that's why there's so many downloads not quite i mean i could write the bottoms up uh i don't know if we're learning anything per se at that point uh i'm just curious and that's what that's why i have like so many wrong answers it's only 40 minutes two to two because i was trying to convert it to c surprise let me see what i did i'm maybe i had a typo here that doesn't seem wrong seems mostly right i mean it seems very similar to write it but i guess after i fixed whatever it was i have a time limited anyway uh at about the same number of test cases that's really silly i don't know what to say well i would say um i mean if you've gone this far give yourself a panda bag you've uh you've done mostly good enough if you ask me but let's see what is going on here i mean i don't know what to say to some typos but and yeah i mean uh i was wondering whether i did some other things uh that made it um i made it uh fast enough for her hmm yeah i don't know i'm trying to think whether there's a better than m square solution but i really don't know that there is a isn't um well friends uh maybe this is why there's so many downloads it's way tiring uh okay well i would say hopefully the explanation was good i am i don't even know if this passes anymore to be honest uh so i don't even know let's see i don't know they've they did reduce the number of tests but durian 50 you know all right i'll try to okay well i guess if there are fewer test cases maybe they made it a little bit better there's 60 last time though dirty six hours i don't know all right let me er let's convert this to bottoms up um and then i mean i already did it in the past a year ago but you know these things are always good to practice uh let's see the hard part about bottom up conversion um is just about um it's about uh making sure that you do it in the right order so we'll see if we can do in the right order so let's see let's just say i in range of m maybe and then here uh also m or m plus no just m uh okay and then right as you go to as we said uh what did we say uh right is equal to m plus left minus m index which is i that's actually for consistent sake let's call it fm index uh hopefully this is right i don't remember this is enough by one from here what did i say uh is this right i'm just looking here m minus now this is just minus one so okay i mean this was roughly right for big o but uh yeah so this is this plus one so right is going to be this minus 1. okay hopefully this is right we'll see and then now dp of left m index okay is equal to max of dp left plus one well this was going the other way so uh oops i guess we don't need to write oh i guess we do need to write to make it easier to mean we'll clean this up in a little bit um because we're doing it the other direction which is a little bit awkward for sure or it's not right um okay right so that means that this plus one um okay so we actually want to start at one maybe and then hmm going the other way so much easier though yeah maybe let's just do it this way then here in that case we will go from let's see maybe not let me think about this so okay so m index this is the previous well so we can just say uh let's say minus one right so let's go to these and then is that even right i don't know wait hang on this does require uh because i did it from the other direction this requires some a little bit of larry thinking but this is basically the idea and then at the very end we should be able to return tp of i guess max of whatever dp of i m for i in range of um something like that um but we still have to get this formula quite a little bit better let's see what is the base case now the base case is in the beginning we have nothing so dp of zero is nothing right because we've used zero on the left and the zero on m index okay and then now we just have to do it the other way where okay um this is equal to so it could have the last number could have been from the left side or the last number could have been from the right side right if the last number was the right side and left in change okay fine i think this is slightly off just gonna run it real quick just to see that i forgot a comma it's also mn minus one let's see yeah the last one was on the right so then white was already modified maybe hmm now this doesn't go all the way that doesn't seem right now this part's okay but the white is wrong isn't it what is going on here let's see my maybe my formula for the right is a little off by one okay so left right m index actually because i shifted n as well so also oh yeah this has to be from zero so many silly possible errors zero then right is so n is three so zero and two sounds right one and three doesn't sound that right though one two right should not be three what is wrong with this maybe i've messed this up what did i have uh okay so m plus left minus m index is equal to right did i mess that up maybe i messed it up to begin with is that right m indexes one now i guess left can only go up to m index including m index maybe that's why okay this is still wrong yeah i think we can also just translate it in a less oh in a dumber way okay f m index 0 what was my old code okay so we can do something like copy and paste this real quick okay let's go to zero then what uh dp of index of left well we haven't used it yet i guess so otherwise minus one i think plus one tp as you get a max of itself or i don't know why i did it the other way actually another thing about it anyway plus okay so this is just me pushing then i always forget i don't use the push dp way often is what people call it these days right hmm well at least i got one question right they have a type of by one they seem close uh maybe my base case as well let's see should it be zero well if it's zero left should be zero so should be okay maybe i need to continue oh no because this is push so you definitely don't continue um is off by one would i have tested so then now we uh we put the first one on here plus one on here so then now it's minus one now this should be right this is i use m as a proof by bounding it but the actual thing should be n because it's from the right side okay wow that was a very silly mistake we'll see if this is fast enough though i don't know because lead code clearly is a little bit silly with the test cases if not oh then god oh my dirty way wow that's even worse than before so i just uh i'll keep it up i was just trying to clear my mind uh i don't know what to say on this one other than that lead code is again being really silly because this is a pretty tight 10 to the six right i don't think i did anything funky i mean other than calling max functions so again huh did i do the if finger check no i just did it this way um i mean yeah maybe i did this but i think that makes a difference i thought that they did fewer test cases but maybe they just made it harder um i mean we can allocate less memory but that shouldn't matter that much and this is me on vacation trying to do a quick one and lead code is just being stupid like check your things man check your code i mean i don't know if there's a python code that works fast enough without like some like i don't know more manipulation i don't want to spend all day on this uh on like things that doesn't matter right like algorithm is the thing that matters and unless you're doing something really uh you know really whatever then let me actually also guess i should have took this case well there's a lot but i mean this yeah i mean look is it great now is it a bad also no like i said there's no way for anyone to know if this is good enough uh because this looks pretty good to me that was slightly faster i mean this is a common trick but i don't know if this is gonna be fast enough but i'm gonna yellow submit i guess probably not because this only did 33 cases oh my i don't know what to say friends uh thanks for wasting 25 minutes of my life i guess that's uh that's what i would say maybe i could have wanted that's what is 90 this five seconds should not be faster than 96 percent of code that is just ridiculous maybe i could have changed this as well but i don't even think i mean it gets dominated by these function calls so i'm just copying pasting to my discord hang on i had to wake up early but thanks the code all right uh that's all i have for this one uh i think i did all the explanation already maybe not on the bottoms up one to be honest um but really i just did the top down and i converted it i'm really out of energy right now uh thanks leeco for nothing thanks for wasting my time thanks for raising everyone's time i'm kind of uh annoyed today uh not gonna lie just because i have no words anyway uh stay good stay healthy to good mental health i hope you stay have a positive attitude and like me today i'm just too tired to deal with this but i will see you tomorrow see you soon uh good luck and i'll see you later bye | Maximum Score from Performing Multiplication Operations | minimum-deletions-to-make-character-frequencies-unique | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of the array `nums`.
* Add `multipliers[i] * x` to your score.
* Note that `multipliers[0]` corresponds to the first operation, `multipliers[1]` to the second operation, and so on.
* Remove `x` from `nums`.
Return _the **maximum** score after performing_ `m` _operations._
**Example 1:**
**Input:** nums = \[1,2,3\], multipliers = \[3,2,1\]
**Output:** 14
**Explanation:** An optimal solution is as follows:
- Choose from the end, \[1,2,**3**\], adding 3 \* 3 = 9 to the score.
- Choose from the end, \[1,**2**\], adding 2 \* 2 = 4 to the score.
- Choose from the end, \[**1**\], adding 1 \* 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.
**Example 2:**
**Input:** nums = \[-5,-3,-3,-2,7,1\], multipliers = \[-10,-5,3,4,6\]
**Output:** 102
**Explanation:** An optimal solution is as follows:
- Choose from the start, \[**\-5**,-3,-3,-2,7,1\], adding -5 \* -10 = 50 to the score.
- Choose from the start, \[**\-3**,-3,-2,7,1\], adding -3 \* -5 = 15 to the score.
- Choose from the start, \[**\-3**,-2,7,1\], adding -3 \* 3 = -9 to the score.
- Choose from the end, \[-2,7,**1**\], adding 1 \* 4 = 4 to the score.
- Choose from the end, \[-2,**7**\], adding 7 \* 6 = 42 to the score.
The total score is 50 + 15 - 9 + 4 + 42 = 102.
**Constraints:**
* `n == nums.length`
* `m == multipliers.length`
* `1 <= m <= 300`
* `m <= n <= 105`
* `-1000 <= nums[i], multipliers[i] <= 1000` | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before. | String,Greedy,Sorting | Medium | 1355,2212 |
868 | find and return the longest distance between two arches and once in the binary representation of n if there are no two adjacent points in the by the representation given integer then just written zero so two ones are adjacent if there are only zeros separating them so the distance between two ones is the absolute difference between their bit positions for example two ones in one zero one have a distance of three opposite three we take one sorry one zero one so one two zero one distance again zero to zero one distance again 0 to 1 is a one distance so total of if you add all these this would give you three answer result and distance so how what is the distance which you need to calculate here the longest distance between two adjacent ones so if there are one zero one is this so either it can be interested with Once only or adjacent once means in the middle it can be it can kind of any number of zeros but it should contain any one you will contains one then that will be adjacent okay it's something like a girl or just into a girl and in the middle if there are boys there so these two girls are adjacent to each other in the sense if we consider only the girls so it's the same similar manner if we take only the months these two ones are adjacent to each other and the length is here one two zero is one zero to one is one so total of two in this case it's length of one because one to one distance is a length by the representation of n so what is the approach to solve the problem so let's take by the number 22 only first let's say how do we write the binary number so 2.0 super one two power binary number so 2.0 super one two power binary number so 2.0 super one two power three two power four okay as you know 2.0124 as you know 2.0124 as you know 2.0124 8 16. so adding up what numbers will give you will it gives q22 so 16 plus 4 that is 20 plus 222 so it's nothing but one zero sixteen plus four plus two will give you 22. so in those positions you represent one rest of them will be zero so this is nothing but binary representation of 16 number so now with this final representation you have to see the adjacent bits so what are the adjacent bits one is these two okay next if you see that uh one adjacent to this uh the bit adjacent to one is this bit so here it's a distance of two and here it's a distance of one so which is maximum of two and one plus two so you have to write in two as the answer that is what they have explained over here and if you see the next example a it's panel representation one zero you could see only one is present in the binary representation there are no any other one so there is no adjacent ones present in the representation hence you've written 0 in such case okay so now let's see how do we solve this problem so what we'll have is we'll have a variable called length okay neutralized to zero and max length so this is a resultant length actually which lies to zero length means you will find length of 1 and length of two but you have you need to have one more variable to Store max length right so initially you'll get one next you'll get length as two so you have to see maximum one and two that is what we have to do and we'll have one more Boolean value let's say found one okay so let's initialize it to false initially found one is set to false that means we haven't yet found the one bit with this with the number one so now we start with the iteration I hope you guys know if you do any right shift upper of a given number by one means it's nothing but n by 2 that is what it happens so Write Sheet of this number by one portion will give you one zero one and if you write shift this one by position one zero one so this is nothing but 16 right so see this number is nothing but 2.0123 so eight nine ten 11th okay yeah okay this is not a number 16 very sorry I don't know I did write with 16 yeah it's 22. so right shifting on uh bit by one position is dividing a number by two so if you divide 22 by 2 it will give you 11 so we could see right shifting bit by one position is giving you one zero one that is something about 11. okay so that operation will do and each time we'll check the only significant bit not more significantly with LSP so how do you check the bit is one or zero you do and operation one and one so it is 1 0 1 and we do and with one means one zero one go to add operation with one so rest of them will be zeros so this will give you one and one will be one rest everything will be zero because this is zero so one and operation will be two only if both are two right otherwise it will be false so you know and with one each day so that logic is as usual what you know so now let's take the number one zero and we have this length max length and form one set to false that means we are not we have not yet found the one now initially we start with the number A Bit Zero at least a little bit zero okay so is found for making it to one zero into the length when will you take the zero into the count for length only if it is between once right if you have let's say one zero one if you found this one length will be set to 1. at this time when you have already found one only then length will be set to if it was just this then in this case length is zero right because there is no adjacent ones only one is present so if you but if you take this example one only difference so you will set plan to two again then again you move here this term length will be 2 right so you do Max of 0 comma if in case we have 0 1 okay and in such case zero one will be there the length will be set to 1. again this zero will form length is set to 2. but you don't have one more one in so if you don't find one more one you will not set max level so that's why length will remain zero one this is how we do so initially when uh if since if found is set to false will not take this zero into one so you do write one question that will give you one zero one okay so now this bit we have to focus if we do handle one this is one right since this is fun here let's store in a variable for Val if value will be equal to n and this one okay since while is equal to 1 you have to check what we need to check is found is sector false if e font is set to false that means this is the first one we are finding right we are not yet to encounter one adjacent to this before so that means we will initialize length equal to one and is found to be said to purana is found true why because a sound is set to false so if this phone is set to fall that means length equal to 1 and a flow should be set to two we have found the one this is what we need to do so this is next again you do right shift it will give you one zero one or two point here again you encountable but this time each one is set to true so here you have to check if a is found is set to true then what should be done we have one quarter one already so that means this is a adjacent one so this time we have to find the max length so max length will be equal to I'll just write max length equal to Max of length comma max length so 0 comma 1 the maximum of these two will be bought because length is initialized one right this one that will be one so max length will be set to 1. and after this also length will be again set to 1 why because that this one will be the land for the next adjacent one so this is these 12 and these two at the same so this is what sharing each other so that's why again set length equal to one volt okay so this is done and again we just found this set to true because this is the uh what sequence of adjacent ones for the next sequence we are finding it this one adjacent file is over next status in Period located so this is a new beginning of that so it is formula sector 2 again and length will be reset to 1 again so okay now again you do right shift it will give you one zero now you find zero at this time do we need to count length increment by one yes why we give else condition if Val is not equal to one again else if you have to check if file is not equal to and else if you have to check what if found else if found one if a Founder that means that's it so length will be set to 2 now next again you would write shift that will give you one so this time Val equal to one and each one is set to True Form one is set to True yes it is set to true so that means we have already found a one and this is this will be the adjacent one to that one so that means we have to find the Max and the max length will be equal to length comma max length so length is 2 max length is one so maximum it will be reset to two and after that again length will be set to 1 because this will be a new beginning of the next level let's say here after 1 we have 0 1 so again this will give you a length as 3. one two three and now is from perform one episode two again so this is the basic approach to solve the problem so ideally what is the logic is we find Value if the fine if you find bit equal to one then just check whether that bit has been already found or not that one is solid for another so found one is said to throw this you find the max length and reset the length equal to one and found equal to for the next sequence of once to find it Adam is what if you find the value if you find the bit equal to zero means just check whether form one is set to true the phone is set to true that means this is the length which we need to add that zero will pair it to the length so yeah so first what you need to do is as I said here we'll have a variable length equal to 0 and max length also set to zero okay so add one more Boolean value we need to have so why n greater than 0 so first we need to do let's say into value equal to n and one so that let's store that bit then n with the right shift by one position so this is number as you write a equal to a plus b how do you write it a plus equals to B right same way okay so now what happens you have to check if value equal to 1 if it is equal to 1 you have to check if found one it's already set to true that means this is a Time to find the max length so max Lin comma length and then again length will be reset to 1 and form one will be reset to so after this what we should we know else condition what if value is equal to 0 check if found one that means if you already found a bit one before to that means this should be the zero should be incremented to the should be contributed into the length a class written next yeah and foreign thank you | Binary Gap | push-dominoes | Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._
Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `1`'s is the absolute difference between their bit positions. For example, the two `1`'s in `"1001 "` have a distance of 3.
**Example 1:**
**Input:** n = 22
**Output:** 2
**Explanation:** 22 in binary is "10110 ".
The first adjacent pair of 1's is "10110 " with a distance of 2.
The second adjacent pair of 1's is "10110 " with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110 " is not a valid pair since there is a 1 separating the two 1's underlined.
**Example 2:**
**Input:** n = 8
**Output:** 0
**Explanation:** 8 in binary is "1000 ".
There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.
**Example 3:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 in binary is "101 ".
**Constraints:**
* `1 <= n <= 109` | null | Two Pointers,String,Dynamic Programming | Medium | null |
881 | What happened was guys welcome back to my channel and this video we are going to solve ODD to say paper solve tips knowledge statement here you are given in a rich people where people is divided of highest position and infinite number of votes where is vote can carry The maximum age limit is boot carrier set most people Addition time provide dism of the weight of the people is at most limit Thandi minimum number of votes to carry every given What is a giver in cherished switch problem and the elements in it In the judgment of MLA it is This position has a weight giver and a limit is given that you can carry a maximum amount of money only up to the limit. Okay, and another condition given is that you can carry only 2 persons on the board. Edit time is okay, so first. Example I am seeing that want to give NS2 please do weight gainer here * a limit give a 330 means that you weight gainer here * a limit give a 330 means that you can predicate on vote for maximum 3 minutes ok so you first which I am describing the incident in front do If there are two, then we can carry two people. If we heat both then the debater is free. We can carry, so what will happen here, my one vote will be used. Okay, let's see how to solve this problem. But what is mine, this is one everyone, there is a limit, okay, then we will solve this problem, what will we do, here is the giver of mine, we will shoot him, okay, if we will shorten it, then people, what after doing MS Word? That want to two are two and cream is ok here Will we take powder here Vyas person and scientist professor Will we take both of them together Ok if both are custom If there is limit quality list then we will take both of them together Otherwise what will we We will take every person, okay so here I have liked my favorite, it is free on Android side, both swear, it is my phone, but what is my limit here, my limit is street light, if there is meaning in limit, then I have done an accident. This is just what we will do, if we go with a great person, then how much will be my vote account, will it become one, the tight board supports here are very valid, between us, here is the voting system, so here you will see that both Kasam Light has been established, Kasam has done an accident, what will you do with the limit, now we will travel with gas, we will not travel with light, okay, then if we have to vote, then my account has become one, then we will increase it further from here, but you will come to two more in Both of them will swear that the right has become free, if it is within the limit, then the friend board will go to 12 and what is left of mine, we will do this world, we will take it in another board, then here it will be wasted, right click for free. The answer is, for the second example, we will see, then what will we do, we will hand it over, we will get free hands, free food and five, so here we have given suit in the limit, f5 given is the lightest, we will swear by selling it, if we accept one, then only we will take it. If we go here with investment, then Bol's card will be made one, then here this is waste, this is for these two, we will swear if there was intake, then what is the limit, if we go with Mahesh, then my voter card will be made two here. We are three, this is 3 If we go then how to solve it, let's see what we will do first shot, we will take all this dot Vaikunth that we have not done it, we will talk about softening int left, let's take 2004 and right, what will we do, gas like, mine is The size of the people will be how to the right side minus one, this is done, a scientist takes the vote, butter is applied, the total account is opposed to the huge, there will be a wild left place in the quest to the right, so here what we will do is first look at both the light and the waste portion. Which is within the limitation or not? Left plus torch light is tight, both swear, my retention request will be limited, so what will we do, will we take the next flight or will we go with the admission, then it is best if the light is here. That if it is possible that today I will have only the time for both of them, he will have an accident, you will leave the light one, we will carry only the waste, then there is waste, in any condition, we will continue as written, so what will we do, then right - - do, then right - - do, then right - - A &S &S &S that here. But we will make vote plus, it is okay that in every condition you will either go with the best or right alone, otherwise we will take both together, if we go with both together then we will do left plus, now after accounting for this, let us go, the cord on the left side is the lightest. If the one is tight then what will we do in the last? Return vote on AR Rahman's test score, turn on, submit tips at this time, thank you. | Boats to Save People | loud-and-rich | You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`.
Return _the minimum number of boats to carry every given person_.
**Example 1:**
**Input:** people = \[1,2\], limit = 3
**Output:** 1
**Explanation:** 1 boat (1, 2)
**Example 2:**
**Input:** people = \[3,2,2,1\], limit = 3
**Output:** 3
**Explanation:** 3 boats (1, 2), (2) and (3)
**Example 3:**
**Input:** people = \[3,5,3,4\], limit = 5
**Output:** 4
**Explanation:** 4 boats (3), (3), (4), (5)
**Constraints:**
* `1 <= people.length <= 5 * 104`
* `1 <= people[i] <= limit <= 3 * 104` | null | Array,Depth-First Search,Graph,Topological Sort | Medium | null |
1,796 | hey everybody this is larry just me going with q1 of the buy weekly contest 48 and i made a silly mistake which is why i'm showing you here uh that i also make mistakes sometimes i think i got too clever and tried to do everything in one line and then i don't know got a little bit quite lucky on the examples but um but the reason why i got um a wrong answer is because i got the second smallest numeric digit instead um even i knew it was largest i it was just me rushing it too much um but yeah um i watched it that there's that's basically the idea and so being careful uh usually i'm more careful or at least i my goal is to be more careful but today that failed a little bit um but yeah uh and i actually you know you can do this as a one-liner you know you can do this as a one-liner you know you can do this as a one-liner uh and i did i mean i kind of because of the wrong answers spread into two lines but you can actually you know just return this list um of one right um yeah and that would be your answer uh i don't think there's anything tricky about this one so definitely i don't know definitely let me know everything sorry like i have a whatever um but yeah um but you can do this by keeping track of 10 digits and yeah i mean the complexity it's you know given 10 digit it's always going to be uh constant or in terms of the digits so all this sorting and all these said it doesn't really matter uh in terms of space it's still going to be on order of 10 for number of digits uh i think the thing that i did was adding the negative one so that if that's fewer than um further than those number of digits uh i just returned one of these um but yeah but i one thing i did forget is that i was thinking about doing it whilst coding it but then i just forgot which is to reverse it to get the larger elements uh what a silly contest um because yeah uh and anyway now you could oh let me keep it up so that you can uh i guess take a look at it uh while you do whatever you need to do if you want to learn it this way but yeah let me know what you think and you could watch me celebrate to the contest next uh and you could even watch the struggle and the silly mistake so yeah oh second largest stitch what almost submitted it to be honest oh no i shall test it but why is that one oh man i'm dumb largest that i got a little bit lucky by accident that's what i get for trying to be cute though because i have done this without the one liner but uh thanks for watching uh hit the like button the subscriber and join me on discord let me know what you think about it today's problem and yeah uh stay good stay healthy stay well and good mental health i'll see you later bye | Second Largest Digit in a String | correct-a-binary-tree | Given an alphanumeric string `s`, return _the **second largest** numerical digit that appears in_ `s`_, or_ `-1` _if it does not exist_.
An **alphanumeric** string is a string consisting of lowercase English letters and digits.
**Example 1:**
**Input:** s = "dfa12321afd "
**Output:** 2
**Explanation:** The digits that appear in s are \[1, 2, 3\]. The second largest digit is 2.
**Example 2:**
**Input:** s = "abc1111 "
**Output:** -1
**Explanation:** The digits that appear in s are \[1\]. There is no second largest digit.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters and/or digits. | If you traverse the tree from right to left, the invalid node will point to a node that has already been visited. | Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | 114,766 |
123 | Hello viewers welcome to your sons media today with all the sixteen problems against killing challenge best time to buy and sell stock three please like this video fuel forget to subscribe our Channel mist update now you have every form is the rectangle element is the price Of The Given Stock Monday Came Designer Lever Come To Front Complete At Most Transactions In Maximum Profit The Giver Not Assume A Native Engage In Multiple Transactions At The Same Time The Latest Tumor Sales From Before You Begin In Five Simple And Different From Zee Cinema To Global Simple Has this platform and western question support also this priceless gift was no fear not only one transaction will find the minimum price in the maximum profit stop this approach will be very helpful in this question plus comeback congress did little but not talk about the scenario where they Can make at most transaction tattoo transactions look like this way remove will give the profit for transaction world rest will give the profile of the convention on that Sony approach will be divided into two and find the profit from all parts but for sequence next day will Have Been Possible Divisions In 14 Elements Who Will Win This Division As A Result The Time Complexity Of This Name Implementation Before In Square This Brings Into Dynamic Programming They Can Start An Intermediate Result In Same Time Generally Wicket ODI And To Date And Time In Programming But In this case viewers two years hence the name of the provided in the mid-day provided in the mid-day provided in the mid-day symptoms of dandruff provisioning sample built in the relief same size in Delhi will have a minimum verification holder minimum dark villagers with false belief is not be started from index 1.5 inches A condition started from index 1.5 inches A condition started from index 1.5 inches A condition values minimum values minimum values minimum A view developed with maths for the best All the values - Minimum which means nothing but values - Minimum which means nothing but values - Minimum which means nothing but profit in this is it means zero no which moves ahead and again and condition These values are also and again and condition These values are also and again and condition These values are also great and minimum Morning update The Amazing to 9 values in Do minimum, I will continue open 10th and 12th, I will finally get the second one, from here maximum profit value, your transaction will no longer need to find jobs in other transactions to the Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Point to Win the Profits from Both of Them Were Rebuilt Maximum Keep Networking and Boarding Cement 102 Left and Right Britain Sex Prosperity Step Well in Last Two Years Left Right Left and Right the Rise In the final of finding the right time complexity of a great quotes on flashlights and optimize one pass solution Tuesday which extra space but AB tracking and a composer transactions inflections the transaction wave section 2 of 2 minutes I have always will be amazed and subscribe 504 506 B 323 That Not Even Problem Active In Profit And Price - TV Cost That Is The New And Price - TV Cost That Is The New And Price - TV Cost That Is The New Profit Editor And Where t1 Profit Thursday Subscribe Milk West Bengal Stock Transaction To Take Into Account The Previous Song 2018 Live Update Of Profit Amazing To See This Pattern Holder Final Result Half Velvet Inch Price And Continue To Do So And They Are At The Invitation To Profit Ghritam Staff And Update Video On The Question A Different Approach Which You Might Find Interesting Delhi's Description Space Complexity Of Single Part Of Resurrection To Turn it off Thanks for watching the video Share and subscribe to this channel Happy Birthday on another portal | Best Time to Buy and Sell Stock III | best-time-to-buy-and-sell-stock-iii | You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete **at most two transactions**.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[3,3,5,0,0,3,1,4\]
**Output:** 6
**Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** In this case, no transaction is done, i.e. max profit = 0.
**Constraints:**
* `1 <= prices.length <= 105`
* `0 <= prices[i] <= 105` | null | Array,Dynamic Programming | Hard | 121,122,188,689 |
105 | hi everyone today we are going to solve the recalled question construct binary tree from pre-order and in another tree from pre-order and in another tree from pre-order and in another traversal so you are given two integer arrays pre-order and in order where arrays pre-order and in order where arrays pre-order and in order where perioda is a pre-order traversal of perioda is a pre-order traversal of perioda is a pre-order traversal of binary tree and in order is in order traversal of the same tree construct and return the binary tree so let's see the example so you are given like a 3 9 20 57 for pre-order and a 9 3 15 27 for in 57 for pre-order and a 9 3 15 27 for in 57 for pre-order and a 9 3 15 27 for in order and uh we use two arrays and just construct binary tree like this so output um should be like a 3 9 20 15 7 in this case okay so to solve this question first of all we have to know how we can uh troubles with like a pre-order in the in troubles with like a pre-order in the in troubles with like a pre-order in the in order so let's focus on pre-order so pre-order so let's focus on pre-order so pre-order so let's focus on pre-order so pre-order is very easy so when we pass a node we take the value immediately so first of all three so we start from three and I go down left and I take nine immediate three and then there's no value here so that's why I go back to three and then go right so we take a 20 and then go left uh take 15 and I go right seven yeah that's a pretty straightforward and in order is like a left Loot and the light so first of all we go left take a nine and then go back take three and then go down and there's a left note so first of all take a 15 and then go back 20 take 20 and then right side seven so something like that so that's why actually there is a hint in pre-order array so we take a value immediately so that means fast value should be a root node right because we start from root node so yeah look at the example one so three is a root node of this three um so that's why uh We sync three as a root node and then um so where is a three in the in order array so we take a we can find the three in the index one so three is a root node right so next hint is so now so we don't know what number is the left side what number is the right side but uh there is a hint so 3 is a root node so as I explained earlier so in order so take value like a left root and a light so that means um before 3 so which is only 9 in this case so 9 is definitely a left side of three right because uh first of all we take nine as a first value so that means 9 is a left side of three so when we create when we build the three of the left side um we only passing the 9 as a left side and then a list of nodes is located on the right side of three and I look at the these three so nine is only left side and the list of three nodes are right side of three right so yeah so and then um uh create a node nine and uh there's no value here so that's why we finished the finish builds the left side and uh so nine is a blue left side and then um next so we finish the um until nine and the next we include the array we find the 20 and so 20 is a light side and the way is a 20 in order array so here index three zero one two three so three um so in green area so 20 is a root node because uh in pre-order array we've because uh in pre-order array we've because uh in pre-order array we've find that 20 as a third value so that means um before 20 so which is only 15. so 15 is a definitely left side of 20. because uh in order so we each of us like a left loot right so um 20 is a root node of green area and that means before 20 so 15 is a left side of 20 definitely so when we call the um like a build function again for left side we pass only 15. so that's why our next value of pre-order is 15 and then pre-order is 15 and then pre-order is 15 and then um 7 is a right side of 20. so that's why uh seven show up the last value and I look at the um example one so 20 we find the 20 and then uh look at the left side only 15 so yeah 15 is the left side of 20 and the 7 is a right side of 20. so we can build the three properly yeah so that is a basic idea to solve this question so with that being said let's get into the code okay so let's write a code first of all um create a DQ so pre-order equal um create a DQ so pre-order equal um create a DQ so pre-order equal Corrections dot thank you and a pretty folder so let me explain uh why we use datu later and then return okay let's say build and passing the pre-order and the in order passing the pre-order and the in order passing the pre-order and the in order and then let's create a inner function So Def build and the passings are pretty cool there in order and first of all if in order exists then first of all take a index in order dot index and a pretty older dot pop left so the reason why we use JQ is that we take a value from uh top so that's why we want to use poplift so yeah we can use a normal array um but it might be time consuming if we take the value from the top so that's why we use datu so these operations should be uh o1 and take an index and then um first of all create a root node three node in the in order and index so then um left equal color build function again build and uh pre-order build and uh pre-order build and uh pre-order and in order and this time so we create a left side for this uh Builder code so in that case I'm passing the so this index number should be a root uh root value index so that means um as I explained earlier before root index all numbers should be left side so that's why passing the index here uh so that we can pass the um all numbers before root value as our left side and loot dot like equal build and uh pre-order and uh pre-order and uh pre-order dot in order and uh this time we have to pass the right side so index plus one in the column yeah so I hope we can pass the right side properly and then after that our little root yeah actually that's it so let me submit it yeah looks good and uh it's not bad so solution because uh we beat 72 percent but on time complexity of this solution should be uh order of n Square in the worst case uh because we every time we call the build function and the iterates through the in order array here so I think uh worst case should be a order of n Square so yeah so let me um improve our solution okay so to improve time complexity so first of all um the problem of on Square solution is that we iterate through all numbers in order array where we call the build function recovery So to avoid that situation um I create a in order mapping so here is each value like 9 3 15 27. and the value is uh index Mega 9 is in Excel three is index one 15 is index two something like that and uh this time um we use two pointers like a start pointer and the end pointer initialized with zero and initialized with last index and uh to create each node so we use a pre-order pre-order pre-order array um and then take the value from the left to right so first of all we take the three to create a root node and at the time check the value 3 location in order array so check the mapping so three is located at index one so look at the index one so we find the three successfully so let's call this index number is like a middle index um and then um actually we apply the same idea of a previous solution so before middle index so this area should be a left side of middle value and then uh this side is our right side of middle value and so first of all we try to create a left side so in that case of um we passed a same start pointer and uh so for in the pointer end the pointer is updated with um middle -1 so in this case in the um middle -1 so in this case in the um middle -1 so in this case in the Excel and then um call build function again and if start pointer is greater than end pointer in that case we don't do anything we just return on so in this case they are same so we continue to create a node 9. so in that case we pop the nine from uh preo dot array and at the time we take the location uh in order array so check the mapping so nine is a index zero so look at the index zero so yeah we find the nine successfully in this case uh middle now middle index should be um nine so in the case uh call a video function again with same start point and uh endpoint should be middle minus one here then now start pointer is greater than end pointer so in that case we don't do anything just return on yeah it's obviously there is no data here so yeah looks good and then try to create a right side so now um uh nine left of nine is uh no so try to create this side like this so also uh there is no node here so in that case um so we so end point I go back to here and then when we try to build the right side so we pass the same end pointer and the start pointer should be middle point plus one in this case like this so in that case um start point is greater than end pointer so we don't do anything so yeah it's obvious um so left side of three is only 9 so we don't have like a left uh left value of 9 or write the value of nine yeah it's obvious so that's why we don't do anything and then we finish the uh this side and then uh we try to build our left side of three so in the case uh so yeah a little bit messy so let me remove this so start number is index 0 and the end pointer is index uh so last index they don't want to see oh and so when we try to um this is the right side of three uh as I explained earlier so we passed the same end pointer and a full start pointer so start pointer is updated with middle plus one so when middle pointer is pointing three so start point that should be middle plus one here and then check the start and the end so start is still less than and in the case we continue to create the new node so next node should be 20 right yeah right so pop the 20 from pre-order array and at pop the 20 from pre-order array and at pop the 20 from pre-order array and at the time we take the location in order a so 20 is at index 3. so look at the index 3 here so we find a successfully we find the 20 successfully so next middle index should be here and then um after that we do the same thing try to build the left side of 20. in that case uh past the same start pointer and for end pointer and the pointer is updated I update it with middle -1 in this case middle -1 in this case middle -1 in this case here and then check the start pointer and the end pointer so they are same in the case we continue to create the new node so in this case 50 so yeah um up 15 and I look at the index uh in order mapping and 15 is uh index 2 in order array so look at the index 2 so we find the 15 so next middle point that should be 15. and then after the same thing and after that we update the end pointer with second middle minus one and then start point is now a greater than in the pointers or we don't do anything and therefore right side of 15 so in the case and the pointer is here and the start Point dot is here uh here so start pointer is great as an end pointer so we don't do anything and yeah so actually we use a sensing on the right side and then um when we successfully create a whole node and the right place and the same tree of exact example one yeah that is a basic idea to solve this question and I think this solution should be a order of in linear time yeah so with that being said let's get into the code okay so let's write a code first of all um initialize mapping with hashmap and create a in order mapping so lensions of in order and the mapping and the key should be value so in order um bar not pi and equal I yeah um that's easy and then return view the function and passing the start point initialized with zero and the end point that should be a length of the employee or the minus one so you can pass um any other is um because uh pre-order on the New Order um because uh pre-order on the New Order um because uh pre-order on the New Order is the same length So Def and build function and start and end and then first of all if start is greater than n in the case uh just a little no and then after that create a node solute node is like a tree node and uh pop the value from pre-order pre-order pop the value from pre-order pre-order pop the value from pre-order pre-order ah yeah sorry uh I forgot to like create a dative so pretty all the equal um Corrections Dot dative and a pretty old and then we can use the pop left after that um find the middle index with using mapping so loot bar and then after that try to view the left side and the right side so little to the left equal build so when we build the left side as I explained earlier same start point and the end point that should be middle minus one in the four right side for the top right equal build and in the case start point should be middle plus one and the same end pointer after that just return root node yeah that's it so let me submitted yeah looks good and I believe sent um time complexity I think um previous Solutions should be like a 70 something and now Pizza 93 because yeah as I explained earlier so first solution should be o n square but at this time I think a on solution because we use a mapping so this for Loop should be our own time complexity so that's why uh in build function uh we can get the middle index with one time complexity this is a step-by-step algorithm of this is a step-by-step algorithm of this is a step-by-step algorithm of construct binary tree from projector and in order to reversal step one create uh thank you with pre-order Step 2 color uh thank you with pre-order Step 2 color uh thank you with pre-order Step 2 color build function step one if in order exists find the Bluetooth index with in order and pre-order and pre-order and pre-order Step 2 create a root node step 3 for left side of root node core build function with pre-order and in order function with pre-order and in order function with pre-order and in order column loot index step 4 for right side of root node called build function with pre-order and called build function with pre-order and called build function with pre-order and in order root plus root index Plus 1. yeah so that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question | Construct Binary Tree from Preorder and Inorder Traversal | construct-binary-tree-from-preorder-and-inorder-traversal | Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** preorder = \[-1\], inorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= preorder.length <= 3000`
* `inorder.length == preorder.length`
* `-3000 <= preorder[i], inorder[i] <= 3000`
* `preorder` and `inorder` consist of **unique** values.
* Each value of `inorder` also appears in `preorder`.
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree. | null | Array,Hash Table,Divide and Conquer,Tree,Binary Tree | Medium | 106 |
21 | hey guys welcome and welcome back to my channel so today we are going to discuss another problem is merge to sorted link list so in the question we will be given two sorted link list so if you see this is the first sorted link list it's sorted in ascending order and the second link is this is which is also sorted in ascending order so uh in the function we will be given a head one which will be the head of this first linked list and hey two which will be the head of the second link list so both linked list head will be given and we need to saw we need to merge these two linked lists merging these two linked lists means that we need to make a final link list which is also sorted so if you merge these english means uh if we make a final link list of these two link list which is also sorted so it would be something like this 2 3 5 6 8 9 and 12 so see this link list will be the output and we need to return the head of this length list this head right this head so uh this is uh this we need to do basically and also we should not use any extra space right so we should avoid that now let's see how we can approach this now if you see right we need to have one head because head of this final linked list we need to know right we need to return that so there should be one variable which will uh store this head let's say it is final head variable so final head variable will contain the address of the first node of the final english which is two here right so this variable will store this two now we need to the second thing is we need to add these next nodes right like this right so after 2 we need to add to its next 3 next of 3 should be 5 so this way we need to add in sorted order right in ascending order so this should be this is pretty much what we need to do so for doing this one thing which is clear is that we need to have a final head variable let's name it as fh because which will store the final head of the final language right also we need to have a tail vary tail variable let's name it as final tail why tail variable you will get to understand now let's see how we will uh iterate through this uh these linked list why we are using this why we are maintaining this tail variable you will get to understand right so we have head one which is pointing to this two head two which is pointing the head of the second laser which is three so what we will do is we have this final head variable which is initially null let's take it as well we have final tale let us take this also as none so if you have watched the video of merge two sorted errors then you must have got what we are doing but if you don't know you if you want to uh watch that you can watch that video first the link will be in the description so uh what we are going to do is we will be traversing now like we will be comparing h1 value with h2 value whatever value is at h1 which is 2 here and value at h2 which is 3 now 2 is less than 3 means h1 value is less than h2 value so because we are we need to merge in sorted ascending order right sorted order so 2 will come first so in our final linked list i am writing here final link list this is our final linked list so in that 2 will be in the starting now if you see when we got 2 right our final head value was null final tail value was in it means when both of these values are null means that this 2 is our first node in the linked list in the sorted in the final linked list right this 2 is the first node why first node because both these values are null so what we'll do is since both are both of these are null right we will fi final head will be two and final tail will be two so both these variables final head will be pointing here and final tail will be pointing here as of now because only we have two in our this linked list now what we will do is since we have taken two so we will move head one ahead head one will move to head ones next which is five now again what we will do is the same thing we will compare five h1 value with h2 value which is three now see h2 value is smaller right so this three where we will add it now you will understand the use of final tail we cannot change this final head right final head will contain two only y two because this we will be returning because this is our head of the final linkage but now this three value we need to add it somewhere right so as to make the whole link list so we will be adding this three in final table because this final tail variable is pointing every time to the last node in our final linked list whatever our final link list is right this ft will point to the end node so that the new node whatever comes we can add it to its next so this three will be added it will be added to ft next so here ft is to choose next we will add three and don't forget to update your final tail now so your final tail is now three so this will be three all right and now since you have taken this three so we will move h2 it like this so i hope you understood what we are doing why we have taken this final tail because we need to add it add the new nodes to the linked list right to final increase so we need to have a final tape because we cannot change this final head it will be two only which we will return at the end right now let's traverse again so uh head one value is five now head to value is six now five is less than six so five will be added this five will be added to final tail ft next ft is next so 5 will be added here and this will be update to 5 now and since 5 we have taken so h1 will go ahead so you have seen we are making a final link list our final link list is being created right now again a head one value is eight head to value is six now head to value is smaller six will be added ft is next here but now ft will update to 6 because this is now ft will be pointing here right then what we will do is we will since h2 value was smaller we will shift h2 here okay so now let's again hydrate now h1 value is 8 h2 value is 9 8 is less than 9 8 will be added here ft will be update ft will update to it because 8 is the end of the final link list now and now we will also update h1 will go ahead here so you're seeing we are making this list in sorted order now what we'll do is uh h1 value is 12 h2 value is 9 h2 is values less nine is less so nine will be added to ft next here ft will be updated now it will become nine all right and we will move h2 so h2 becomes h2 comes here h2 becomes 9 right so then now what we will do is since 1 h2 with h2 has become null so then we will stop the loop and after that what we will check uh what see we have one node remaining in this first linked list right which is 12 so we will check if head 2 is if head 1 is not null it's 12 so we will add it to ft is next so 12 will be added at the end in case if it would have been that h 1 became becomes null but h 2 is not null then we will add h 2 and vn so you see this is a final link list which is made and our this head value is stored here so we can simply just return it return fh which is final head so this is the way which we are merging to linguist it's very simple let's discuss what we did we have maintained two variables final head initialize to null final tail initialize to null right then we are traversing the both the linked list and if fh is equal to null and ft is also null means both are null then it means that the node if h1 is value is less than h2 right if h1 value is h the less than h2 means this h1 is the first node in the linked list because both these values are null initial null right now so fh will be equal to h1 and ft will be equal to h1 but if h2 is less than fh will be equal to h2 and ft is equal to h2 right and if these are not none else it means that we are now adding other nodes in the linkage in the final link list so accordingly we will write that code so this is basically the approach let's see the code once code is very simple we have this function merge to link list it is it will be returning uh the head of the link list so the return type is note star we have head one we have head to if you are not clear with uh with what does this note star means i will highly recommend to watch the pointer video i'll share the link in the description so we have taken two variables from final head final tail initialize to null we will be traversing until any of one becomes uh like any of these one becomes not like head one either head one becomes null or head two becomes that so if you see over here also we did the same thing now so if these values are null means we are add we are getting our first node in the final linked list so if head one head two values less head two will be the final head final date and move head two to head twos next else it will be head one but if these values final head and final tail are not null means we are not that we are now adding the second third and so on link uh nodes in the linked list so we will run this if head one value is less than head to we will in the final tail next we will add head one final tail will update we will be we were also updating the final header final tail was updating every time so final tale will be update and we will move the head one to head one's next else we'll do same thing with head too so after this while loop once this while loop is done we discussed that now that uh what happened here was that h1 was not null h2 became null so we will come out of this while loop h2 becomes this will come out of this while loop but since h1 is not null right so we will check that if head one is not null in the final says next just add head one so we added this twelve after uh at uh final tales next right otherwise if head to there might be a case if head 2 is not null then you can do the same thing and at the last you can return final hit so this was the code and the approach it's very simple just dryer and if you are unable to understand what we did uh just try it in with an example you will understand it easily and if you like the video please like it share with your friends subscribe to the channel and i will meet in the next video bye | Merge Two Sorted Lists | merge-two-sorted-lists | You are given the heads of two sorted linked lists `list1` and `list2`.
Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists.
Return _the head of the merged linked list_.
**Example 1:**
**Input:** list1 = \[1,2,4\], list2 = \[1,3,4\]
**Output:** \[1,1,2,3,4,4\]
**Example 2:**
**Input:** list1 = \[\], list2 = \[\]
**Output:** \[\]
**Example 3:**
**Input:** list1 = \[\], list2 = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in both lists is in the range `[0, 50]`.
* `-100 <= Node.val <= 100`
* Both `list1` and `list2` are sorted in **non-decreasing** order. | null | Linked List,Recursion | Easy | 23,88,148,244,1774,2071 |
347 | hello everyone welcome back to my channel this is jess so today we'll be looking at a problem called top k frequent elements so first let's take a look at the question statement you're given an integer array noms and an integer k and you're asked to return the k most frequent elements you may return the answer in any order so if we look at example one if you're given this nums list or array with 1 2 3 and k equal to 2 then your output should be a list of 1 and then 2 because 1 has an occurrence of three in this list and then two has an occurrence of two in this list which make them the top two frequent elements in this given list nums and for example two if you're given a list only containing one element which is one and k is also equal to one then your output list should be just one and just by reading the question statement we can tell that the solution logic should be pretty simple you're basically just getting the occurrence of each unique element in the list and then find the top k frequent elements so we could pretty much just divide this question into two steps first step would be to compute the frequency list of all the elements in the given nums array and then once you have computed this frequency list then you might need to sort the frequency list by the frequencies and then return the first k elements based on its frequency so for step one computing the frequency list what we could do is to build a hashmap or a dictionary to store the key value pair of each element and its corresponding frequency or occurrence in the list to do so what we need to do is to loop through every single elements in the list and then if you see an element that is not in the frequency list or the hashmap then you add it into the map and then set its frequency to 1. if you have seen an element that's already in the hashmap then you just simply add one to its frequency and once you have this hash map you could just sort each key value pair by its value which is the frequency of each element in the list and once it's sorted you just get the first k key value pairs and then store the key which is the element itself into a separate list and then return that list pretty simple right but the tricky part about this problem is actually the runtime and the space complexity analysis and whether or not we could optimize its runtime so let's talk about the runtime for the implementation that we just talked about for step one creating the hashmap since we're looping through every single element in the list that's going to be a big off and run time and then creating this hash map meaning that adding new key value pairs to the hashmap or multiplying the existing key value pairs value which is the frequency that's just going to be constant time run time big off one so in total for step one building the hashmap it's going to be big off and runtime and then we said we're going to sort this hash map by its frequencies by its value and for sorting if we're using the default sort method in python then it's going to be a big o of n log n runtime so far our overall run time is going to be big o of n log n and then once it's sorted the last step is to get the first k elements or the first k key value pairs from the hashmap and then stored the key which is the element value into a separate list and that is going to be a bigger off n runtime so in total the runtime for the implementation that we talked about is going to be big o of n log n which is all right but we could definitely do better than that so an optimized solution to this question well we still have to find or build the frequency hash map for all the elements so step one stays the same and our runtime for step one is still going to be big o of n but for step two the previous solution that we talked about we were sorting every single element in the hashmap but do we actually need those the answer is not really because for the final result we're only looking at the k most frequent elements so here heap comes into play we could definitely replace step two with a heap and the heap only going to be having a size of k so how do we keep the heap size at k you might wonder since we definitely have to pass in all the elements with its frequency into the heap to get the k the overall k most frequent elements well to keep the heap at size k what we're going to do is to first we're going to add those frequency elements pair into the heap and then once we have added k of those pairs the next pair that we're going to add we're also going to be popping the least frequent element frequency pair from the heat so this way we can always keep the heap at size k and once we're done with adding all the frequency element pair into the heap should contain the k most frequent elements with this frequencies so now let's actually talk about the runtime for building the heap the first k element that we're adding into the heap for each element the runtime is just going to be big o of log k then for the k plus 1 element that we're adding into the heap we're also popping the least frequent element from the heap and the popping is just going to be big o of log k as well and we're going to do this add new element and then pop the least frequent element step for n minus k times so in total for building the heap our runtime is going to be big o of log k times that's for the first k elements plus big o of y k times n minus k times so in total it's going to be big o of n log k and then once we have this size k p computed we could just add those elements into a list and then return that list and the runtime for that is going to be big o of k so in total this solution is going to be big o of n log k runtime slightly better than our big o of n log and runtime so now let's start coding this out first thing first we're going to check for null for the inputs if not noms then we just simply return an empty list and then we also saw in the second example if there are k elements in the given input then we could just simply return the nums list so if the length of nums is equal to k then we just simply return knobs and then we're going to do something very magical at least i think it's pretty magical there's this function in python 3 called counter and it helps you to create a frequency hash map so we're just going to call our frequency hashmap as count and it's going to be counter and then pass in knobs so count is our frequency hash map and then for the next step there is also a pretty awesome function that comes with python 3's collection heap queue is called n largest so for n largest it basically helps you return n largest element from an iterable so in our case it's going to be a hashmap and it takes in three parameters the first one is a number specifying how many elements you want to return and in our case we're returning k elements and then for the second parameter it is a iterable meaning that the elements you want to iterate through so in our case it's going to be the keys and then the last one it is an optional parameter and it's called key but this key is basically what you're comparing those elements with so in our case we're comparing their frequencies which is the value in this key value pair from the hashmap so our key is just going to be count.get it is a function count.get it is a function count.get it is a function and let's run it submit so like i said the runtime for this solution is big o of n log k and for the space complexity we're storing every single element with this frequency in our hash map that's going to be a space complexity of big o of n and we're also storing or building this size of k heap and in total space complexity for this function is going to be big o of n plus k alright so that's it for today's question i hope you enjoyed this video and the solution feel free to post any comments questions in the comment section and i'll see you in my next video bye | Top K Frequent Elements | top-k-frequent-elements | Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\], k = 2
**Output:** \[1,2\]
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `k` is in the range `[1, the number of unique elements in the array]`.
* It is **guaranteed** that the answer is **unique**.
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size. | null | Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect | Medium | 192,215,451,659,692,1014,1919 |
983 | hey guys welcome back to another video and today we're going to be solving the lead code question minimum cost for tickets all right so in this question we're so in a country popular for train travel you have planned some train traveling one year in advance so the days of the year that you will travel is given is in an area called days and each day is an integer from one all the way to 365. train tickets are sold in three different ways so you can buy a one day pass a seven day pass or a three a 30 day pass and so you have an area called cost so for example like this one and whatever it is at the zeroth index represents the cost for the first day a one day trial pass and whatever is at the first index is going to be the cost of a seven day pass and whatever is in the ending or at the second index is going to have a cost for the 30-day pass the 30-day pass the 30-day pass all right so we're given these two areas days and costs and the passes allow that many days of consecutive travel so for example if we get a seven-day so for example if we get a seven-day so for example if we get a seven-day pass on day two so what does that mean that means we can travel on day two day three day four day five day six day seven and day eight so that's a total of eight days including the day that you bought the pass on all right so let's just take a look at this example that they gave us every year so real quickly what they did is they went to on day one they bought a one day pass then so that lasts for one day which is day one then again you had to buy a pass on day number four right so for that they bought a seven day pass which is going to last all the way until uh this over here day eight and after that they bought a one day pass for day 20. so on day 20 they bought a one day pass and that's actually the cheapest option available for them so in this case it was eleven dollars for them all right so let's take a quick look about how we can solve this problem all right so the most intuitive thing at least the first thing that i came up with so we're going to try out all of the possibilities there are so we could buy one day pass seven day pass 30 day pass we're going to try all of these possibilities and at the end of it we're going to end up choosing whatever has the minimum cost so let's just see how that looks like real quickly all right so let's say we're given these this area for days and this area for the cost and what are the options that we have on day one well we have one of three options we can either buy a one day pass so i'll represent all one day passes in the color green or you could buy a 30 day a seven day pass so i'll use the color blue for that or you could buy a 30 day pass and i'll use the color red for that so these are the three options that we have so let's say we bought a one day pass on day one and that's only going to be valid for that date so if we bought a one day pass we would have validity for just one day so if you bought a seven day pass it's gonna last up uh last us for seven days so it's gonna last us for day one day two day three day four day five day six and finally day seven so it's gonna last up for a total of seven days so the next time that we need to buy a ticket so if we bought a seven day pass the next time we would have to buy a ticket would be over a year on day eight and similarly if we bought a one day pass the next time we would buy a ticket would be on day four okay and finally we have our 30 day pass which is well we only have 20 days so it's just gonna last forever okay so we have so these are the four options that three options that we have and what are we so how does this matter so this is just one iteration so what we're going to do is each time we're going to recursively call some sort of function and we're gonna try to get the minimum of these three probabilities so again what we're gonna do is so first you buy the pass at that date so one day seven day and thirty day pass and for the next day we do the same thing what i mean by that so on day one considering we bought a one day pass that leads us to day four so we have to buy a pass on day four considering we bought a one day pass on day one so if we bought a one day pass on day four we could either have validity just for day four or we could buy a seven day pass right so if you got a seven day pass we'd have validity for day four day five day six day seven day eight uh day nine and day ten but we only have up to day eight so we're valid until day eight and finally we can buy a 30 day pass which is going to last up lasts until everything right so we get all of that so that's for day four let's assume on day one we actually ended up buying a seven day pass so in that case we're going to be we're going to end up at day eight so at day eight we could do several things we could either buy i know it's gonna overlap but just try to understand so let's say we could buy a one day pass on day eight or we could buy a seven day pass but if you look at this if you buy a seven day pass it's still only going to last for that one day or finally our last option is by 30 day pass which lasts for this day and the last day so that's our other option and now we're going to keep continuing this for each and every possibility what i mean by that is now we're going to go to sixth day considering we bought a one day pass or we would go to the 20th day and what we're going to end up choosing is going to be whatever has the most the smallest value so whatever has the minimum value i know this might be a little bit confusing because i myself wasn't too sure about how i could draw this out and explain so i'm pretty sure that as we code along it should be easier to understand right so let's get started with our code over here and before we do that i just want to kind of point out something is if you look at our drawing over here per se you can tell that so if we kept going on and on there will be a point where we're making the same calls over and over again right so there might be a point where we reach the number eight again and we're gonna do the same call or same we're gonna call the same function another time and that's just an absolute waste of time in order to solve that problem we can be using dynamic programming and all that's going to be doing it's going to be storing that value so let's say calculator value it's going to store that in some sort of data structure in this case we're going to be using a list so it's going to be storing that value and instead of calling that function again we can just refer to that value and one more thing i want to note is that i'm not going to be using any decorators like the lru we'll be doing everything from scratch okay so we're going to start off by defining our dynamic programming area so let's call it dp and it's going to be filled with zeros and what is its length going to be well its length is going to be the same length as that of the number of days we have and one more small thing is that over here we just have a few days but imagine for a total of 365 days we might have a lot more days so doing this is actually going to save up a lot of time okay so it's going to be the length of day so now we have an area filled with zeros which has the same length as the number of days we have okay and over here i'm just going to do self.days equals to days and then self.days equals to days and then self.days equals to days and then self dot costs is equal to cost and the reason we're doing that is that we can refer it to uh to it from other functions so over here we're going to end up making a helper function so let me just return it and then we can talk about what the uh helper function is going to be so here i'm going to return i'll call the function self.min cost and we're going to give it self.min cost and we're going to give it self.min cost and we're going to give it the value of sarah okay so what is this function actually going to be so let's call this function over here so define min cost what is it going to take it's going to take self and it's going to take a value over here so what is this value actually referring to that value is going to be referring to the current index we are on start off at whatever is at the zeroth index right so that's going to be the first thing we start off at so that's why we actually gave it the zero with index since that's what we're starting at okay so since we have that we're going to put index over here so index that's going to be the parameters taken inside of min cost function so before we get to the main part we need to uh consider a few base cases that we have so over here one of the base cases is going to be if our index is going to be equal to the length of the number of days we have so self.days self.days self.days that means that we've reached the ending and we can just end up returning zero okay so that's one of our base cases and the other base cases we're going to keep adding our values to our dp array right and we want to check if that value is already in our array and if it is we're just going to return that so how can we do that so we're just going to refer to our array and we're going to go to wherever index we're at so index and if that is not equal to zero so in the beginning they're all girls so if it's not zero that means that we've changed the value and in that case we're just going to return that value so we're going to return self.dp index we're going to return self.dp index we're going to return self.dp index instead of performing all the functions again okay so now we get to the recursion part of this so over here we're going to be adding that value to our dynamic programming area so self.dp dynamic programming area so self.dp dynamic programming area so self.dp index and what is this going to be equal to so like i said earlier we're going to find the minimum of all three possibilities so we're going to take the minimum so over here we're going to try for a one day pass then a seven day pass and then a 30 day pass right and so first we're going to buy that pass and after that we're going to call this function again on the next time we need to buy it what do i mean by that so real quickly so if i bought a one day pass on day one that means when is the next time i need about by the pass well it's going to be at day four so now we need to create some sort of function which is going to let us know when the next day is so one more example real quickly so let's say we bought a seven day pass on day number one so when do we know when to stop to do that we're going to create a function so in this case if we bought a seven day pass on day one that means our pass is valid until the seventh day over here after which we need to buy a pass another time okay so let's create that function and i'm just going to create this function over here and i'll call this function next day uh just for a short form i'll just call it nd and what is this going to take it's going to take the same thing it's going to take the index we currently are on and it's also going to take the duration so the duration is going to be how long the past lasts for all right so we're going to start off by storing this index value that we have inside of a temporary variable so i'll just call temp equals to index and we're going to be ending up returning this temporary variable and one more thing we need to find is what is the last possible day given this duration okay so i'll call this the last day if it doesn't make sense it will really soon so what we're going to do is we're going to go to self.days area to go to self.days area to go to self.days area we're going to go to that index and we're going to get whatever current day we are on day 1 day 7 day 100 whatever it is and now how do we know what the last possible day is so if we were on day one the last possible day is going to be day one plus whatever our duration is so we're going to add our duration so self.days self.days self.days plus duration and then one more thing we're going to do is we're going to subtract one from it and the reason that we're doing that is because let's say we were at day one and at day one we bought a seven day one day two three four five six and seven it lasts until day seven and on day eight we need to buy a new pass right but uh what happens when we do this we're just gonna do one plus seven so this is directly giving us a value of eight so this is basically telling us that our pass is valid until and including the eighth day which is not true so in order to consider for that we're gonna subtract by one and yeah so now we have our last day variable so now we're going to go inside of a while loop and this while it's going to have a few conditions so first we're going to check if the index is less than the length of self.days so we're going the length of self.days so we're going the length of self.days so we're going to be keep going we're going to keep increasing our index value until we reach some sort of ending or if we reach the last possible date okay so that's one and the other condition like i said earlier is we're going to check if we pass our duration so to do that all we're doing is we're going to do self.days going to do self.days going to do self.days we're going to call our index okay sorry we're going to be calling our temporary value which i defined over here sorry about that so this is also going to be temp okay and after we do this we're going to check if this new value is less than or equal to the last day which we defined so until either of these conditions are not met we're going to keep increasing this temporary variable of hours by one okay and when we get out of this while loop we're going to end up returning this temporary variable so now by calling this function what we got is the next day when our ticket duration doesn't last anymore so this is what our nd function gives us so what we're going to do is we're going to call this function in our min cost function over here okay so like i said earlier let's first make a call considering that we bought a one day pass so over here we're first going to add the price so i call this self dot cost and the price for a one day pass is that the zero with index as said in the question and we're going to add this with whatever is at the next day and we're going to recursively call this min cost function okay so in simple words we're first going to call the min cost function and what index are we going to call it on well to do that we've created our nd function so self.nd and inside of nd we give it so self.nd and inside of nd we give it so self.nd and inside of nd we give it the current index we are on so that's going to just be index and then we have to give it a duration in this case the duration as well it's one day so that's one of the conditions and this is going to give us the next day and again after we get there we're going to call this min cost function on that right so we're recursively calling it okay so that's one of it now we need to call it for considering that we bought a seven day pass so all i'm gonna do is i'm just gonna copy what we have a bar copy that and i'm gonna paste it over here so instead of going to the zero with index we're going to go to the first index and self.min cost first index and self.min cost first index and self.min cost is going to be the same thing but over here we're going to be calling the set we're going to give it a value of 7 because the duration as well it's 7. and finally let's uh copy and paste it one more time and over here we're going to change it uh so instead of calling the zeroth index for cost we're going to call the ending so the second index and so this is for the 30 day pass by the way and finally the duration for a 30-day and finally the duration for a 30-day and finally the duration for a 30-day pass is well 30 days so we change that value and we're going to end up choosing whatever is in the minimum of this and each time we're adding this value to our dp array so sometimes we might be we might have to make that call again but we actually won't make it since that value is already stored in our dynamic programming area so in that case we're just going to refer to it and just return that value instead of ending up and doing this calculations all the way again and finally at the end of this function we're just going to return self.dp and whatever current index we self.dp and whatever current index we self.dp and whatever current index we are on and that should be it so in the beginning we call this function over here and let's submit this and see what happens hopefully it works so submit okay and as you can see our submission did get accepted and finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if this video was helpful thank you | 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 |
109 | hey everybody this is Larry this is day 11th of the deco day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this Farm yay one that doesn't have the solution in the memory all right let's take a look is it seems like it's gonna link this from 109 convert sorted list to binary search tree hit the like button hit the Subscribe button join me on Discord and today I would do a bonus um uh premium problem so definitely if you have premium or even if you don't uh check that out uh and you know see a new problem or whatever or just do one with Larry uh yeah all right so let's see so it's a sorted list sorted linked list even and we have a binary search tree hmm what does that mean height balanced binary search tree um is that weird maybe I don't know that I understand this exactly uh the specifications because um okay so I guess the depth of the sub trees are but it's a little bit awkward like because you can imagine this no I guess that's fine I guess five knows this is roughly right okay um yeah I think it's just recursively getting the medium node and then you know bending it if you could uh but basically it's just um what you might call it uh divide and conquer I think um and then taking the medium node and then just go left or right um You have to be a little bit careful just to make sure that you don't go a little bit out of whack um on handling you know dividing by odd numbers or something I wonder if that would ever come up but I guess we'll see we're just doing naively and then we'll see um but yeah and of course you could uh Define a get middle node Thing by just um using the turtle and the uh turtles and the hair album which means having two notes uh two cap pointers and going one that's tricep to speed and then one going uh singular speed and then you would get the median uh medium node in that case so let's just say get medium for uh ahead right so then you have current is uh fast as you go ahead tip the tail as you go to her head and then while fast is not none as fast as you go to fast time next fast as you go to fast down next assuming fast is not none right and then slowly go slow as you go to slow down next and then we return slow right what do you say tail that's weird so that's get middle medium Middle English is hard and then yeah and then this is just regular recursion right and then we just um maybe have a two PST of uh the node right and then we do middle node is you go to uh get middle of the node um I think I want to change this up a little bit um the reason being that um we'll be telling the node which is useful but we also want we actually want to get the node containing the next node to be um to be the middle so I think that's a little bit easier um so maybe we'd say pre-head as you go um so maybe we'd say pre-head as you go um so maybe we'd say pre-head as you go to list node of negative one head and then pre-head right then pre-head right then pre-head right uh something like this I suppose right um and then now we can be touched slow but now we want to slow that next will be the middle element is what I want to do because then uh because then now we can do something like middle dot next as you go to none and then you know divide the thing right um so we won't we will do that but not yet so basically now we want uh so now the middle uh yeah so now um so now the current node oh this is a list note that's why I get confused so kind of note is you go three note of no uh middle Dot next dot value somewhere like this um we have to do some checking to make sure that middle dot next is not none it shouldn't be none though because it cannot be maybe but let's just put in a third here and then we can maybe fix it later if this assertion is wrong right um and then basically middle dot next uh let's just say also um yeah how do I want to invite it yeah maybe that's fine I think this is already good enough right and then current that left is you go to uh oh now we have to do middle dot next is equal to none so that we Chop It Off Middle down next is equal to BST um maybe I missed a parameter oh no notice the leftmost note so that should actually be good so uh node and then current that right is you go to PST metal dot next because you want to know that's next to I mean I have to fix some stuff but that would be the idea right um yeah and then also if node is none then just return none um yeah I don't know I didn't do it but yeah let's call this middle pointer and then we go middle as you go to Middle dot or middle pointer dot next so then here we got middle and then we could just already done away with right so we could do that here um then now we do middle dot next and then that maybe should be good so now we return to PST of head and then let's give it a spin uh apparently we have some assertion error middle is not it's going to be none at some point um so get metal how when is this none when this is none maybe no because it cannot I mean if it's none that will be already be none so that's one node what happens if it's one node this they both point at the beginning of one note and then fast goes to and then slow goes to the one node right let's kind of look at this actually so basically you have one oh no wait oh also negative one is not good enough I guess uh because this is in the range but uh I mean I don't think we use it anyway but still so okay so this is the node we printed and middle let's just also print middle then just in case that one of them is good but hmm oh because we get rid of this that's why this looks a little bit awkward before okay why does this it's probably fine now if there's one node we just want to return that one node right so this means that this is a little bit off what do we fix this let's say faster next so basically if this one node faster next is not I mean we only do one elevation of this so that oh because this points after the first node um I wonder if this is enough um yeah maybe like okay so if middle is none then we only have one node maybe and then just return three node of uh middle or just node dot value maybe that's good enough I don't know let's see we don't have a base case for it though so maybe it was a little bit off anyway okay I mean we have answers they're not the right answers but you know that's progress uh is there a way to visualize this I feel like I've seen like visualization 2 or something right or it's not only in the old version because they like they have things that goes into a tree but maybe that's a little bit different uh what am I doing well I don't know because I don't know what this visualization thing is um let's see right so it's five let me draw it out on paper because I don't even know where my pencils are happening okay well there's one I don't know if that's good so let's take five is the root zero nine uh and then negative three no negative 10. oh negative 10 is a little bit awkward isn't it minus negative 10 all the way over here huh that is weird all right let's actually that why you all right let's take a look so oh huh so I guess my math was just wrong because it would because I am returning the middle note but not the note that points to the middle note so I have to kind of change this up a little bit uh we want to know that before this so let's just say pre is the go too slow um and then maybe just like three years ago to slow again and then we just do pre right it may now like one in the infinite Loop because what is that zero is good and then now there is some like awkward thing with some assumptions that we've made um okay let me think about this so now this is no longer possible so then that means that it keeps on going infinitely uh on in fact when this is negative 10 creates one and then creates the node so this is the middle wait where am I so middle Dot because then now it should be that middle dot next is none because this is okay so we wanted to put uh it's just so hard to keep everything in my head sorry friends um okay so then now this is the note before the metal node okay so then this is the middle note yeah so then we put zero is good but then now we have two elements and then two elements it points at the left one um but then it's still I think there's some like assumptions where if notice you go to middle or something like this then we don't do it um basically if there are two elements now we have the earlier one which is the opposite of what we had before that's kind of why it just messed up or not messed up but just a little bit imprecise how do I handle that case hmm because basically um what how do we want to handle this case is actually the same thing we did with pre-head I think pre-head I think pre-head I think um I suppose yeah uh and then now this is if no dot next is none then we return none um that's funny real quick just to kind of get a visualization but then now what we want instead of node negative three oh man because now we don't want the pre anymore hmm what why is this it's very easy to get well as you can see okay this is just very well so it was dividing by zero and then three and a negative 10 that's good but then it's missing uh the five so I think we're in a well and then now also it adds this thing somehow hmm okay now I'm just doing like random things so this is definitely not right but um all right this is way tough because we're it is way tough because I'm an idiot but uh let's see okay let's go back a little bit right so we want from first principles we want this thing to point to the node that is the middle right so then the middle we foreign go back a little bit this way you mess up so yeah I know I have a print I mean I know that's just gonna go okay so zero and then negative 10 is doing negative 10 so then it creates a negative 10 node but then notice you go to middle so maybe we just do something like if node is not equal to Middle then we just do this maybe that's good enough um I guess that is good enough I was I thought that it may be a little bit trickier so that's why do I need this I'm not even sure that this is quite right yet so let's uh let's give it a few more numbers I mean it's always sorted it's fine it doesn't change the answer so we'll see it looks okay let's give a quick submit okay so that looks good I think I just it's very hard to get these pointers quite right um and other edge cases I don't I the reason why I didn't do it I did think about this immediately but I didn't want to do it because I thought that's kind of a hacky way of doing it but maybe not I don't know um this is gonna be linear time uh oh wait sorry is it linear time am I lying um it is going to be n luck and time because this is going to be analog and depth um and each of these will have a linear node because we do the get middle I think I mean it's a little bit weird right because it's not again time because of this but let's say you don't use the linked list and then or you use the link because in space this is going to be linear space anyway so I think the smarter way to do it in theory but you would have to create extra space is converting the linked list to an away and it can bring that a way to binary search tree then you get the middle point and all one which means that you have linear time but uh but I don't know if that's in the spirit of things I don't know I mean you can definitely do it that way did I do how did I do it last time uh I get the length and then I get the middle note okay so this is the same complexity I think but yeah if you just like put it in an away it'll be faster but that's kind of I don't know that feels a little bit weird but that definitely is the more optimal uh time uh complexity so I don't know anyway um yeah that's what I have for this problem let me know what you think stay good stay healthy to good mental health I'll see you later and take care bye | Convert Sorted List to Binary Search Tree | convert-sorted-list-to-binary-search-tree | Given the `head` of a singly linked list where elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** head = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** One possible answer is \[0,-3,9,-10,null,5\], which represents the shown height balanced BST.
**Example 2:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in `head` is in the range `[0, 2 * 104]`.
* `-105 <= Node.val <= 105` | null | Linked List,Divide and Conquer,Tree,Binary Search Tree,Binary Tree | Medium | 108,2306 |
961 | okay let's talk about unrepeated element in size two an array so you are given the array integer nums with the following properties so note that the integral of two times n numbers contain plus one unique elements exactly one element of unrepeated end times so um there's a element that is occur more than once and you can actually return so for example this one three of course two times so you return three and then this is two right two of course how many times three times right and this one is five because only five has more than one uh element in the array so this is pretty simple so they just start coded so what i will do is i use a headset so if the number is not in the set i add in if the number is in the set i return the value so this is simple enough i'm going to write a hashtag and traverse the loop and if the number is not in the set i add the number into the set all that's why i return the number and this will be the solution but you need a return value for this function i'm going to say repeat 0 and let's just run it all right this is easy and i pass the test so let's talk about timing space complexity for this one so for time you do have to traverse every single one of the element in the nums array so that will be all of n and for the space the worst case will be um although all of them right but the problem is you will definitely return one element one integer in this set in this numps array so although the worst case olefin for sure right but you'll return one element at least and time is all open right you traverse every single one of it in the array and this will be the solution and if you feel is helpful subscribe like if you want it and comment below if you have any questions alright bye | N-Repeated Element in Size 2N Array | long-pressed-name | You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _times_.
**Example 1:**
**Input:** nums = \[1,2,3,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,1,2,5,3,2\]
**Output:** 2
**Example 3:**
**Input:** nums = \[5,1,5,2,5,3,5,4\]
**Output:** 5
**Constraints:**
* `2 <= n <= 5000`
* `nums.length == 2 * n`
* `0 <= nums[i] <= 104`
* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times. | null | Two Pointers,String | Easy | null |
1,721 | hey everyone welcome back and let's write some more neat code today so today I'll solve the problems swapping nodes in a linked list we're given the head of a linked list and an integer K and we want to swap the values of two nodes how do we know which nodes they are well that's what our integer K tells us so the first node or what I'm going to call it is the left node is going to be the kth node in the list so this is the first node this is the second node and in this case k equals two so this is going to be our left node now the right node is going to work very similarly except we're going to be starting from the right and counting in the other direction so one and then two this is the second node once we have a pointer at these two nodes it's going to be very straightforward to swap them because we can just take the values and swap them and then we get a resulting linked list that looks like this down here the four is now over here and the 2 is over here so the obvious way to solve this problem would be just to start at the beginning it iterate K minus 1 times which in this case would just be iterating a single time and then we'd have a pointer at the left node how do we get a pointer at the right node well we can't work our way to the left because the linked list is a singly linked list but the easiest thing to do would just be calculate the length in this case it's five and then we would want to iterate 5 minus K times in this case that's going to be 5 minus 2 which is going to give us 3. so what we would do is start all the way at the left iterate one two three times which would land us over here and then we can swap the two values that's a perfectly valid way to do it the time complexity would be Big O of n the space complexity would be constant but there's a slightly more clever way that you can do it which I guess I'll show you just because it's a tad bit easier to code up I think I blew this up so we can take a closer look at what exactly is going on when we start all the way at the left we iterate K minus 1 times we're over here let's say k is equal to 2. so now we have a pointer over here and do you notice that the distance between this and the beginning of the linked list is going to be the same as the distance as the end to the Target node on the right hand side okay but how exactly is that going to help us well the idea is two pointers that's kind of almost always the idea when it comes to like these complicated linked list questions well sometimes you need even more than two pointers that's the idea we're going to one save the pointer over here because we are going to need a reference to it but then what we're going to do is create another copy of that pointer and we're also going to initialize a pointer at the beginning of the linked list what we're then going to do is take these two pointers shift them by one each time so we shift it by one here then shift them again to their over here then shift one more time until they're over here by the time that our second pointer lands at the end of the linked list we know that the previous pointer will be at the other Target node and we know that because the distance between this is K minus 1 just like over here so that is the way I'm going to be solving this again the time complexity is going to be Big O of N and no additional space because we're just using two pointers over here so now let's code this up okay so we're given our head of the link list and that's what we're going to initialize our current pointer to initially and then we're just going to iterate K minus 1 times and each time just taking the current pointer and shifting it to the right by the way we are guaranteed that the length of the length list is going to at least be K so we'll never end up going like out of bounds here or getting like a null pointer exception or anything like that which is great and after that Loop is done executing we know that current will have our left node so let's save that in a separate variable left is equal to current now we also want to find the right node which we're initially going to set to the head and we're going to continue reusing the current pointer just like this we're going to say while current dot next is non-null which means while it hasn't non-null which means while it hasn't non-null which means while it hasn't reached the end of the linked list continue Shifting the current pointer but also continue Shifting the right pointer which is going to start at the head to make sure that the distance between these two nodes is always going to be K minus one so we're going to take right and set it to right dot next and again neither of these pointers will give us a null pointer exception because we're guaranteed to have at least K elements after that's done all we have to do is swap the two values which in Python you can actually do in a single line without a temporary variable like this left dot val and right.val are this left dot val and right.val are this left dot val and right.val are going to be equal to write.val and left going to be equal to write.val and left going to be equal to write.val and left dot val respectively the reason you can do it in a single line is basically python takes like a snapshot of the right hand side and then starts evaluating the left hand side it does evaluate it in order I believe like it'll set this one first and then I think set this one but that doesn't matter because these values will basically have been like snapshotted at least that's my understanding and after that's said and done all we have to do is we're return the head of the linked list which should not have changed at all maybe the value had changed but the head pointer should not have changed so we can go ahead and run this to make sure that it works whoops I made a mistake and that is I didn't actually update the current pointer over here sorry about that current should be equal to current dot next I don't know how I always make these sloppy mistakes but now you can see it does work and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of check out neatcode.io it has a ton of check out neatcode.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon | Swapping Nodes in a Linked List | maximum-profit-of-operating-a-centennial-wheel | You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100` | Think simulation Note that the number of turns will never be more than 50 / 4 * n | Array,Simulation | Medium | null |
382 | hello everyone today let us solve the problem linked list random node given a single linked list return a random nodes value from the linked list each node must have the same probability of being chosen implement the solution class solution list node head initializes the object with the head of the single linked list and get random method chooses a node randomly from the list and returns it value all the nodes of the list should be equally likely to be chosen okay so we have a linked list say one two p 4 and 5 okay whenever we call our getrandom method one of the nodes node values has to be returned and each node must have the same probability to be chosen okay so if we consider the probabilities of each of the nodes what is it going to be how many nodes do we have five nodes that is the total probability is one that is five by five to choose this node the probability is one by five to choose this one it's one by five this one is one by five and this one is one by five that is what means by equally likely isn't it so what are we going to do if we think about the naive approach okay first of all we know that in every programming language we have a random inbuilt function right which can Generate random numbers okay we are going to use this now in the name approach what we can do is we can convert this linked list into a list okay which will have indexing isn't it because in this one we don't have indexing so it's kind of difficult to choose from them right so we'll convert them to a list let's say this is our left one two three four and five now we will generate a random index how do we generate a random index in Java if we use the random function it's going to return us a random number between 0 to 1. exclusive okay that is it is 0.999999 like that okay never one so if 0.999999 like that okay never one so if 0.999999 like that okay never one so if we multiply this whatever suppose we get a probability of 0.5 okay if you multiply this into the 0.5 okay if you multiply this into the 0.5 okay if you multiply this into the length okay let's have a length is 5 okay what is the probability going to what is the index going to be it's going to be 0.5 index going to be it's going to be 0.5 index going to be it's going to be 0.5 into length 5 into 0.5 that is 2.5 which into length 5 into 0.5 that is 2.5 which into length 5 into 0.5 that is 2.5 which is nothing but index 2. we convert it back to an integer it's going to be index two so we are going to return this 0 1 2 let's say uh our random function returns us here let's say zero point seven let's say so 0.7 into 5 zero point seven let's say so 0.7 into 5 zero point seven let's say so 0.7 into 5 is 3.5 so we are going to return index is 3.5 so we are going to return index is 3.5 so we are going to return index 3. if you convert it to an integer okay so that's what we are going to do simple approach let's see the code so this is the code globally we declare our arraylist okay and here we initialize it okay in our Constructor so while our head is not null we add each of the integer values node values to our list okay then whenever our get random function is called we generate a random index okay that's exactly what we did math.random the number would be between math.random the number would be between math.random the number would be between 0 to 1 okay exclusive inclusive into list size convert it to a end we get the index and return list dot get random index okay so this is the simple approach what is the time complexity this uh method this Constructor is going to be called only once so that is a big O of n okay but this get random method can be called a lot of times right as many as 10 power 4 or 5 times in as mentioned in the question so let's say it's called let's say k times okay K times so our time complexity is going to be we go off n plus k the end to add the values into our list and K that is the number of calls okay now what about the space complexity we are using an extra space right we are creating this list that is a bigger of n okay so this is the name approach now what if we try to space optimize our approach we can't use a list right we can't use a list in that case we can't use the help of indexing so in such a case what are we supposed to do we will definitely uh generate a random Index right a random index now if we can't access that random in index what else can we do we will have to reach to that we have to iterate up to that index isn't it that okay we don't have a list so we can't access it so if we have a index and we want that uh want that value in that particular index there is no other way than to uh serially go through the linked list right up to that index let's say the random generated index is this one then we have to iterate through the list and reach up to here then only we can access it isn't it so this is also a possible solution okay so this is how the solution is going to look like globally we will have the length of the linked list and globally we will have a reference to the head of our linked list okay so in our Constructor we will compute the length okay we'll compute the length okay fine now in our get random we will generate the random index how just the way before right math dot random into length now we had our length here right globally so we can access it and we will start iterating from the head okay so start acting iterating from the head and initially our index is zero so while our index is not equal to the random index that we generated we will keep moving forward okay and we will increment our index and finally when we reach it right it will become equal equals to random Index right so in that case our while loop will break and we will finally return the value okay pretty simple right now what is the time complexity so our solution Constructor is taking a time of big off n isn't it and our get random method is taking a time of Big O of n now in the previous solution it was taking a big off one time isn't it but since we are making K calls we assumed we are making cake also it became K now since it's taking big of n time and we assume that we are making K calls so our get random method is going to be we go of n into k right so our total time complexity is going to be you go of n plus n into K which is uh simplified it's n into K only and our space complexity is this time constant we haven't used any extra space okay so that's all from my side we can also use an algorithm called Reservoir sampling Reserve wire sampling okay but that would be another big of n into K algorithm the last one that we saw was also big off and into carrot and the first one that we saw was we go of n plus K right but it used a big of n space isn't it so time complexity wise I mean that the first one is the better one okay so yeah it's totally your call okay so if you like this video do hit the like button share this video And subscribe to my channel and I will see you in the next video bye | Linked List Random Node | linked-list-random-node | Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.
Implement the `Solution` class:
* `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`.
* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
**Example 1:**
**Input**
\[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 3, 2, 2, 3\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3\]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
**Constraints:**
* The number of nodes in the linked list will be in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* At most `104` calls will be made to `getRandom`.
**Follow up:**
* What if the linked list is extremely large and its length is unknown to you?
* Could you solve this efficiently without using extra space? | null | Linked List,Math,Reservoir Sampling,Randomized | Medium | 398 |
1 | Hello guys my Sampantha welcome back to my channel text message send a video they want to discuss list problem number one but its problems let's get started problem states and enters the return of two numbers subscribe now to the number 90 number this particular 100000000 Inter Referral Vacancy That And In Its Numerous Janet Input Exactly One Solution Not To The Element Basically Itself Will Have Two Number Merger Friends Problem List 1999 subscribe and subscribe the Channel and tap on the Path What We Can Do We Can Find The Required Number 5 Minutes How Target Number Minor First Number Is Number 999 9999 To The Number One Subscribe Number Two 9 Question Which Can Take His Weapons Mtyas Maths Vighn-Vighn To Vighn-Vighn To The Number Tips Do n't forget to subscribe to Half an hour three to four skin deficit target inter research in the celebration with minor 93 subscribe to this number will not be to the number two to the attacks of wave 2K quiet Obvious That Indicates I Can See Her Outfit We Fight Election From Left Side Reaction Intelligence Test Element Subscribe Now To Receive New Updates Now Half Minute And Run Allu Which Will Start From Picture Tree In The Amazing Please Connect Number To The Return Of The Day Airtel ke bus din index of this request number and I which is the number simply not Ranbir will withdraw all pre-2005 notes subscribe The Channel Please subscribe and subscribe Ashwini hour later this 3 to 4 into foreign target from this hour Rekha 324 Entertainment Fiction Incident Frequency of This One to That is Also True Knowledge Test with the Three Do Subscribe Please Like Share and Subscribe My Channel Thank You for Watching My Video | Two Sum | two-sum | Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
You can return the answer in any order.
**Example 1:**
**Input:** nums = \[2,7,11,15\], target = 9
**Output:** \[0,1\]
**Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\].
**Example 2:**
**Input:** nums = \[3,2,4\], target = 6
**Output:** \[1,2\]
**Example 3:**
**Input:** nums = \[3,3\], target = 6
**Output:** \[0,1\]
**Constraints:**
* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**
**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity? | A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search? | Array,Hash Table | Easy | 15,18,167,170,560,653,1083,1798,1830,2116,2133,2320 |
1,621 | good morning my audiences how are you doing today we are going to study lead code 1621 together 1621 um you can search up in a little website for this description of this problem basically it talks about if there are any elements in points and you want to draw k lines with those elements with this points and those lines cannot overlap for example uh let me draw again for example you can draw like this or this you know or like this these lines can meet at one point but they cannot overlap for example like but they cannot overlap like this right that is not correct but these ones are correct so this looks like a dp problem um well how can we find the relationship between f n and f and minus one if we look at this i might thinking way of thinking is that here with the last nth element there are two ways two big ways to two categories to divide into one is um you don't totally don't include this line this point you just draw k lines with the n minus 1 points so that would be that would make it to f uh let's it's called dp a minus one and k right and the other is that um you always remember this is a inanimate even though it's five only five in reality and okay uh the other um point is that the other category is that you include this it's not this point so how many possibilities of that this scenario it would be if we it for this case for the first if it's uh only the length is only one that with you deduce that from here to here you have k minus one lines right because you already have one that here you have your mice must have k minus one that's one that would be dp n minus one k minus 1. right and for this well if the line starts from here and ends here that will be dp a minus 2 k minus 1 and this was the same thing that would be dp a minus 3 k minus 1 and so on and so forth until it's two i think uh you can only draw one line you can only draw lines with two elements okay minus one and you have to plus them all together and plus this one to get the dp and k yeah basically that's the trend of thought um here i'll let me write some code here right uh well first initially instantiate a dp array and okay i mean okay n plus one k plus one i just want to align the indexes so for uh first i'd like to instantiate the initialize the base cases the best case is actually uh for every uh any no any line and in any points you have if you have zero lines that'll be one that would be dp x one x naught zero equals to one of course you can also instantiate the big basil line base your case at dp x 1 equals x star x minus 1 plus divided by 2 that is also could be your base case these two are the same but i'm going to just start with this one 4 and i equals to dp 2 i is less than equals to k n i plus d p i zero equals to one that's the best case and then um let's build up the the let's build up the case of the from the bottom up uh when i um i'll explain later uh for this thing we can use uh prefix uh sum to represent uh for this thing for here you can see that it's this the batch is different from this one so it's always k minus 1 and this one is k so for this batch i will use the prism prefix sum for and let's call it length equals to uh one length than k l plus and you just say that there are parenthesis but and let's call it uh now that's the actually that's lengthy it's not very accurate that's lengthy is the case the length that maybe it's called k maybe small k would be better uh and let's view this as big k let's view this as small k and this is length actually length is uh from uh you can see from one less than and plus okay uh here i will create a sum this sum is used to uh to calculate this one yeah because it's a sum of uh the num the m plus one plus two plus uh minus one minus two minus three minus until um until yeah in two uh that's the and the divide and uh divided by k minus one so that's here at the map okay then dp l k equals to dp let's see l minus one okay now smoking plus some mode there's a mode because of the number could be very big and the initial result could only requires of the mode at first the sum is zero apparently then i will sum plus equals to dp l k minus 1. then here you can see that it represents this part as long as the l grows this not the sum it keeps growing let's examine basically that's it okay i have to mode by the mode and the sum anyway mode equals to mode just mode it to make sure that it doesn't overflow the integer let's examine the if the code is correct and note that this is just code i wrote just wrote it might not be correct but the train of thought is should be correct because writing code is very difficult let's examine that so when from length from when length is one minus one actually length is one and the k is one there's a one should be zero actually it should be zero but uh let's see if it's zero 1 minus 1 0 k is 1 0 1 and d p 0 1 should be zero because we only instantiate the initialize that uh zero one dp01 let me see dp zero one and it should be zero because only instead should initialize the zeros so if i didn't initialize the zero one it's zero so dp um one equals zero that's because yeah it should be zero because you cannot draw a line with only one point and dp two one the sum is zero sum is equal to zero two one equals dp 1 plus sum two one two watch b1 uh now still this zero this is zero interesting uh here no actually here uh this sum when l equals one now the sum here actually we will make the sum equal to dp one zero it should be this one is already one yeah this one was initialized at code here so it's one so sum is one and the next one when the l increment two the sum is one then the sum it's as okay it's sum is one here then it equals to 1. 2y is you is 1. so it's initializing correctly so far uh that's uh the codies should be correct uh basically that's my thinking of this problem if what do you think if you have any questions comments please leave uh below uh thank you and i hope you learned something bye | Number of Sets of K Non-Overlapping Line Segments | number-of-subsequences-that-satisfy-the-given-sum-condition | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints.
Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** 5
**Explanation:** The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
**Example 2:**
**Input:** n = 3, k = 1
**Output:** 3
**Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
**Example 3:**
**Input:** n = 30, k = 7
**Output:** 796297179
**Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
**Constraints:**
* `2 <= n <= 1000`
* `1 <= k <= n-1` | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. | Array,Two Pointers,Binary Search,Sorting | Medium | null |
49 | hello boys and girls and welcome to another episode of your favorite algorithm channel my name is Ryan powers and today I'm gonna be taking you through leet code 49 group anagrams so let's introduce the problem give it an array of strings group anagrams together okay awesome so what exactly is an anagram well if we look at this disarray of strings here we can see that they end up being grouped in this way where 8 and T are all grouped together and then NAT and Tanner group together and then bat is grouped by itself so what an anagram is a string that contains all the same letters right so 8 + 8 + T all the same letters right so 8 + 8 + T all the same letters right so 8 + 8 + T all can contain an E and a t and then Nats and tan all contain an N and a T and then that is it's the only string that contains B so it's by itself and I think the important thing to note here is that it doesn't um just have to include the same letters but also the same number of those letters right so if we had like a TTE that would be in a group by itself so that's kind of how we're grouping these together let's take a look at the notes of this problem here since all inputs will be in lowercase well that's really nice we don't have to account for uppercase letters we can just assume that everything is lowercase so while we're comparing our strings that's going to be making it a little bit easier and then the order of our output does not matter so what does that mean well that means that we can return these sub arrays in any order we don't have to return a you know this sub array in the 0th index position and this and the one and this and the two doesn't matter we as long as the anagrams are grouped correctly together we can return the output in any order okay so the one last caveat to this problem is I think maybe the easiest solution to come about would involve maybe sorting these strings but I would like to challenge you to do this problem without sorting right so that's going to be the solution that I'm going to be showing and the solution that I'm going to be coming up with and I think it is a good challenging exercise to maybe think try to think about this problem in a way where you could complete it without doing any sort so that's my challenge to you anyways well like always I suggest that you try to solve the problem on your own first and if you can't figure it out or you just want to see how I did it then check out the video otherwise for your get started come with me to the whiteboard so on the screen here we have our example array for example where this is the same example that we had in the opening of the problem and what's the strategy crew needs to solve this problem well first I first want to go through the answer where we're actually sorting the strings right because that's kind of the most intuitive way to solve this problem so what we're going to do is we're going to iterate over this array we're going to sort each string and then we're going to make we're going to hash each string to the sorted value right so that way any string containing the same letter count in the same letters is going to hash to the same string right so let's kind of go through around of solving that really quick so what's the first thing we're going to do we're going to iterate over our array of strings and we're going to first we're going to grab eat we're going to split that right then we're going to sort it then we're going to join it together and then we're going to check to see is this string in our object well it's not in our object right so we need to make an array for that make a bucket for that so we'll take a eet and we'll create an array and we'll store eat in that array and then we'll move on to our next string in the array and we'll get to T well what are we going to do teep we're going to split it we're gonna sort it and then we're going to join it together and we're going to check is AET and our object is so we're going to push T into that same array and we'll move on to ten so we'll split tune sort it and join it together forgot to join it there but we create a bucket ant right because ant was not in our object and we'll stick ten there okay great moving on to eight we're gonna do the same thing we're going to split it sort it join it we're gonna look for a eet we're gonna find it so we're going to push that into its corresponding it right moving on to net we're going to split it sort it and join it looking for ant we find it so we'll store that in that array and then finally bat we'll split it sort it join it will look for a BT we won't find it so we'll create a bucket for that and we'll push that into that array so what do we need to do at the end here what we need to turn our answers we need to iterate over those buckets and we need to just kind of push them into one array so that's going to be our answer set so that is the kind of most intuitive way to solve this problem it's certainly the way that I solve this problem the first time I looked at it and let's talk a little bit about what's the time complexity of this solution well if we say that n is equal to the length of the array so n is equal to the length of the array and then we'll say that each string will call that s right and what's the worst case here is the maximum string right so we'll say that X is equal to the maximum string that we have in our array so our time complexity is going to so we're going to be doing n things and then at each index of that array we're going to be sorting the string right sorting is n log n or in this case SS max log n right that's the worst case so we can say that our time complexity is a Big O of n times s log S or slogs right we can con select but what is the space complexity of this well space complexity this is Big O of n right because we are storing we're storing every value again we're restoring it and returning it as our answer I guess you could say if you don't count the answers for the space complexity then we're not using extra space but in this case we'll just go ahead and say that we are counting it as space but you could also say that this is a Big O of n times s right so if we basically count s as during each individual characters taking up space well then it's n times in the worst case the maximum string value right so that's kind of a quick run-through of maybe the most intuitive run-through of maybe the most intuitive run-through of maybe the most intuitive way to solve this problem but what we want to do is we want to figure out a way to remove this part right this log s how do we avoid doing sort right how do we avoid doing sort and turn this problem into an N times s solution how do we gain just a little bit of optimization here and do that and that's what we're gonna cover in the next section half and we want to go to Big O of n times s so if you solved it using the sorting method maybe take a minute think about how could we break this problem down and solve it in n times s without doing sort otherwise let's take a look at how we would solve it without doing a sort so on the screen here having a write full of zeros and each one of these indices and this array is mapped to a specific character so how are we going to create a hash how are we going to turn this problem into an N times s the length of the string well we're just going to use the character count right so we're going to iterate over the string we're going to get the count of the character we're going to create a hash for that string so each one of the indices in this array is mapped to a specific character there are many different ways we could accomplish this mapping we could create an object and manually have the letters as the keys and its index value as the index of this array and then we could get the index and map into this there are a few different ways we're going to accomplish it but we'll go into that in the coding portion of this but let's just say that we have a way of mapping each character to an index in this array so that's what we're going to do so we're going to iterate over this array of strings and we're going to iterate over each string and we're going to create a hash for it so let's go through around the solving this problem and get a better idea of kind of how this is working so we'll iterate over the array first and we look get to eat so well iterate over each well we'll find that we have an e so we'll increment the index at E we'll find that we have an X so we'll increment the index at a we'll finally have a T so I can write the index at T and then we will join this all together into our okay so we'll check our object for that hash we don't have it yet so we will push eat into the bucket for that's kind of ugly I think that's gonna work itself out but we'll push eat into the bucket for that hash and then we'll move on to the next item in our right and we'll reset our array and we'll move on to T what will iterate over T we'll find a T will increment that we'll find an e we'll increment that and we'll find it will increment that we will join this together creating our hash oh yeah we have this hash already I recognize it's right there so we will push T into that same bucket so now we have a hash that contains E and T it will move on to the next item resetting me right moving on to the next item 10 okay well you're right over tan we'll find a teep well plan a will find an N will create a hash for that and we don't find it so we will create a bucket for 10 and we'll push that in and we'll move on to the next item in our array 8 so we'll iterate over 8 we'll find a at E and eat and we'll stringify that together and we will find it in our object a te and so we'll push 8 into that curve corresponding bucket and we'll move on to the next item resetting okay well iterate over net we'll find an N and a at E and this is the hash that we come up with what we have that hash so we'll push that into that bucket and we'll move on to the next item so the final item is bat so we're bat will find a beat and eight and a T and the hash is going to be this thing we don't find that in our object so we create a bucket for bat okay so that is how we solve this problem without doing sort right but you might be asking me or asking yourself hey Ryan we just had to create this giant 25 index array to actually hash this thing which it seems in some cases that it might be better to do sort like if we have a bunch of three-letter if we have a bunch of three-letter if we have a bunch of three-letter words well that's prot that could probably be true but um let's go over kind of how does the time complexity of this prom break down okay well first of all we'll push all our answers into this array there's our answer array but ok what about the time complexity okay so still our array down here is equal to N and our string is still the maximum string right but what about this part well yes we're iterating over each of our strings but what about this part here so what is the time complexity of doing this operation right because we have to create this array we have to create a hash for every single on for every single string so in the hash is much longer than the current strings are working with but you can imagine that if our string was not one word right maybe it was a sentence right or a phrase or a grouping of words well it could get a lot longer than 25 spaces so iterating and creating a hash could be less expensive than actually sorting right the longer the input grows the more time-consuming that sort the more time-consuming that sort the more time-consuming that sort becomes but the hash creating the hash is always constant right and why is it constant well because the hash is only twenty five spaces long and will always be twenty five spaces long it doesn't have an impact on the size of the input right the sorting becomes more expensive the longer s max becomes right s max so that is dictated by the input values but our hashing is twenty five spaces long it will always be twenty five spaces long so we can consider this a constant time operation it's constant it's twenty five it is twenty five operations but it is constant it does not change it is always twenty five and that's why we can say that going through and creating this hash is a constant time operation right so the actual variable part of this is the iterating over s right and that is how we get our time complexity of a Big O of n times our Max s max right that's how we get the time complexity because the only thing that is dictated by the inputs are N and s the construction of the hash is constant time operation so that is a breakdown of the time complexity and what about the space complexity well it's still the same as it was in the previous problem okay so hopefully I think the idea of coming up with the character counts is definitely something that could come to your mind but maybe creating a hash is not something that it's definitely not something that I do very often maybe it's not something you do very often either but it is a pretty cool way to approach this problem and maybe something we can kind of put in our tool belt next time somebody asks us to solve this type of problem without sorting right so let's see how we execute this in code in the next section so on the screen here we have our group anagrams so that's going to be the function you use to solve the main part of this problem but let's create a helper function so let's create a helper function call it create hash and create hash is going to do exactly what it says it's going to create a hash so it's going to take in a string and then it's going to return to us a hash that we can use so inside of this hash function the first thing that we need to do is we need to create an array to hash into so we can say that our Const hash is equal to an array so we want our array to be the length 26 right so there are 26 characters in T alphabet so we want to do array 26 dot fill and we want to fill it with zeros so this is kind of the creation of the hash this is our s had 25 earlier but I meant to say 26 character indices that we have to create every time we make hash so this is kind of the initialization of that so that will give us our hash and then we want to iterate over our string so we can just create a loop for that so we'll let I equal 0 and while I is less than the string dot length well we'll increment I okay so then at each part of this iteration we need to get a mapping to the correct index to increment the value right so we need a variable index so we'll say index is equal to and then what we need is we want a number that corresponds to each letter well all of our letters are going to be lowercase we don't have to worry about capital letters so we can actually get the character code which starts at 97 so a starts at 97 right so that's kind of our zero index value so we can say that we want a string dot care code at act will pass in I so that's going to give us a character code at the I position so and what we want to do is we want to subtract 97 from that right because a is the first index which is going to be the zero index and the character code for the ASCII characters for a starts at 97 and goes to what whatever 97 plus 26 is Z so if we just zero it out by subtracting 97 that'll give us kind of the index of the corresponding bucket that we are looking for so then we can say that the hash at index is equal to hash the current value at that corresponding index plus 1 right so we're incrementing that value so we'll iterate through the string we'll increment that value at each iteration and then at the end we want to return the hash so we'll do hash dot join and we'll join it with a string so that will kind of that will give us our hash so now grouping the anagrams actually becomes fairly simple and we're going to do this in a pretty slick way so we're actually going to reduce so we'll just start this out with a return statement and we will say that we want to reduce this array of strings right so we'll do STRs dot reduce and we'll pass in our accumulator and our value into our function and the value that we want to pass in is an object but what we also want to attach to our object is a property called answers and we'll attach an and that would be an array so we will push our answers into this array as we are mapping or hashing so we'll also have our hash keys in here with the corresponding buckets but when every time we initialize a bucket we'll pass it into our answers so the first thing we want to do is get a hash so we'll say a Const hash is equal to create hash and we want to pass in the current value which is V so V is going to be each one of our strings inside of our strings array so we'll create the hash and then we'll say that so we'll say if a hash so if the hash exists well then we just want to do a hash which will return us that array and we want to push in that current this current string so we'll push in B if this is not the case if the hash does not exist well then we need to create that bucket right so the else case is that the bucket does not exist we need to initialize it so we'll say a hash is equal to of a array and we'll initialize it with that string value right and then the next thing we want to do the slick part of this is that we can actually say that a dot answers because we've created we have created a an array that are a property answers on the accumulator object and that property answers is an array right so we can push into a dancers so you're a dancer stop push and we can push in a and the current hash right so every time we push an item in this if case here if it already exists well we're going to push that next string into that bucket and this array of answers here is a its array just has a reference to all of these different buckets inside of it every time we create one we push a reference into our answers so we're kind of keeping track of that array while only having to push into the array one time we're just saving ourselves the trouble of going through this object the end and then manually pushing all of those items in so of course we have to return a at the end our accumulator and then at the end we want to return dot answers so this whole reduced function is going to result in our object that is our hash map that has our answers property on it and then we want to return the dot answers part of this as our final answer okay so let's see how we did see if we got any bugs here all right so there's that and let's submit okay great all right so I don't know what's going on with leak code again but they seem to always want to slow down my runtime to make me look bad so we're gonna play the same game where I grab the best answer on leak code and run it against our solution so ours is faster than 68% let's go ahead and check out than 68% let's go ahead and check out than 68% let's go ahead and check out how the best solution that we can find on we code is running you all right so here's the distribution let's zoom in on this part you know what let's zoom in on this part let's grab one of these Alzheimer's here how about a 95th percentile solution awesome so we'll grab this okay okay and we'll paste this in here man that's shorter it looks pretty good let's run it oh all right I mean that's pretty good so we're kind of in the range here we're four milliseconds slower I can deal with that anyways I hope you enjoyed this video I hope you learned something and I hope to see you in the next one | Group Anagrams | group-anagrams | Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** strs = \["eat","tea","tan","ate","nat","bat"\]
**Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\]
**Example 2:**
**Input:** strs = \[""\]
**Output:** \[\[""\]\]
**Example 3:**
**Input:** strs = \["a"\]
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= strs.length <= 104`
* `0 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null | Hash Table,String,Sorting | Medium | 242,249 |
18 | look at number 18 for some we finished the threesome and here is the foursome so we're giving array target to zero we need to find out all the solutions that 4 with 4 which has four elements which sums up to zero so actually we're already finish the threesome so I'd like so please refer that first I'll just write the solution it's very straightforward the first step is we sort at the elements and then loop through the elements we fix the first elements of the result the leftmost two like four here and then fix the second one here and do the four - cursor for one here and do the four - cursor for one here and do the four - cursor for the rest and then remove then the curt remove the neck second element to the next one and two the two cursor again pay attention to the pay attention that we need to skip the skip to skip the turn when there are consequential same elements okay so the first step is that is returned for the irregular cases like okay for cost result if moms and small enough for of course we just return the result now sort coal causes a Oh log okay and now we fix the fur first Edmund so for I for the first name for the first element because it's leftmost each start from zero okay so here not we should stop at these sediments which is minus 1 minus 2 minus 3 minus 4 so smarter than them right matter 3 because it's the first intamin so we can safely say a skip if now we fix let make sentiment so here we should do the same but here's a problem that J actually starts from one right so the first for the first one it might be the same to the I element we need to say that J must not be the first Jane must not be the first element for the for all possible numbers of J so we need to say J must be bigger than I plus 1 ok now we start to cursors need K cross J plus 1 let's l equals last the last index part case more than L sum equals if it's 0 push the result if it's smallness or equals a0 remove K and move to the next different number so if K knows K equals nums k minus 1 k plus one we do the same for L and yeah that's done return results we run the code a runtime error ah God if you pushed it ray accept it let's submit zero we should expect it empty if we're given away of zero this solution is this R is zero ray should return empty why mm-hmm let's copy that ah God target sorry it says the target is not zero I'll God so if it's target we push this smaller than target well it's very simple with this trick it's a target so this is my bed yeah it's not fast but it's accepted and okay that's all for today so we need to get the time complexity here is log N and there here is a four two loops so actually it's end to the square cubic so time I think this is the time I'm not sure whether that's right or not but yeah and the space Wow I don't know how to say this maybe three see it and not sure anyway that's all for today see you next time | 4Sum | 4sum | Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that:
* `0 <= a, b, c, d < n`
* `a`, `b`, `c`, and `d` are **distinct**.
* `nums[a] + nums[b] + nums[c] + nums[d] == target`
You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,0,-1,0,-2,2\], target = 0
**Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\]
**Example 2:**
**Input:** nums = \[2,2,2,2,2\], target = 8
**Output:** \[\[2,2,2,2\]\]
**Constraints:**
* `1 <= nums.length <= 200`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109` | null | Array,Two Pointers,Sorting | Medium | 1,15,454,2122 |
477 | A Slow Gas Today We Are Going To Discuss Very Interesting Problem No Problem You Still Having Distance Which Elite Code Medium Problem Of But White Manipulation Solved Problems As Word Problems Statement This You Will Give And We Are Of These Teachers Black Spots Give Energy Office Hand To Such person element of The Amazing and you have to find out the total having distance between the choice for PM 300 meter water representation OK taste for this day and to so let's find out the distance between the 400 feet and see the point presentation like this distance Vote To Position Withdrawal Different * Write Number Vote To Position Withdrawal Different * Write Number Vote To Position Withdrawal Different * Write Number 98100 349 Having Distance Between Among The Best Different 14 Minister In The Notice Of The Same How To Connect With Different That Minister Took Planning Distance Between 20 Numbers Vipin Bisht Se Assistant Now Let's Calculator For Reporting And To na vacancy date ok health bad singh and then all the best with sim that to position business different * number 100 sister distance business different * number 100 sister distance business different * number 100 sister distance to for distic poverty and to wear calculator for this is the distance between not subscribed ki facility answer to now Rahul Services and evil return the function 5 to select first try to concentrate upon doing but number single fix total distance between what is the first day do subscribe two phone number to this minor e request and in this number to this dam request so you can find Which you have as you know data how to convert department - over sleep which converts department - over sleep which converts department - over sleep which converts decimal to binary and detachment to be not active due to demin the spelling e agri computer kissing with destiny positions of different fluid you are d sharma positions with different so absolutely soft Total Account Increase The Total Number Of Account Between Similarly For 42nd Calculate The Blind And Converted Into Complaints And Every Single Fix Total Distance Between To The Function Of Yesterday Morning Just Post Matric Of Doing Great Slashed The Flats In Very Difficult To Give R Tears Might Have discussed at time complexity of developed for the benefits of considering this and every player of the day soen hindi me thought we are going to do we are going to check the number and reviews and the number of we meet position to what is the independence day Sapoch wear considering meanwhile position is I aapke show tobacco hero tar MP3 which is the size of a are welcome to that edition knobs sideeffect nickel all the best 409 dubai know how many distance between any of the receiver consider reduce position not the best will be Different a flat swift the ki another bit position with his first position due drops position sunna hai 102 9th total number of fear on jai hind consider chhatri the best way to hello how this is that solid also help us find the hai medicine pina char To Hai Medicine 349 451 980 Point To 9 Foreign Tour With Him In The Prayer For Rain To Give One So A Total Family Distance Will Be The Number Of Account Of Reviews And The World Multiply Vipin Chandra I To Let Soon Sample To A For This Bit By position total number of dynasty 2 end numbers upt 212 yesterday morning tottenham distance between early all backward teaspoon number how is to every country having only made fatig and four wheel real power bits in this position nine this ministry for foreign to the best all different and Definition a nice mirchi powder do and asking them back side effect to clear getting result on do the cost a number of pollution and number of wave divine today going the distance between them is the number of bluetooth on number of world comes to the size of First Darwin is Minister's Subs and SIM and Debit Card's Electric Board 10th Total Number S2 adv1 Morning and Distance Between Channel Bittu Always How Ek Aaj Ki The Number of Baroda Do Ki Underworld Firoz Ban Phone Samsung S4 and Proteus Excursion's Exit Subscribe Not Fit For B.Ed Exit Subscribe Not Fit For B.Ed Exit Subscribe Not Fit For B.Ed to tarah minister has even considered the difference between point to the best all things to share with you and distance from its an order total answer will be the addition of all the who in this method will take maximum and Into Love In Time For Calculating Is Now How Can Be Implemented At Sita Implementation Of Disputes Through As You Can See Torch Light Decoration Is Medicine Skin Was That Number Opposition Activists Half Inch Back Side Effect So What You Have Done Is Front Side The End Slide Available And physical 2019 we have but root from 0238 miding 54331 bittu is so what you have done within there lives to give video and deposit account of 0tweet warden hair attack in the end of the element subscribe to who is the end of the number and the K Physio Unlimited Fun Within 6 Last What You've Done This Number One And Number-15 Spite Of Her In The Days When He One And Number-15 Spite Of Her In The Days When He One And Number-15 Spite Of Her In The Days When He Position Twitter Back Side Effects If They Have Implemented Number Of Verses And That Redmi To The Answer For Band Which IS USED TO CALCULATE TOTAL NUMBER OF GRITTEN WA A GLASS NEW MISSION KA ANSWER A K MEMBERS SIMPLE AND COMMISSION'S WEBSITE INCLUDES THAT AND IF U K THIS STAND THAT BEST PROVIDED MOST OF EACH A SIGNIFICANT AND DEDUCTATIVE DO SUBSCRIBE OUR CHANNEL THANK YOU Is | Total Hamming Distance | total-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 an integer array `nums`, return _the sum of **Hamming distances** between all the pairs of the integers in_ `nums`.
**Example 1:**
**Input:** nums = \[4,14,2\]
**Output:** 6
**Explanation:** In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
**Example 2:**
**Input:** nums = \[4,14,4\]
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 109`
* The answer for the given input will fit in a **32-bit** integer. | null | Array,Math,Bit Manipulation | Medium | 461 |
633 | hello everyone and welcome back to another video so today we're going to be solving the lego question sum of square numbers all right so in this question we're going to be given a non-negative we're going to be given a non-negative we're going to be given a non-negative integer c and our goal is to decide whether there are two integers a and b such that a squared plus b squared is equal to c okay so a quick example is when c is equal to 5. so in this case a could be 1 and b could be 2 and when you square them you have 1 squared plus 2 squared which is 1 plus 4 which is equal to 5. and in that case a squared plus b squared does equal to c so we return true but now with the number three for example there's no combination of numbers which is going to give us uh the value three so for example let's take one and one then we would get uh two right which is too small now let's take uh two which was four and what uh any other number we add is going to be greater than or equal to four uh so it doesn't really matter so let's see how exactly we can solve this question and before actually uh so let me just show you how we can actually get or reach to a better method or step by step okay so let's start off with an example of c is equal to five so we're taking c is equal to five and what we're going to do in the beginning is let's just use our most naive solution now when we're looking at this um our goal is to find a and a b and if they exist when squared then and when you add them up it's equal to c then in that case we return true else we return false okay now in this case our goal is to look for a and b now how exactly are we going to look for a and b in other words what is the search space going to be so realistically it tells us that a and b are integers so we could have everything from negative infinity up to positive infinity this could be our search space but one thing we can just directly get rid of is all the negative numbers because remember we're squaring these values so anytime we square a negative number it's going to end up becoming positive so for example negative 10 squared is the same as 10 squared they're both going to be equal to 100 since the negative is uh we get rid of the negative so we don't need to worry about any negative values so the range is now going to be zero to infinity but now we can actually make it a lot easier so in this case so let's say uh to infinity right so let's say we go up to a hundred i'm just going to take a number saying hundred but in this case c is five there's no reason to go to a value greater than 5 because look if we take the value 5 itself 5 squared is 25 that's too big so in this case we can just stop our search space up to the value c itself to our space could be zero to c so let's see what that looks like for this over here we can obviously simplify this further more but let me just show you what this looks like so let's say we have zero one two three four and five now what we could do is we could have two for loops and these two for loops are going to iterate through all of the possible pairs so we're going to get all of the possible parents that we have whatever they are and each time we're going to check after squaring them and adding them is it equal to c and if at any point it is equal to c we return true so this over here is going to be big o of n squared and this is going to be our brute force solution but the problem with this is the values of c as it shows us over here it could be all the way up to 2 to the power of 31 and that's almost 2 billion values so obviously this is not a good approach okay so let's see how can we make search space even smaller okay so in this case uh we have zero one two three four five now the other thing to actually notice is what is the largest value we can get okay and actually uh let me just take a simpler example just to kind of show you this so let's say uh c is equal to 25. now the first thing that comes to your mind is well 5 squared is equal to 25 now one way of looking at this is uh one of the numbers could be five so let's say a is equal to five now in that case b is just going to be zero so what i'm going to show here is there is never going to be a number greater than 5 which will help us satisfy its condition of a squared plus b squared is equal to c right and the reasoning is pretty simple because if 5 squared is equal to 25 6 squared 7 squared or whatever anything past that is always going to be greater than 25 no matter what okay so this is one way we can further shorten our search space so instead of going from 0 to c we can only we can just go from zero to square root of c okay and in this case that's going to be uh so let's say c is equal to 25 our range is going to be zero all the way up to square root of 25 which is well nothing else but the number five so zero to five so this actually decreases our search space by a lot so in this case let me just write it so from zero to c we're only going to go our search this is going to be zero to square root of c because anything square root of c is automatically too big so in this case what is the square root of five well it's gonna be two point something and we're gonna round it down so we're just gonna look at zero one and two so this over here is going to be our new search space okay cool now in this case these values are also so now again we can run two for loops look at all the combinations obviously we do have fewer pairings but still since we have since c can be all the way up to 2 to the power of 31 you want to further simplify it and that and the way we're going to do that is instead of having two for loops and looking at every possible pair what we're going to do is a simple two-pointer approach we're a simple two-pointer approach we're a simple two-pointer approach we're going to have a low pointer over here a r and a high pointer or let's just call it right at the very ending and the basic idea is that each time we're going to calculate the value so currently we have 0 squared plus 2 squared which is well equal to 0 plus 4 which is 4. right now 4 is too small so whenever the value is too small the goal is to look for larger values and the way we do that is by moving the left pointer to the right by one because well obviously the values on the right are greater and if the values are too big we move the right pointer to the left by one that's it and we keep doing this until we find a solution and if we find a solution we return true and if we don't find a solution and at any point the right pointer is less than or equal to left pointer then we break out of it and we return false so now at this point uh the left pointer was here we move it to the right by one so it becomes over here and now we have one squared plus two squared and as you can tell that's one plus four which is equal to five so perfect we reach the value c and in this case we return true okay so this is going to be our search space zero to square root of c and then on top of that we're going to use a simple two-pointer method so now let's simple two-pointer method so now let's simple two-pointer method so now let's see what this looks like in code all right so the first thing we're going to do is defining our two pointers so l and r now l is going to start off at the zeroth index and r is going to be at the very ending sorry not zeroth index is zero the number zero okay and r is going to be the uh ending the last value in our range and to get that like i showed you it's gonna be the square root of c so we're gonna use math dot square root c and let's just import map up top over here so import map cool so now we have l and r defined and now what we need to do is we go in a while loop now in this while loop our condition is going to be we're going to stay in it as long as l is less than or equal to r now at this point we need to calculate our a squared values and b squared values so let's just call this a 2 for a squared and this is going to be l squared so we could just do l squared or we could just do l times l same thing right and now we need our b squared value and this is going to be r times r okay so now we have a squared and b squared so now what we need to actually check for is we've got to check if a squared plus b squared is equal to c and we're going to have a condition for that so if a square so a2 plus b2 is equal to c then in that case that means what we found our answer and we don't need to actually do anything we can just directly return true and if this is not the case the other condition we have is if this value over here is too small so let's just see how so the way we do that is if a2 plus b2 right and if this value is two is smaller than z then in that case we want larger values and the way we get larger values is by moving l to the right by one so by incrementing it by one and we do that by doing l plus equals to one now if this is not the case we could just do else but this would be more specific i'll have an else if condition and this is going to be when a2 plus b2 is greater than c so now the sum is way too big and we actually want smaller values and we get this by decreasing or decrementing the right value by one so r minus equal to one and that should be it so if at any point we exit out of this while loop that means that while we weren't able to reach the number c and that means that we cannot find its value with a squared plus b squared so we are going to return false so let's submit this so there's one small thing i actually forgot to mention so when we take the square root of c we want to round it down and i didn't do that so let's first do that and we're just going to int math that squared c so for example the square root of 5 is going to be two point something right but we're not going to consider that we're only going to go up to two so when we convert it to an end even it's something like 5.9 it's going to end up just becoming 5.9 it's going to end up just becoming 5.9 it's going to end up just becoming the number five okay so we convert this to an end and now it should work so submit it so as you can see our submission was accepted so thanks a lot for watching guys and do let me know if you have any questions thank you | Sum of Square Numbers | sum-of-square-numbers | Given a non-negative integer `c`, decide whether there're two integers `a` and `b` such that `a2 + b2 = c`.
**Example 1:**
**Input:** c = 5
**Output:** true
**Explanation:** 1 \* 1 + 2 \* 2 = 5
**Example 2:**
**Input:** c = 3
**Output:** false
**Constraints:**
* `0 <= c <= 231 - 1` | null | Math,Two Pointers,Binary Search | Medium | 367 |
44 | hello let's try to solve another lead code problem number 44 wildcard battery and we are giving a straight s and a pattern P so implement the wildcard pattern matching with the support for question mark yes and the star so for the question mark it means any single character yeah for example this is a b and this is the C and here is the question mark this means the question mark can be any character can be C that is equal but for this b and a it is not equal that is y with true false yeah and for Star it can match any sequence of characters including empty so for example here this star can be empty they are not equal but it can be any characters for example it can be a and a yeah so they are equal it can return true but for this one the first one is a but for the second one there's nothing so it is false now let's see yeah basically this problem is going to be done with the dynamic programming yeah for the Matrix it is a 2 000 times 2000 it is still okay and SNP as our screens and P only with the question mark and start and any lower case English characters let me first go to the Whiteboard and then go to the code Editor to finish the coding yeah so let me go to the Whiteboard to explain it so basically I'm going to use a example like 3s equals to A and P equals to Star I'm going to consider all the situations why we can solve it using DP this is the DP tabulation yeah for the wild card version I used to use the tabulation to solve the problem so first of all I will prepare some empty strings before this a and before the star so when we are dealing with the DP problem the first step is to have the initial state so what is the initial state it is the empty string yes so I'm going to deal with the empty string so if I have empty string with the empty strip of course this is true yeah and if I have a star this means the star can be anything the star can also be empty this means if I have a star I just need to check the value before it so before it is a t so it means here will still be true yeah because this star can be empty so I'm going to soft attack What what is the Boolean value before it so it is the true so what about the column so the First Column this is empty because this is empties here is the two but with a of course it will be false and here another 8 will be false this is why I will Define my DP array PP array always initialized with Force after that I will set the first value as 2 yet because this is empty with empty so it definitely it will be true yes and also I finished the First Column and the first row of the DPR range now I will go to the Second Step the second step for the DPL final transformation function so what is the transformation function is like that there are two conditions one condition is a question mark another condition is a star so for this example I'm not going to tackle the question mark Or if they are equal because it is simple but the difficult part is the three it is the star so how we are dealing with the star so for example this is a star what is the here what is this value it is the true or false so there are basically three conditions so the first condition is this star can be empty what if it is empty so it will be here so this empty compared with this 3A it is the force so this is the first condition what about the second condition so this star can be a character one character it can be a if it is a here is a if we did the uh added a distance or some other DT problem we know that if this is a and here is also a because this is star equals to A we're going to check the value before it like here this value yeah so the if it is IC we're going to check the value I minus 1 and C minus one we're gonna check this one yeah so this are the first two conditions but what about many so the star can be three since one is empty one is one a another is many we call it many characters yeah so if it has many characters it means this star okay has many A's as many as possible yeah so what are we gonna check we're gonna check what about we take this a off we take it out so here becomes an empty string but here because we can have as many as possible so here is it just means we take this a off with the this is the last screen yeah so here is are true so this means if we take even yeah and because the star can be as many as possible so what is for the star is in a 1A yeah it is still of course it is still okay but what the star is empty or star has two A's it is still okay but for this situation so here is 1A we can still compare this take this a out yeah if we take this a out so here we will compare this empty string to this star as we know it is a true so in this case this many a means a MP3 so it is true yes but what about the second but what about this one yeah so this one we're gonna tackle the first one so if this star is empty we're gonna check this one here empty with two eights here is one a two a it is a fourth yeah if this star is empty so what about this star has one A if it has only one a if it only has one A light here so this is one a this is a we're gonna check so it means one a is not possible to be two so what about many so the third step is to check many if the star has many A's here if this star has many A's yeah so it means if it has many characters I mean here is a it can be many but what if this starter have many characters it has many characters what about we take this off because star has many characters it means we can take this one off it is still totally okay because this star can have many so here we start to take this a off here means many minus one yeah many characters if many is a minus one so we just check if we take this one off which have if it is equal so here this a equals to many characters yeah so it is still equal so this means it is a two so what I'm going to do is I'm going to compare all of them so if this is three one two and three one of them is a two enemies I'm going to return a true for this uh saddar situation yeah no so the hard part is the star means many if it means many so here it means we can take this one off and it didn't influence our result because the star has many characters it means the character a plus minus one times a is we still have a n characters so in its value so this means we can take this one off if we take this one off we still need to compare before these characters so before these characters they are equal so it means it is equal yeah now let me go to the code Editor to finish the coding use the method yeah so I'm going to Define r and say as low end columns so here though will be length s so will be the three plus one and line P pH is pattern plus one then I'm going to define a DP array so the DP array will be as I explained it will be both times column and for I or are influence R so the for this step we defined our DPL array and then the first step will be in it yeah the state so for any to the state we just need to have the DP 0 and 0 to be true yeah as I explained and then we are going to check the star so for C is ruins one two say is t say minus 1 because here start from a one so we're gonna to we're going to use the first character of the three so here will be C minus one yeah because here is one we use an empty and three first yeah so this is a y yeah and the p c minus one if this equals to Star we're going to initialize the first dose so the first row will be the DP 0 say should be equal to VP 0 say minus one yeah so this is basically means here so if this is a true so if this is the star we're gonna check the previous value it is a t so it will gonna be true yeah it will keep the same value as the previous value so and then I'm going to finish the Trust Transmission yeah transformation function yeah so the transformation function will be for Aryan reads R and for saying rings say so here we're gonna start from the one because as I explained before the zero will be 0 will be for the first rows it will be used this Loop and for the first value will be true so here I will start from the one and also for the column I will start the index 1 as well so we're gonna First tag if this value the surgery R minus one because here I use this R to represent so this is why I use the capital r and C so here similarly I will use the lowercase R and C if this is equals to P say minus one so this is one condition or P say minus one equals to the question mark yeah so this means if the first character for example the character adds the first character they are equal in this situation here is a or here is this say or this is a question mark So if this is a question mark it does matter this character yeah so this is a the first condition we're gonna use DP R and C equals to DP R minus 1 and C minus one yeah so this is easy because if they are equal we're going to check some value before him if there are two it means we're gonna return true and if we're going to check the second condition yeah so if the p pattern C minus 1 equals to Star yeah if it equals to Star the DP are say this value should be equal to DP R minus one say o d p r C minus one or DP are say this means from here yeah if this is a star here we're gonna attack three values this one and this one as I explained each one of them the difficult part is this one means we have many characters we're gonna just take this out to check if they are equal yeah so our result will be let me enter the result will be DT -1 -1 -1 yeah now let me run the code to check if there are any mistakes yeah it seems okay now let me submit it to that if it can pass all the testing places yeah for the DT problem it is very difficult we must yeah I mean the programming is easy but it's really difficult to think you may think about this one or this one here but for the last one it's really difficult to think why you need to have these three conditions because the meaning of the star it can be empty it can be one or it can be many so yeah for all the parts if you considered all the parts it means you can find the solution if you only find two parts you identify to the last one or you didn't find the first one or the second one definitely you're gonna yeah you will not gather the right solution thank you for watching if you think this is a helpful please like And subscribe I will upload more difficult problems like that thank you bye | Wildcard Matching | wildcard-matching | Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:
* `'?'` Matches any single character.
* `'*'` Matches any sequence of characters (including the empty sequence).
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "\* "
**Output:** true
**Explanation:** '\*' matches any sequence.
**Example 3:**
**Input:** s = "cb ", p = "?a "
**Output:** false
**Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'.
**Constraints:**
* `0 <= s.length, p.length <= 2000`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'?'` or `'*'`. | null | String,Dynamic Programming,Greedy,Recursion | Hard | 10 |
732 | That them guys welcome back to my channel vriddhi dutta and in this video is not discuss about this thought was not mycalendar posted by cbi on 20 presented out because this video has gone definition of the series right gold behavior discuss spoon hardware problem just quantum of previous Approach August 1 Hour Approach Of MyCalendar To Problems And Set This Problem In These Heart Problems Na 150 Light Bill Default Basically And Use This Pin Code In Last Problem Right And Will Just Wicket 9 And Use This Problem Poverty Should Not Take Much Time Video Those Issues But if you have come then 20 crickets are equipped with water system, you can subscribe to 100 people, meeting is Panchami's events is not and interaction do something on to all key business meeting, you write your personality yes now we start admin, this is only 3000 mute not intelligent Representing Maximum K Booking Will Always Gives Immediate Right Shoulder Joint Family But Even Audit Use Accountable To Understand What Happened In This Number Per Division Has Gone Now All Care Tourism Sector Return Value Off The Counter Everything Is Not Working In Fluid Just To Maintain The What Is The Maximum First Age Limit Sinks Life Into Parts And Justice Return Refrigerated Rights Is But Will Just Absolutely Maximum Of The Counter For The Bill Will Be Transplanted How Do Subscribe To Select Electronics Review On Activity Your Half 1020 Lights Of Units Warriors Pest Problems With Facebook And When You're Fear Not [ __ ] Videos Of And When You're Fear Not [ __ ] Videos Of And When You're Fear Not [ __ ] Videos Of Vitamin A Small Simple Thing The Best All These Twelve Vatican What Is The Maximum Number Of Winter Means A WhatsApp Message Number Close Muddy Skin Please Note Slashed To Criticism Of Life Which Is 1020 Life Will C Hadith 1021 You will remain only bus stand Bihar display will continue to be found Vidron in this course at any particular and beauty Commerce Ministry has shifted the image Can have just park that and sixty flash lights are next comes and body referee lage written with support for every household with Water Meters And Tired Now Comes End Quality Subha Stand Quality Residence Of Something Like You Will Return To Be Cuch So Now Between Stand To Any Danger To Events Run Fluid 125 ST Suno Phase And Sunao Drishti Veteran Initiative's Between This Time Frame 1015 Guava Aisa Military Tightening Consciousness Mit 50 Urgent 125 Points Hai Mein Aa Second But Interaction Bus Ko 800 Vitamin C Em Bigg Boss Sofia The Maximum Event And Maximum Number Of Baje 324 323 325 5.0 Anil Gote This Song Again Heading In This 5.0 Anil Gote This Song Again Heading In This 5.0 Anil Gote This Song Again Heading In This Point Will Have Two Events Of Burning In Five Years Will Have To You Went To Vaikuntha But Maximum These Three Super Speedo Meter Street Lights Whiteness Debit The Inventor Well-defined Book Which Simply Will Well-defined Book Which Simply Will Well-defined Book Which Simply Will Return That What Is The Maximum Number Of Eliminating Early Morning Proceedings Of The Video Union President Platform Youtube New Software Development Schemes and Development Tutorials Subscribe to Videos Villain Book Development of Development Phone Number Building Internship Like Professional Development Environment To Install Develop Attractive and Lordly Streams CSS JavaScript Mountain Return Mode and Development Trust You Will Learn Java Spring Boot Space API MangoDB Testing and Those Half Programs Will Work With Multiple Professional Web Development Schemes In Front Of Your Profile And Take Good Care Of Yourself Thank You All The City That Was My Channel Problem Climate Change In Two Videos Subscribe Subscribe to Zee TV Must Subscribe Video Problem Solve your problem with just a few lines and aaj tujh jaisi difficult copy aur kaun isko open end begusarai send reminder karo volume isko death chini kid president ko dalog select2 included in corporators pay just miti ki mez drinks pet you will be influencing for days And Tried And Say Funds Tractor In The British In More The So Basically What You Are Doing This Will First Insulting Start And Stopped And Definition Of Residence For Any 10 - 15 Residence For Any 10 - 15 Residence For Any 10 - 15 Number Fix And Avid Traveler This Is Like Or Subscribe Or Share And Subscribe 340 subscribe to the two - - - - And two - - - - And Destiny 125 One Act 2005 Video Pimental Other Checking Difficult And At Any Point Of Time Which Will Be Removed And The Native May Return Forms Will Not Alliance Double But MyCalendar Problem Stripes De Research Of This And Vitamin Tour And Travels Private Limited Spotted Padukode World Tourism Day To Maintain Come Expect Bread Sites Twitter Google Maps Booking Stretched And Related 2012 Is Wheel Factory Booking That One Of Math And Match Referee Booking Main Maths The Festive Booking Site And Is Considered To Be A Day To All Of For you watching this point questions, Prashant Test Inter College is in Ireland, that someone is vote bank, Vitamin C is in the warm office, Britain is in Bigg Boss tank and Sanjay Dutt's Chocolate Times, It's good too and likes every passing day interval. Between the officer and this is placid over the swimming all the best for you and you have recommended you to give and ride this thing convert and drop back to lines video and subscribe To My Channel press The Bell Icon for you True Videos And Content It's Do n't Forget To Follow The Example Of Hearing Now At This Time Old Subtle Life Scales To End Academic And Order Situations And Topics Press 29 And Difficult To Follow Instagram And You Want To Reach Of Money From Any Thing You Can Give Strength and witch to be the demolition of twenty-eight order comment below demolition of twenty-eight order comment below demolition of twenty-eight order comment below pain from this video help you out if any election 2014 everything dentist comment below and every month and happy to resolve1 price subah swasti and lecturers in mycalendar seats will meet in all unique Zara Do Videos Pride And Told HT Stays And Finds Interested | My Calendar III | my-calendar-iii | A `k`\-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.)
You are given some events `[startTime, endTime)`, after each given event, return an integer `k` representing the maximum `k`\-booking between all the previous events.
Implement the `MyCalendarThree` class:
* `MyCalendarThree()` Initializes the object.
* `int book(int startTime, int endTime)` Returns an integer `k` representing the largest integer such that there exists a `k`\-booking in the calendar.
**Example 1:**
**Input**
\[ "MyCalendarThree ", "book ", "book ", "book ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\]
**Output**
\[null, 1, 1, 2, 3, 3, 3\]
**Explanation**
MyCalendarThree myCalendarThree = new MyCalendarThree();
myCalendarThree.book(10, 20); // return 1
myCalendarThree.book(50, 60); // return 1
myCalendarThree.book(10, 40); // return 2
myCalendarThree.book(5, 15); // return 3
myCalendarThree.book(5, 10); // return 3
myCalendarThree.book(25, 55); // return 3
**Constraints:**
* `0 <= startTime < endTime <= 109`
* At most `400` calls will be made to `book`. | Treat each interval [start, end) as two events "start" and "end", and process them in sorted order. | Design,Segment Tree,Ordered Set | Hard | 729,731 |
223 | Hello Gas, the daily problem of Azamgarh is rectangle area, so this is a medium question and also easy and first of all we will look at this question, two big rectangles are given and we have to find their total area, so I think it is very easy. You take the area of two easy. You take the area of two easy. You take the area of two rectangles but one in each. The problem is that the two rectangles will be overlapping in such a way that they will have to mine the common area between themselves, the bottom left of the first and the bottom right of the second. This is my second X1 y1 and its second We have to get the total area. We are making the total area. I have to get the area of this. I have to get C get the area of this. I have to get C and this has given me -3 So now and this has given me -3 So now and this has given me -3 So now see how this voice will be exported, multiply it, how much it becomes, 24, then look, its area is 24, which you look at this, how much is its base, look from here, 6, how much is the height, four is 6 * 4. How much is 24, which is a how much is the height, four is 6 * 4. How much is 24, which is a how much is the height, four is 6 * 4. How much is 24, which is a rectangle, we get diamonds in this way, so this is our first area, how much is the second one, I write somewhere here, how many areas of the first one is 24. See, its base is you and how many are vans below it. 2 - 1 then you and how many are vans below it. 2 - 1 then you and how many are vans below it. 2 - 1 then how much is three then nine in three then 27 so its area is 27 Now you see this when I took out the first rectangle area, this area of mine also got covered in it area of mine also got covered in it area of mine also got covered in it and when I took out 27 yours, it covered it again. We are being shown how the dun comes out, which one is this, meaning here there will be an How will I get out, I [Sangeet] [Sangeet] [Sangeet] Now I stand here and I Masting from here, you can see it 9 witch 9 and its first setting Wich three common area, how will you come out like experts like minimum Now look at me, what are the old coordinates of this, if I make zero here, then what will be the result, that is, if I have to find the quadratic of Its X2 and your triangle's X2, which of these two is the minimum to see, so you have to take the dragon out with a little minimum and it is also coming from behind, so this is what I think is zero it's mains. Now how will I get out of this mobile again, I will get the brother of both of them out And now I have got the base 24 + 27 which was our add, how much out of 51 and 51 if I do 12 - Our total is this much area A. If we mine it, we should have | Rectangle Area | rectangle-area | Given the coordinates of two **rectilinear** rectangles in a 2D plane, return _the total area covered by the two rectangles_.
The first rectangle is defined by its **bottom-left** corner `(ax1, ay1)` and its **top-right** corner `(ax2, ay2)`.
The second rectangle is defined by its **bottom-left** corner `(bx1, by1)` and its **top-right** corner `(bx2, by2)`.
**Example 1:**
**Input:** ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
**Output:** 45
**Example 2:**
**Input:** ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
**Output:** 16
**Constraints:**
* `-104 <= ax1 <= ax2 <= 104`
* `-104 <= ay1 <= ay2 <= 104`
* `-104 <= bx1 <= bx2 <= 104`
* `-104 <= by1 <= by2 <= 104` | null | Math,Geometry | Medium | 866 |
1,339 | welcome to august leco challenge today's problem is maximum product of splitted binary tree given the root of a binary tree split the binary tree into two sub-trees by the binary tree into two sub-trees by the binary tree into two sub-trees by removing one edge such that the product of the sums of the sub-trees is of the sums of the sub-trees is of the sums of the sub-trees is maximized return the maximum product of the sums of the two subtrees and since the answer may be too large we turn it modulo 10 to the ninth power plus seven note that you need maximize the answer before taking the mod and not after taking it all right so if we're given a binary tree here we want to find the edge that we want to split it by and the two sums of the binary trees now we want that product to be maximized here it's going to be 110 splitting it at between here one two all right so that sounds really complicated and it certainly does seem hard but they give you a big hint here it says if we know the sum of the subtree the answer is total sum minus subtree minus sum times subtree sum so that's kind of a big hint what we can do is traverse through our binary tree we know that it's quite large here so we have to do this in oven time pretty obvious so what we'll do is traverse our entire binary tree and first find the total sum that's really the only way to find it so we'll find out total sum first then we're going to traverse our subtree again our binary tree again and at every node we're going to calculate the let's say total sum of the left side or i should say rather the subtree sum of the left side and the subtree sum of the right side and we'll try to calculate the max product there depending on what the answer is we'll maximize it and we'll just move up all the way to the root uh whenever we find that it's like an empty one we're at a leaf it's basically we're just gonna return a zero here to basically if we split it at an edge where it's going to be none then it's like we're just you know multiplying 0 times the sum of this total sum so thinking about it now i guess that's a little redundant but whatever we'll just do it the way that i solved it first so the first thing we'll do is first calculate the total sum okay and total sum of our tree will write a helper method here we'll call it dfs sum pass in a node and we're just going to traverse the entire tree to find what the cumulative sum of the whole binary tree is so if not node we'll just return zero and otherwise what we'll do is return say no dot value plus node dfs sum of node.left sum of node.left sum of node.left plus dfs sum of node.write of node.write of node.write and this will be our total sum here i actually don't even think i need to set that dfs sum of root so great so now we have that let's actually keep track of this here because uh we don't want to get confused all right so now that we have our total sum let's um traverse our tree again so we'll have our output here start with zero and we're going to write a another that first search starting at the node and same thing if not node will return zero and we want to find you know this the value of these sum of the subtree on the left side and the value of the sum of the subtree on the right side right so let's go with left this would be what whatever is returned here on node.left node.left node.left and whatever gets returned here on node.right node.right node.right then right at this point we are going to update our max output we'll say max of self.output and we have two things self.output and we have two things self.output and we have two things we have to calculate right we have either total sum minus left times left or total sum minus right times right and this is kind of the key here we have to return the no dot value plus this the value itself here and the sum of the left side on the right side right so left plus right okay so all we have to do now is just call our functions and finally return our output make sure to do a modulo uh what was it 10 to the ninth power plus seven right okay so let's make sure this works all right looks like it's working and accepted so time complexity is going to be o of n and space complexity will be the same now is there a way to do this in one pass you know there might be uh there's probably cleaner ways of writing this but you know sometimes like you come with a solution and then it works and you're just excited with it so i'm just going to keep it there i'm sure there's slight improvements you can make but it's good enough all right thanks for watching my channel remember do not trust me i know nothing | Maximum Product of Splitted Binary Tree | team-scores-in-football-tournament | Given the `root` of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.
Return _the maximum product of the sums of the two subtrees_. Since the answer may be too large, return it **modulo** `109 + 7`.
**Note** that you need to maximize the answer before taking the mod and not after taking it.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** 110
**Explanation:** Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11\*10)
**Example 2:**
**Input:** root = \[1,null,2,3,4,null,null,5,6\]
**Output:** 90
**Explanation:** Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15\*6)
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5 * 104]`.
* `1 <= Node.val <= 104` | null | Database | Medium | null |
1,678 | let's do problem 1678 gold parcel interpretation so the question says that you own a go parser that can interpret a string command the command consists of an alphabet of G open and close brackets and open and close brackets with Al in between in same order in some order the goal passer will interpret G as the string G open and close bracket as the string o and Al with open and closed brackets as the string Al the interpreted string are then concatenated in the original order given the string command return the gold pares interpretation of the command so all they're saying is that there could either be something like this that is part of the string so command is a string that will be provided and going through the command string you'll find if you find something like this open and close brackets you have to replace it with o if you find something like open and close brackets with Al in between you need to replace that with Al and if you find something like G you need to keep it as G itself so how will you go about it simple I'll just create an arring and keep adding uh keep convert go through the command string from left to right and as I find these elements I'll in that string I'll add the equivalent in the uh in the array and then update it and then join it and return it right so I could simply do if I find something like this then I'll check if I find something like this after it then I'll add o else I'll add a because if this is not after it then definitely a is after it there's only one two possibilities of getting something after the Open Bracket this Clos brackets or a so if I get Clos bracket I'll add o else I'll add a and if I don't find open uh bracket then of course what do I find g so in that case I'll update it to be G that's it how do I do this in code let's go about it so I'll first of all in initialize an empty string store it in s empty array sorry empty array to written s and within this I'll add my converted values and finally join it and return so and then I is to iterate from left to right and in this case if I go in this F Loop I'll increment I by two if I go into this else Loop I'll increment I by four and if I go into this L Loop increment I by just one okay so let's do go about doing that while I is less than length of command if command at index I Is An Open Bracket then go inside the block and check if command at I + 1 is block and check if command at I + 1 is block and check if command at I + 1 is closed bracket then add o to the array s then I + then I + then I + 2 increment I by 2 else if I have not found a closing bracket which means there is an a after it in that case I'll add Al to my array and increment I by 4 then I'll check if I did not find at command at index I did not find an opening bracket which means there is a g there and so I'll add G to the array and finally increment by one and return the I'll join the are into a string and return let's run this and see that worked 8 milliseconds better worked that worked 8 milliseconds better than 93% of than 93% of than 93% of solutions and if you see the best solutions they would be using replace function which is an internal function of python not expected in interview setup but yeah that is also one of the way to do it simply replace in place call replace and pass in the uh the part to be replaced and the part and with what you need to replace that with that's it let's look at one more solution and this is following something similar to what we did so that's how you solve the problem 1678 gold parser interpretation see you in the next video | Goal Parser Interpretation | number-of-ways-to-split-a-string | You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order.
Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`.
**Example 1:**
**Input:** command = "G()(al) "
**Output:** "Goal "
**Explanation:** The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal ".
**Example 2:**
**Input:** command = "G()()()()(al) "
**Output:** "Gooooal "
**Example 3:**
**Input:** command = "(al)G(al)()()G "
**Output:** "alGalooG "
**Constraints:**
* `1 <= command.length <= 100`
* `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order. | There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same? | Math,String | Medium | 548 |
473 | hello everyone today's daily code challenge is matchsticks to square here it's a medium level question uh the question given is we have given an integer array which is named as matchsticks here every i of a matchsticks will represent a length of a matchstick and we need to use all the nastics to make one square and we should not break any stick and we should link up them and make a square and we should and the condition here mentioned is we should mention we should use matchstick exactly only once if we can make a square by using this matchsticks then we should return true otherwise we should return false we will understand the logic behind the question by help of algorithm the algorithm of a question will be as follows first condition should check is all the sides of us matchsticks all the sides of a polygon you are making using a matchstick should be equal that is if one side is yes all the side should be s only all the sides will be s only and the another condition will we will follow is we should check whether the matchstick array length is less than 4 or greater than 4 if the array length is less than 4 we should write return false because at least we should have 4 or greater than 4 to make a square using a matchsticks so we will directly written false if for the length of a matrix if length of a array of matchsticks is less than four the second condition we need to follow is we should check whether the array sum of map match array sum of matches some more values of arrays of sum of values of matches is giving a reminder 0 when divided by 4 whether it's giving a reminder for a reminder 0 when divided by 4 or not if it doesn't give a remainder 4 then we should directly return false if it given if it will given uh reminder zero then we will go for another statements okay let's start coding then we will know how to write a recursive function for this math box okay friends now we start coding first we need to check whether the length of array is less than 4 or not if it's less than 4 would directly return false because uh the length should be greater than or equal to four to make an a to make a square so if m dot l e n g t h less than four we directly return we directly written false here uh and the next condition we have to check is whether our sum of an array is uh some of an array is giving a reminder 0 or not if it's not giving a remainder 0 then we will see written false so for that first we need to so first we need to find a sum i will make a for each loop using for each loop we will try to find the sum of an array uh i'll initialize sum outside first in sum equal to zero and sum equal to zero sum plus equal to a now i'll check if the sum is with the equal to 0 or not if it's zero then i will return directly false if it's not zero then uh if it's not zero we need first we need to sort uh sort our array and we will apply a recursive function by comparing uh by comparing another array side and our match our matchstick array so sorry friends i need to rename this i'll uh i renamed this as m so it will be easy for coding okay now i'll sort arrays of arrays dot short res dot short and now i'll return i'll sort m and i one more thing i need to do is i will i'll make another array and initialize all the elements of our array by sum by 4 as uh as we are calculating for square which has a four sides sum by four i'm sorry it's comma not semicolon sum by four some by 4 okay now i will sort the array and next i will return my recursive function dfs by parameters match m sites um side m dot l a n g t h minus i want to travel from last of our last of a given from la from last of a given array 2 i need to compare the last element of a given array and the element which i have initialized side so let's see how our recursive function is working okay this is our matchstick array and there is our side array which you have initialized with the sum by four uh here all the values is already initialized as two because the sum of these matchsticks are a will be equal to eight by four by equal to two all these uh all these values are equal to now so we will check from starting element of the side and ending element of math match uh if the element in the match is less than or equal to side of i then we need to remove the element then we need to subtract the match element from side array and update the resultant to the side array again so 2 minus 2 will be equal to 0 which will be updated to side array and we need to call recursive call again for this one and we need to compare this and this if again sides if again match index is less than side index then we need to minus match index from side index and update the resultant to side index again we need to make a recursive call if it's uh again we need to make a recursive call by decreasing indexing index array and increasing i array we need to increase i and we need to decrease match array index so uh so now we will see the coding part of this recursive array recursive function uh the recursive function will be i will declare it is a private and it should return a boolean whether it's a true or false i will declare it as boolean type and dfs int array match again one more array sites again i actually i will i'll assume this value as idx and now uh first we have to check whether the condition if i dx equal to minus 1 then we are array out of bond that means we are traversing from last to front of match array if idx equal to minus 1 then we already reached a last element and we are going out of the bond so when we reach that element we'll dial it will directly written all the elements of a side array but we need to check one another condition uh all the elements of a side array should be equal to each other so we will return side array as side array of 0 should be equal to side array of 1 sides array of 1 and those should be equal to sides of 2 so sides of 1 should be equal to sides of 2 and those should be equal to sides of 3 so sides of 2 should be equal to sides of 3 that's it if i dx equal to 1 we will directly return sides array and we need to check all the elements of the size array are equal to each other and after that we will make a for loop and we need to traverse the size array from 0 to its length obviously it will be equal to 4 but we'll do this length sides dot length if we have discussed in our algorithm section if match of index if match index is less than size array then we need to minus the match array value from sides or a value so match of idx if match of idx is less than or equal to sides of i then we need to remove the value match index mass idx from sites match idx from sides and we will make another slope in this after this we need to write another recursive function so if dss of match sides and idx minus one here idx first we will traverse from idx then again idx1 if it's true then again request a function will be called for idx minus 2 so like that if i dx minus if it's true if this condition is true then we'll return true then we will return true directly if this condition fails then no it will not come in the else first we need to return true and let's understand first we need to check this value then we need to make another accuracy call if it's true we have to print directly true we have to return directly true then we need to add sides of i less equal to match of index we need to add directly index and return false here if this condition is true will return directly true if this condition doesn't true doesn't make any sense we will make we will written false directly uh i think that's enough now let's try to run the code sorry it's a compiler one more sides of i it's an array it's not in variable directly sides of i minus it's true we'll check for another test cases also yes it's true and we'll submit yeah 40 okay thank you | Matchsticks to Square | matchsticks-to-square | You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**.
Return `true` if you can make this square and `false` otherwise.
**Example 1:**
**Input:** matchsticks = \[1,1,2,2,2\]
**Output:** true
**Explanation:** You can form a square with length 2, one side of the square came two sticks with length 1.
**Example 2:**
**Input:** matchsticks = \[3,3,3,3,4\]
**Output:** false
**Explanation:** You cannot find a way to form a square with all the matchsticks.
**Constraints:**
* `1 <= matchsticks.length <= 15`
* `1 <= matchsticks[i] <= 108` | Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this. We don't really need to keep track of which matchsticks belong to a particular side during recursion. We just need to keep track of the length of each of the 4 sides. When all matchsticks have been used we simply need to see the length of all 4 sides. If they're equal, we have a square on our hands! | Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask | Medium | null |
1,630 | okay let's try to solve today's L code problem 1630 arithmetic subes now what this question says a sequence of number is called arithmetic if it consists of at least two elements and the difference between every two elements or consecutive elements is the same just like here 13579 is arithmetic sequence because 1 and three has a common difference of two five and three is a common difference of two s and five has a common difference of two and 9 and seven has a common difference of two in the second example 7777 has all the 3 and minus1 has a common difference of four -1 and- 5 has common difference of four -1 and- 5 has common difference of four -1 and- 5 has a common difference of four and- 5 and - a common difference of four and- 5 and - a common difference of four and- 5 and - 9 has a common difference of four now we have given an integer array nums and two arrays of M digits called left and right so what we have to do is we have to on the basis of the we have to check that whether the sub particular subar is an EP or not it is basically an arithmetic progression question so let's try to understand by this problem okay so let me give them a index so you can understand better now here we have left and right array and on the basis of these index we have to check like whether the sub ARR is in AP or not for example the first one here is 0 to2 now we can check from these elements 4 6 and five and on the basis of these element we have to check whether it is a whether it is in Artic pration or not now what we can do is we can sort this are here so on this on basis of sorting it will become four 5 and six and hence every element here has difference of one so will push true into our answer now let's check for a second one 0 to 3 here is zero and this one is three so 4 6 5 9 let's again sort them they will become 4 5 6 9 this one has one common difference this one has one common but this two elements have three so we'll push false and let's check for two and five I'm so sorry if you are confused by my drawing but I'm not very good at it I'm using Mouse that's all so let's say from 2 to five now the elements are five 9 3 7 again let's them becomes 3 5 7 and 9 and on basis of them we can check like these two have a common difference of two and these two have a common difference of two now why we are sorting because why we are sorting it because then we can rearrange the elements and on the basis of that it is very easy to check if it is in AP or not so let's solve this question let's get the query size first of all we need a query size so we can call it m and this will the query size now let's look through the now as mentioned here we have to check for these two elements these two sub arrays so we'll extract them from the array so let we can call it left equals L five so right of R5 now we have these both uh indexes what we have to do is we have to form a new array as we are forming here so let's declare a new array let's call it array and num there the function JavaScript called SLI slice from left comma right plus one because this slice function only works from here till here we have to add one more value so we can get left to right both now let's deare a new Val let's call it is AP and you can declare a new function and check if this is AP or not and whatever our result is so deare array result and whatever our result is will push it into our array so is AP will be push here you can return is AP now let's create a function to check whether the array is in AP or not again it is very simple let call it array so what we said it we have to sort it the array so we can check for arithmetic progression now let's sort it AR sort again in JavaScript you have to use it like this so it will be sorted in numerical order now let have a common difference again class 10 mathematics formula R of 1 minus AR of zero now we have two elements the difference of two elements now let's loop from second element till the size of are and we'll check array of IUS one is not equals to the difference then we know it is not an artic progression we can return false or here we can return true everything looks great now let's try to run it oh sorry my bad should be this not is indeed we got submitted and let's submit this thank you so much and do subscribe if you like the video thank you so much | 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 |
49 | Hello how can you identify the graphene gives strength and Polytechnic is right at least to two to eight samples were tested in A plus B square feet profit Tank Stratfor faced this problem Bike collided with the driver killed Problem Hair Straight Forward Use K Nire Do Something That To Group The Exam Together For Little Water And Gram Hai Trick People When Cigarette P Tag Remedy Ready Made Of Same Number Of Characters Is Look At The World Listen And The World Silent Yukt Diet Subscribe Silent Sperm from a saiya anti interwar listen all you can find the same character right silent and different perspective from now understand better is my latest batter first test case you have enough strength and the worst thing is it district sperm time letters pe that is look loongi dark Water stress can you find out the same characters you can see but you also have the same characters pen date of the same characters Paytm e right this site one group that is look more you can see but you have a string pen and you can Find one more thing and it will also have the same can configure an lite to 20 groups so I did that is group exit poll result of that you can app has one group only affect your perception truth not and 08 2010 that positive yoga group of Death and grant there light similarly in taste is number 2fa the world in at the same character fight for truth only three characters in her the world car of directors and he also for group d letter in her third group of letter in health e Will Test Case No. 3 Destined for 8th Class Strong Input is MP And Hence Your Heart Will Also Be MP Distinct of Your One Table to Find Any Process Right Seems Very of That Naav Phenomenal Solution Today's Problem Is Very Office's Tried to Take Up Every Street and compare effective remedy name of the other and inform all of that but this pretty cup is time complexity of order of inquiry they want to improve it's right to latest way they can go about doing that is to computer solution complete method to take advantage of fact That they need to point and grime and point to point property of gram can e and effective apna original example of the word silent and left in dwipoon tharane respectively remember that mean best trick fame characters pe ko support both of din berukh like right shift silent earthquake Something Like This Half Fuel Less Something Like This Hai To Yukt Bhi Data Positive Wala I'm Able To Feel The Same Trick Right Love You Can Give This Property To Advantage Latest What We Can Do Not That All This And Right I'm Taking Up Map Where I Can Give All Distic For The Part Of Speech For Tree And Values To Play List Of The Tree And Values To Play List Of The Tree And Values To Play List Of The First Readers This World But Will Get The World And Team Joe Pisces Shot Right What Does It I Check Map Effect Can Not Find Ishwar Demand's Side Of Thiswar Chart that by putting according string for which it gets relief but you were still wondering to my husband quantity in next to again tried to appointed as Pune next to again tried to appointed as Pune next to again tried to appointed as Pune explosion also amazing anti that now you tried to look up this water in Indian map this time you Can find out to her right what does it at distic in love with you the correct how to import packet third trick tan now gift david beckham they zain right again tried to look up distic in her eyes met you can find out what is abs zain I Just Add Folding String To My Group That Noticed That In The 21 I'm Just Sugar For Telling Bheego Swift 200 Grams Do The Same Right And Busy Property 210 338 Shifted Again On Twitter Maze Find This Again In My House Map So Simply 821 Hair Movie such diet roti get changed into a great scientist great map where the world over share in the last word such best shopping changed into a b c d that a can't find any house map to aditya uber hair and lord krishna in world in Here I am possible to find out all of my group and you need to return in this list of strings Veeravrat the time complexity of dissolution good care of in log where is the length of maximum strength and this number three do subscribe to improve Be it on the table at UP office to take advantage of fact that you need to find a branch where everything properties of fire and sacrifices character but if inter subscribe and subscribe the Light of day and subscribe Governor 98 Camp Take Advantage of this property to Categorize and lower income latest what we can do 100 I am creating house map where it grew up in all of district together but how to fill up placement latest pick up falling but from this brother who rule e district have to 8 and in this how I can Feel her to be given in this can be of frequency spring be quiet tele has data 271 also industry occupying peer water into that giant achievement string in my easy to be one and artificial waterfall at torch light that to informed that if the country By Distic also you can see the tune of 281 BB again got its name after 10 in measurement history of to my hair you know me to three to one and difficult to find the value of frequency to give vote to two and three ki naav kand Find You String In Frequency Map Right Side 1002 And According String In Value Hai Flash Light To Eid-ul-Azha Once Again Be Flash Light To Eid-ul-Azha Once Again Be Flash Light To Eid-ul-Azha Once Again Be Upcoming It To Mostly In Original Unimportant To That Now Mode Off But Right To Create Frequency Of Trains Of My New elementor so this tends to be one b2 and distance and dubai jevan b-2 b-3 light look distance and dubai jevan b-2 b-3 light look distance and dubai jevan b-2 b-3 light look like can you find a b1 b2 so this day bittu in here and corresponding string that and you can find a 153 for and frequency map And then you write down the correspondence strings and volume to group UP 1022 and 30 grams together and you will notice that you can find a frequency string in time complexity of water and that this length is always different and features and tricks. You Need Any Additional Time Complexity of Order of N in Health The Total Time Complexity of Which Solution Good Care of and Multiply by K Quarters Solution Guddy Faster You Not for Selection in Solitude and See the Phone How to Understand Better Iron Limited Come and Example There They stop and 30 grams in the lap of mother code to porn 300 grams of pure input parameters trick digestive very for the next day and they have wickets left in the 500 index of birth storing the frequency string and observe that they are going forward to all oo Deliberate and 14 element in next pass history parameter subscribe channel but no from the delhi chief the generated subscribe in the map in to-do list and left key map in to-do list and left key map in to-do list and left key and 10th please my frequency screen saver key value pair now half created in my map light weight Reduce Again And Each Time You Will Create A Frequency Of Bud Buran System Generated Beam Seven Between 21 Can Not Mind Map And Hans Seven b2b Edit And Un Lift Form With A String Bv Edit That This Third Edition Of Budh 108 Generator Frequency String And Distance From System Generated B2 B1 Again You Can Find The Right Click Add Distinct To You Can See All Confirm This Is How Your Retirement Age Populated And Its President At The Very And You Written All Of The Value Of Frequency Is The Latest Film Life Is Trick ABC B and want to generate frequency street light 98100 bb2 21 right what happens during ifin such a parameter next to meanwhile cricketer frequency but is dark definition of two initially and elements basically story the frequency of character scientist great and thing character of district what so to This BCD Letter The Nine Way Can Be Treated As You Right Breast In Just One Neck Tupac Again Distinguished To The Next Person The Letters Patent Puberty Right Side Effect Director Changes 212 Main Koi Ghee Ad UPSC To Isko Change Hanuman Pendant This Can Bring Change In Frequency of now you know the frequency of the character of frequency and benefit character of the day to independent directors pe white vinegar character plus in the frequency of this ajay devgan bittu f3 plus so aakar actor vikram fee and veep and frequency of eid f1s that going Ahead Effectiveness In Up And Everything Like D0 A0 R0 Upvayi Do That Correct On This Are Has Been Agreed Up On Between Simply Return This Frequency String And You Can Always Be Original How To Check The Like I Ho To Problem And Solution Andheri Important Questions Interview Company Twitter And the solution of the problem is Question in time complexity and the only thought in two in hospital after 200th test This explanation problem is available on our website at To-do list website at To-do list website at To-do list subscribe my channel and motivate video Problem is | Group Anagrams | group-anagrams | Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** strs = \["eat","tea","tan","ate","nat","bat"\]
**Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\]
**Example 2:**
**Input:** strs = \[""\]
**Output:** \[\[""\]\]
**Example 3:**
**Input:** strs = \["a"\]
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= strs.length <= 104`
* `0 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null | Hash Table,String,Sorting | Medium | 242,249 |
255 | welcome to interview Pro in this video Let's solve another lead code problem to verify pre-order sequence in a binary verify pre-order sequence in a binary verify pre-order sequence in a binary search trick as per the problem statement we will be given a array of unique integers and in the pre-order the pre-order the pre-order if that forms a correct pre-order if that forms a correct pre-order if that forms a correct pre-order sequence of a binary search tree we have to return true otherwise we have to return false let's take an example with an array of integers so let's try to form a binary search tree when we say pre-order it's root left and right so pre-order it's root left and right so pre-order it's root left and right so first we have 10 will insert it then we have 6 then we have 3 we have already inserted the root node and also the left node then comes the right node which is 7. now we have a node 13 which comes to the right of 10 then we have 12 which has to go to the left yes it is less than 13 so it goes to the left which is correct then we have 15 we have already finished the root which is 13 left which is 12 now we have to put it to the right does 15 go to the right yes because it's greater than 13 and also greater than 10 so we have 15 to the right this is a direct pre-order sequence of the binary direct pre-order sequence of the binary direct pre-order sequence of the binary search tree let's take another example where I'll replace number 13 with 5 from the previous example so insert node 10 we have inserted root now we have to go to left so 6 is less than 10 so it goes to the left which is correct this in this recursion now 6 is the root then we have 3 which has to go to the left 3 is less than 6 so yes it goes to the left then we have 7 which is greater than 6 so we have filled root left and now 7 is going to right so this chapter is a proper pre-order sequence chapter is a proper pre-order sequence chapter is a proper pre-order sequence now we have node 5 Which is less than 7 so it goes to the left of 7 but every node that is to the right of 6 should be greater than 6. now when we insert at 5 to the left of 7 we have to make sure that it is greater than 6 but 5 is not greater than 6 so this is not a valid binary search string pre-order valid binary search string pre-order valid binary search string pre-order sequence let's try to solve this problem so let's go back to example one again and every time we visit a node let's track it using a stack so then as soon as we see a note 10 which is valid just push it on to the stack now we have six this is also a valid node so push it onto the stack then we have three this is also valid so push it just that now we have seven in order to insert 7 we have to go back from three to six whenever we go back from three to six let's remove it from the stack so we are now going from 3 to 6 so remove 3 from the stack now to insert seven we have to go to the right of six and we also learned that once we enter the right side of a node we cannot go back to left and we don't need the root also so we don't need 6 also onto the stack so we'll remove six on the six from the stack and insert 7 to the tree as soon as we insert we have to push it to the stack now our stack has 7 and 10 then comes the node 13. insert node 13 we have to go back from 7 to 6 because 13 is greater than 7 we could have inserted it to the right of seven but if we go to the ancestor 10 13 is greater than 10 so it cannot be part of the left side of the uh root 10 and to go to the right first we have to come back from left to the root so we came back from seven to six and also we have to come back from 6 to 10 so we are moving backward two times so remove from the stack to elements now uh we don't have anything that is related to left side or to the root now insert 13 and insert it into the stack push it onto the stack now we have the node 12 which falls to the left of the root node 13. so insert the 12 and push it on to the stack then we have 15 to insert 15 we have to go back from 12 to 13. so then we have to make sure that we remove the all references related to left side and root of the subtree from the stack so remove 12 and also 13 then insert 15. now insert push 15 onto the stack as well so this is a proper binary search history pre-order sequence since we reach it to pre-order sequence since we reach it to pre-order sequence since we reach it to the end of the array without any problems now let's see how this works for the second example we have node 10 we'll push it onto the stack then we have six push it three push it seven we have to backtrack so we have to pop it from the stack and insert 7 so we remove the all references for left and root of the subtree now insert seven onto the stack now we have five we cannot insert it to the right of 7 because it is less than 6 so this is not a valid binary search tree pre-order sequence pre-order sequence pre-order sequence let's look at this approach from stack perspective what did we do we have 10 6 and 3 onto this stack uh every time we pop an element from this stack Let's uh total lowest element that can be inserted into the stack so initially low will be assigned with the minimum integer value now we have seven uh top of the stack is less than seven so just pop it then we have six which is top of the stack and less than seven so just pop it every time we pop just update the value of load to 6 and since 7 is a valid node we are pushing on to the stack then we have 13 top of the stack is less than 13 so just pop it now what is the top of the stack then 10 is also less than 13 so we'll simply pop it now the low will be 10. every time we pop just make sure that you update low because low will specify what is the lowest value that can be inserted onto the stack if a number is less than low we cannot insert it into the stack we have seen this scenario in our example 2 where the uh when we remove the 3 and 6 and inserted 7 our low will be 6 and number five cannot be inserted onto this stat because 5 is less than 6 right so coming back to this example now we have 13 on this stack then we have 12 because it's greater than low so we can insert it then we have 15 so uh now 12 which is top of this stack is less than 15 so we'll simply pop it then the top of the stack is 13 Which is less than 15 so we'll top it and the low will be updated to 13 and 5 will be inserted onto the stack we reached the end of the array so this is a valid binary search reorder sequence let's look at the same approach for example two so example 2 initially low will be minimum integer value minimum possible integer value so in the stack we inserted 10 6 and 3. now it comes for the time where we have to see if the incoming node is greater than top of the stack or not so top of the stack is less than the incoming node 7 so just pop it and check if the top of the stack is less than 7 again so pop it now we have 10 is greater than 7 so just insert 7 onto this stack last prompt element is 6 so the lowest value that can be inserted onto the stack is should be greater than 6. now we have five top of the stack is not less than five so we don't have to pop it now we have to see if we can push it or not what is the lowest value that can be pushed on to this stack it is 6 so 5 is less than 6 so it cannot be pushed on to the stat so this is not a valid pre-order sequence let's see how we can pre-order sequence let's see how we can pre-order sequence let's see how we can put this into the code this is the problem and I'll be coding in C sharp so what do we need first we need a stack to keep track of the elements that we visited so stack new stack of integer then we need a low variable to keep track of what is the lowest integer that can be pushed onto the stack so inch low equals uh it should be assigned with the minimum integer value first so n32 dot main value then we have to look through each of this items in the array so for in the I equals 0 I understand now pre-order dot length I understand now pre-order dot length I understand now pre-order dot length I plus first what did we do when we encountered so it let's take this example so first five is a valid node so we just pushed it on to the stack so stack dot push is pre-order of I pre-order of I pre-order of I then now we went to the next element which is 2 is to the left so we pushed it then one which is to the left so we pushed it but when we encounter three is greater than one but uh greater than 2 as well so we have to backtrack what did we do when we came back we popped this element and also the root because we don't need to work with the left substream or with the root load once we enter right side of the root so how do we put this into the code I'll use a while loop we have to make sure that the stack is not empty because we are popping from the stack and we cannot pop from an empty stack so stack dot count greater than zero and what is the condition uh so you know when did we push this when the so previously when I pushed this was my uh top of this stack then we have three so three is greater than one so we popped one then top of the stack is 2 so 3 is greater than 2 so we popped it so pre-order of I than 2 so we popped it so pre-order of I than 2 so we popped it so pre-order of I a 3 is the incoming node which will be given by pre-order of I and as long as given by pre-order of I and as long as given by pre-order of I and as long as this 3 is greater than top of the stack Dot what do we'll just pop it and our popped element will be the new low why are we updating this low because uh assume this case before inserting cream we are popping one and we are popping two once we pop two we cannot insert an element which is equal to 2 or less than not 2 because we have already moved to the right of the two right so any value Which is less than or equal to 2 cannot be pushed onto this binary search tree so we will be updating the low and uh in this case this is a valid binary search tree but we have seen one example where there was seven here and we were trying to insert five which cannot be inserted because this value is six so this is already removed from our consideration so any value Which is less than 6 cannot be entered and how do we verify that in a code we are maintaining the low variable for that purpose as long as we can pop the element will pop it but once we pop it we have to also consider whether that an item can be pushed onto the stack or not how do we do that the incoming item which is pre-order of I should not be less than pre-order of I should not be less than pre-order of I should not be less than or equal to low so if it is less than or equal to rho we already know that this is not a proper pre-order sequence so is not a proper pre-order sequence so is not a proper pre-order sequence so we'll simply return false now we have our Loop ready if this Loop is completed successfully without entering into the step block that means given array forms a correct pre-order given array forms a correct pre-order given array forms a correct pre-order sequence so let's run this the test cases are successful now I'll submit it the solution is accepted so let's recap what we did first as soon as we uh get an element the first element will simply push it but in order to push the next element we have to make sure that the incoming element is not greater than top if the incoming element is greater than top we'll simply pop it and whatever value is probed will be our new low that means any element which is less than the popped element or equal to the popped element cannot be pushed onto the stack because it doesn't have any place to be inserted into the binary search tree because the entire left substring and the root is removed so how do we check that condition using this if block if the incoming node is less than or equal to the lowest value possible then we'll simply return false otherwise we keep adding it to the stack once we complete or reach the end of the array we are now confident that this is the proper pre-order sequence so is the proper pre-order sequence so is the proper pre-order sequence so we'll simply return true coming to time complexity we are iterating through every element of this array so the time complexity will be bigger of N and coming to space complexity we are using a stack in the worst case this stack will have all these elements so we have a big of n space occupied I hope the solution is clear if you like the content please like share and subscribe to interview pro thank you | Verify Preorder Sequence in Binary Search Tree | verify-preorder-sequence-in-binary-search-tree | Given an array of **unique** integers `preorder`, return `true` _if it is the correct preorder traversal sequence of a binary search tree_.
**Example 1:**
**Input:** preorder = \[5,2,1,3,6\]
**Output:** true
**Example 2:**
**Input:** preorder = \[5,2,6,1,3\]
**Output:** false
**Constraints:**
* `1 <= preorder.length <= 104`
* `1 <= preorder[i] <= 104`
* All the elements of `preorder` are **unique**.
**Follow up:** Could you do it using only constant space complexity? | null | Stack,Tree,Binary Search Tree,Recursion,Monotonic Stack,Binary Tree | Medium | 144 |
48 | hey guys today we are going to solve 48 rooted image from lead code so it's a 2d Matrix question and has been asked like a lot from many multiple companies so let's get started with this one let's set the timer we'll try to solve it in 10 or less than that if not then we'll jump to the solution okay so if you are given an end to n 2D Matrix representing an image rotate the image by 90 degree clockwise okay you have to rotate the image in place which means you have to modify the input 2D Matrix directly do not allocate another 2D Matrix and do the rotation okay so basically we have to rotate the entire thing like rotate like this row to here this row here and the 5 will remain as is similarly for this guy will be rotating this one on the top this original row here okay and also symbols for the inner row and we have to do that I'll do that for the inner row also so how will he do it okay it's a trick question and so the question that comes to my mind is you know till the array B of the row and column size would be the same that question we can ask but irrespective of that I guess even if we have let's see in the Blackboard that we have um we have uh three into three to four Matrix then one two three four five six seven eight nine ten eleven two so rotation of this would be this yeah so the it won't be possible to rotate so I guess this question importantly valid because if we rotate this guy then it will only fill up this three or can we rotate it so 3 will come here 2 will come here one will come here okay yeah we want so next should have been one four five six we cannot do it so just in case if we didn't sorry if we remove this guy then we can rotate it uh so three two one four five nine ten and eight and seven so yeah let's repeat okay so we have this um so the Matrix will be always 10 into okay the question itself says that xn n into n Matrix speaker so we should have I should have uh carefully read it some that was a mistake number one okay so we are three minutes into it and I'm still trying to understand the question so okay so we understood the question how should we go about solving this like um yeah to rotate it I can we have to like swapping we have to swap this seven okay how will this swipe it like uh swapping meaning that you have to keep a temporary variable where you can you know store the value of TV and even if we are able to um like to rotate the first the outer boundary it should be recursively like it should go to the Inner Loop and then do it here as well so how to do it not given an N into a including Matrix representing an image in place do not allocate any other allocate another 2D Matrix we have to attend this tattoo okay so we need two for Loops for that and I guess I solved this question but it was very long back like two years ago and my intuitive thought is not going anywhere how can I solve this question so we are almost six minutes into this one two three is there a pattern okay I guess I have to look it up um rotate adding need for what was the question rooted image sorry hey everyone welcome back and let's write some more neat code today we're given an N by n Matrix so this time it's a square Matrix for sure representing some image and we want to rotate that image by 90 degrees clockwise and we are required to do this in place so we cannot allocate more memory we can't just make a copy of the Matrix and rotate it like that so the challenge here is definitely doing it in place you can see that they had a original Matrix like this what they did is they took the one and put it over here so 90 degrees basically what they did is took this entire first row and moved it into the rightmost column right and so they did that by moving this over here moving this 2 over here moving the three over here and so the problem is when you're moving this one over here you have to save the three temporarily right so you have to save the three or once you move this one over here you can take the three save it and move it over here and we know that this entire right column is going to actually be put in the bottom row so what is actually going on is this 9 is actually being moved over here right that's where it ended up in the result and then this 7 is being rotated over here so that's where the 7 ends up the one ends up over here the 3 ends up over here the 9 ended up over here so these four let's say have been rotated so far so now we don't have to touch them but you can see there's a little bit left in the outer layer so let's just worry about the outer layer so far we don't have to worry about the five but in the result we know that the five actually doesn't move you know you rotate it but what about this four now it's basically the same thing that we did over here right we are rotating this so basically we can think of it as being in the top left right let's the original Square we were rotating was like this now the square we're rotating is like this it's still technically a square you know if you turn your head a little bit but this is what we're doing we're rotating this so This 4 is of course going to be moved over here to this two and then and before we get rid of the two we want to save it and move it over here to the six and so in the original we have a 2 over here but we know that 2 is going to be rotated right because this is the rotation we're doing and before we get rid of the six we want to save it in a temporary variable and move it over here replacing the a but we don't want to lose the a yet because it needs to be rotated as well it's going to be rotated over here to this 4 and since we rotated the two we know there's going to be an empty spot over here for the 4 to be placed in and that's what you have over here the four the two got moved over here the six got moved over here and the eight got moved over here so this is still a rotation and lastly we just have a one by one we know that you know it can't really rotating it will just be the exact same so let me show you the general algorithm to solve this problem we're going to do this in N Square time meaning we only have to look at each cell in The Matrix once remember the dimensions are n by n and we don't need any extra memory so the memory complexity is going to be constant we're doing this in place in our given Matrix so I like to set some boundaries so we know that this is our left boundary and this is our right boundary initially because we're going to rotate the outermost layer first right the outermost square and then we're going to move inward right we're going to do the inside of the Matrix and the top boundary I'm going to place over here because that's the top remember the origin over here is zero by zero this position is three to three it goes like this and as you go down it increases and the bottom boundary is going to be down here so immediately we're going to start the rotation now how is the rotation going to go well let's start at the top left because it's the easiest right we know that this is the general rotation that's going to take place right because we're going clockwise and then we're going to do that right and we know we're going to keep doing that with every element in the top row so we did the first element in the top row then we're going to rotate the second element in the top row and how is that going to look well it's going to be pretty similar so since this was the second position in the top row we're going to move it to the second position in the last column right so in this column we're going to rotate this one to this position so the second to last position in the bottom row the main thing to notice though is that this is offset by one from the top this is offset by one to the from the right and so the position that it's moved to is also going to be offset by one from the bottom which is where the last rotation took place and then this is going to be moved over here and so as you can rotation to make right with these four elements and they actually do form a square if you tilt your head enough this is a square rotation a matrix rotation but notice how since we already rotated this one we're actually not doing four rotations for the outermost layer we're doing four minus one rotations we're doing three rotations right so even though the outermost layer was n by n we actually did n minus one rotations right so we did three rotations and let's say f after we complete the outermost layer right let's say we've completely rotated that you know we had to rotate this part and this part so once we do that then we know that we actually have an inner Matrix that we have to do so we did the outermost layer but now we have to do the inside how am I going to handle that well it can actually just be treated as a sub problem because we know no matter what it's going to be a square Matrix so all we really have to do is take our pointers and then shift all of them by one so our left pointer will be shifted here our right pointer will be shifted here our top pointer will be shifted here and our bottom pointer will be shifted here and so now the last rotation seems pretty obvious right so it's going to be one rotation it's going to include four elements and then we will have our result now one last thing I want to show you and then after that rotation has taken place we know we can update our pointers one more time but at this point what we'll notice is our left pointer is over here and our right pointer is here we know that left should always be less than right and since these pointers have crossed each other we know that we can stop the algorithm right we don't really have a matrix left to rotate one last thing I want to show you about the rotation is we know that the five the top left is going to be put in this position right the 11 so we're going to cross that out so we're going to really replace this with a five but then what happens to the original 11 that was placed here well what we can say is oh let's move the 11 to a temporary variable and now let's put the 11 over here so we're putting in 11 over here now but what happened to the 16 that was over here well we have to put that in a temporary variable a 16 and then move that 16 over here so let's replace this with a 16. but what happened with the 15 that was over here well we moved that to a temporary variable and now that temporary variable 15 is going to be placed over here so the 15 is here and we don't have to move the 5 to a temporary variable because look we already put it over here so we're needing a lot of temporary variables I can show you a slight Improvement to this which isn't required or anything but I think it makes writing the code easier so we know that this 5 is going to be rotated but let's do this let's do the rotation in reverse order so instead of removing the 5 over here first I'm going to take the 15 which we know is going to be placed over here and I'm going to put the 15 over here and I'm going to move the 5 to a temporary variable okay so are we going to move the 5 over here now nope that's not what we're going to do this in reverse order so since the 15 has already been moved let's take this 16 and move it over here so now let's replace this 15 with a 16 and now we know that we need to make a rotation from 11 to here so let's put an 11 over here and last but not least we know that the original five had to be put over here and we stored that five in a temporary variable so now let's move that 5 over here and so we did the exact same rotation but do you notice how we did it in reverse order right we went counterclockwise and the thing that the reason that was helpful is we only needed one temporary variable which will make the code a little bit easier for us but it's not actually required the overall complexity is still the same the memory and the time complexity is still the same so now let's get into the code so the first thing I'm going to do is set our left and right boundaries so left is zero right is going to be the length number of columns minus one but we know that the number of columns is the same as the number of rows so we actually don't need this and I'm gonna run our rotation while left is less than right and I'm going to go from index so let's say we're in our top row I'm going to iterate through the entire row except last element so how many rotations is that going to be that's going to be from left to right minus 1. or in other words we can say from in range right minus left so this is the number that we're going to do so if left was zero right was 3 we would do 3 minus 0 which is going to be three iterations even though we have four values in our first row so I also want to have some top and bottom pointers and these are actually going to be the same as left and right so top is going to be the same as left and bottom is going to be the same as right because we do have a square matrix it's not just a generic rectangle it's definitely a square and the first thing I want to do is save the top left Val value right because the way I showed you the rotation we only need to save one variable so it's the top left I'm going to get that from our Matrix so Matrix of top left and just like in the drawing what I'm going to do is move the bottom left into the top left so in the position of the top left I'm going to move the bottom left into that spot the next thing I'm going to do just like in our drawing I'm going to move the bottom right into the bottom left we are doing this in reverse order basically even though the rotation is clockwise the direction we're going is counterclockwise so the bottom right is going to be moved into the bottom left we also want to move the top right into the bottom right so in the bottom right position we're going to replace it with the top right and the last thing we have to do is move the top left into the top right but remember we over wrote the top left position but good thing for us we saved it in a temporary variable in the top right we're going to replace it with the top left there's just one thing we forgot to use so we forgot to use our I variable so you remember how this was the first rotation that we make right and then we move from our top left position we move one spot to the right from our top right position we move one spot down from our bottom right position we move one spot to the left and from our bottom left position we move one spot up and then we do a rotation from here right and then we're not done yet from there on we move another position to the right another position down another position to the left and another position up and then we do a rotation from these values so we can actually handle this pretty easily in our code we can use this I variable to handle that for us so we can add the I value to the left index which will shift us one position to the right and this is also the top left position so we're going to add I to this as well this is the bottom left position and we know that we can subtract I from the bottom which will shift us up by one and this is that same value so we're going to subtract an I from that as well this is the bottom right and to shift that to the left we can subtract I from the right index and this is actually this is also the bottom right so we're going to subtract I from that as well this is the top right and as we continue doing rotations we're going to add we're going to move down in this column so we're going to add I to the top index and this is the same top right so we're going to add an i to this index as well so basically as I is incremented it's going to be handling more and more rotations it's going to shift these uh cells that we want to rotate accordingly and so this will basically perform a layer of rotation so after we've completed an entire layer what are we going to do we actually need to do one last computation we need to update our pointers right because now we're going to do the sub Matrix so our right pointer can be decremented by one our left pointer can be incremented by one and that is the entire code so it's going to complete every single layer once every layer has been completed our Loop will stop and we are not required to return anything like it just as over here we're doing this in place inside of our Matrix so we don't return anything this code is good to go and as you can see it's pretty efficient about as efficient as you can get for this problem and I hope this was helpful I hope it showed you in a relatively easy way to write this okay tattoos I need to see another girl becomes the first time but you're doing a like symmetrical swap on the diet that's again interface because we do 147. so you swap this and what happens really quick uh I have this I wrote this Trace out right before just so you understand so I'm gonna grab the length of the array problems so suppose I plus this is just a standard Loop through the 2D array J is going to be set to I so pay attention to that J is going to be set to I and I'll explain that in a second so this Loops through the rows this Loops through the columns and then we do our little switch this is transpose uh Matrix so we're going to do attempt variable to the current element just a regular one more regularly looping then we're going to say okay Matrix of current element is equal to the swapped value so the row and column value will be equal to the con the column value as the row and then the row is the column and I will explain that right now and then because we lose reference to I of J because we set it we change it here we have that temp variable to save the reference whether we could do this and this is how to transpose The Matrix and let's look through the trace what this is doing is in our example for like um if we have you know one two three four five six seven eight nine then at 0 okay this is much complicated hey everyone welcome back and let's thank you okay so basically this rotate image five one nine eleven two four by what was that okay let's see five one nine eleven okay two four eight ten thirteen three six seven fourteen twelve sixteen so we have this Matrix um then okay so what he did was he um took this five and stored it in our temporary variable and then he swapped it with this guy so meet this 15. and then moved over to the uh like yeah moved over to the 16. and um made shop 16 here then moved over to 11 012 3 zero one two three okay so probably yeah then swap meet this 11th here and then whatever the value was stored in five then it was shifted here and then we move the okay so he's we also set some variable like boundaries right and sorry left and right quantity and top and bottom boundaries so what is your name that was um not bad okay what he originally let me scroll down this a bit okay original did here was like this and then we have to shift n by one you have to increment uh L with one and R minus equal to 1. so that the L comes here R comes here and then we can swap the elements so basically once we have swapped this guy the one and the top left um also shift accordingly top will come here bottom will come here sorry bottom will come here and then okay so this Top Value will be stored right okay let's look at his code what he did hey everyone what left okay so while left and right is not equal to then he is running a loop okay R minus left range R minus left meaning 3A minus 3 minus 0 okay so top left top and left is storing in top left right then bottom left it's he's transferring it to this guy then um then top right okay then one very one should go at 10 square like 13 should come back one's Place one should go at 10 space and then should concert okay from there on another position pretty easily in our so one position to the right and this is Okay so you have to implement the account right so L plus I yeah v s two n plus I then move bottom left into top left so here also L plus I will come here and then no bottom left to be here I will come bottom right into bottom left the bottom right into bottom left so right index will Plus I will happen here right yeah bottom left is this guy in one and then okay so for example top left right um this is also the top left position so we're going to add I to this as well this is bottom left so I will come here bottom right the bottom left position and we know that we can subtract I from the bottom which will shift us up by one and this is that same value so we're going to subtract an I from that as well this is the bottom right and to shift that to the minus sign we can subtract I from the right index and this is actually this is also the bottom right so we're going to subtract 5 from that as well this is the top right and as we continue doing rotations we're going to add we're going to move down in this column so we're going to add I to the top index and this is the same top right so we're going to add an i to this index as well so basically as I is incremented it's going to be handling more and more rotations it's going to shift these uh cells that we want to rotate accordingly okay so let's jump back here okay let's do it from the start why is here 15 is 15 C or 16 is here and 11 is here all right okay so we have our top here top bottom and left right okay so what we have done is we have given L is equal to 0 and R is equal to 3 right and we are looping uh through this like what he did was for I equal to 0 I is less than R minus l I plus so that's what he did there so what is the significance of this uh this guy you need to identify that okay so once we have got this set um top is equal to left and bottom is equal to right okay then what we'll do is so at any given point we are traversing anti-clockwise right traversing anti-clockwise right traversing anti-clockwise right so this uh here we are storing the top intent top left in template we are stored in top left let's remove this a bit yeah we are storing top left um what we call it there anymore tricks right okay yeah The Matrix of top n left right we are doing we are storing this top left in into the top left like um in this case five we are storing five there and then we have to swap uh the desktop left with bottom left so Matrix top left Matrix bottom left okay so top um yeah then bottom for bottom what we have to do is Matrix this will be bottom left we will tricks bottom right will shift bottom right here and zoom out a bit and then bottom left bottom right The Matrix of bottom okay so now so we have if we look at the Matrix you are able to when you were able to swap this here and then bottom swap bottom left with the bottom right so this is bottom left with bottom right and then what we have to do is stop right we have to swap it right there bottom right so your bottom right would get swapped with top right and then talk tonight would be let me scroll up a bit Matrix of top right and with the help of the stored store number here in the top left okay so we have this in place and at the end we have to do R minus equal to 1 and left minus equals to 1. once we come out of this Loop hopefully yeah okay so let's dry run this thank you so he um I'm able to understand what we did till here like this guy and then this guy was transferred here so switching um incrementing the stock top and left values so what happening is we have to increment the uh we have to shift this uh this two here and then here let me take a look yeah so this will be a new starting points for us to in order to get there what we'll do is plus I this will remain constant the top will remain concentrate throughout because for the first row the top on the left we have to increment left is plus I and R minus L why we are writing that R minus L because it shouldn't go to 3 The Edge should not reach 3 that's why it's less than that R minus L okay I understood that now so R plus I left plus size there so we will get uh will be shifting till nine so we'll first get 5 then on the second Loop we'll get one and on the last Loop we'll get ninth um okay so we got the first part of the puzzle we are able to get all the top values n equal to store them in the temporary variable then what we'll do is we have a okay if you have a okay we have new text top left we are storing the bottom left okay so in this case when we are storing this guy um so next position would be this right this 13 will be going to add this place so we have to keep left edges like the top as is and put I here so that we jump to the position where we want to point and the bottom so we get the uh here we got the uh got the topmost element where we want to shift set this guy we have to Simply bring it here right and the bottom left so bottom repeat decrementing like uh bottom is three and we have to go to two so we have to add minus I here okay so that's how it will go up one step and then bottom left now that once we have shifted this will be empty so we have to print this CL right minus I know minus I and then what we have to check in this place we have to shift this bottom right now bottom right to this place right so once we've got this where we need to swap the new element we have to decrement this by I guess right is here you have to bring it here so once we do that we have to come at this spot and bring this guy here because that part is now empty so bottom minus I okay so Matrix of top right now we are um We have dealt with this guy is empty now this guy is empty and we want to bring this guy here okay so that is top right um top right so top right would be R would be staying the same and the top will be decrementing so we decrement top I here and then we simply move because this is empty now we'll move this minus I here like okay so basically that's what is happening and by the end of the loop we will simply minus this guy okay so yeah now we can code this up this took a lot of time like uh this stuff more than one hour like almost an hour but I understood like how what is the flow of this algorithm select first what we have to do is take left and right so L is equal to Matrix dot length and left R is equal to also the same thing both are same left and right um yeah why okay exercises sorry my guy so left will be pointing at 0 or 50 pointing at the last element Matrix dot length minus one so while left is less than R we have to run this Loop type so for let I equal to 0 so I doesn't go over like left shouldn't or left with r the last element like this guy left should only travel still two so in order to avoid that we are doing R minus l and I plus so yeah save the top left element so let's see um let is equal to Matrix of the top and select top and bottom equals to left and right values okay yeah gotcha uh and then what we have to do is let's call it the fourth top and bottom select we are not writing we are keeping the code in um be sorry L left some left yeah we'll get this thing done first so we have to so this Matrix top left swap the um top left with bottom left yeah so Matrix of top left that's what we have let me swap to it bottom left swap bottom left so we uh we have placed bottom left in top left so bottom left is now empty so bottom left let's have bottom left effect bottom right okay Matrix top left equals to sorry bottom yeah I dealt with bottom so bottom is empty right so we metrics of bottom right slap bottom right is now empty so we'll swap it with top uh because we have to login reverse this stop right so Matrix of B are let's take the sky because that's what we placed it here so this is empty so not empty but we have to subtract the element but yeah it takes off top right and now top right is empty sweat top right with the top left temp will be able some Matrix of top right equal to 10 top left yeah and at the end we have to do R minus equals to 1 L plus equals to 1. and we don't have to return anything for this as we have to do it in place and we have done it in place so the only thing we have to do now is to take care of the incrementing part and the commenting part so here on the top left we are dealing with the first row so we have to take this uh take this guy to 0 let's talk in less respect so we start from PI because L will be 0 at this point so we'll start with L it will be pointing here now we have to go 1 and 9 so I will help us I will be starting at 0 and in the next iteration I will be 1 so plus I so that's how we'll get to the next element that will go we'll get five one nine now we have to also replicate the same thing because we are transferring this guy to top left so ultimately that position will be empty for the swap so we'll copy like replicate this here same thing and The Matrix also slope Matrix of B and L so bottom left will remain the same so once we have transferred this then if we are dealing with this once we've transferred this to this so 15 will take this place then in the next iteration uh we have to transfer this to 10 we store this one a one here and then 13 one in temporary variable and this 13 so we are coming up in this case so left will remain as is we don't have to increment the value of left because uh we are dealing with the outer loop so bottom will decrement by I so that is that part is empty now so the empty portion we have to fill it with the next value which will be bottom right so we move this here but um and Angela now we have to move this here so initially the right was here so we have to decrement the right minus I so now the right is empty so you have to replace it with the top value so this gets replaced with 16 and in the next iteration this kit gets replaced with ah this guy r10 so we are decrementing top always in this case and then as top is empty you can replace it with the top left element so on hopefully this is okay RS 100 point okay so p r minus I cannot read property is it going out of bound I don't think so R minus l should be minus 1 or how is it like it's still coming out to be like this I don't think so it should be minus one okay if I compare this code um birthday oh yeah this guy that's insanely created this list Okay so we let me compare my code to this okay so I'm doing the stop left and then top left plus I then left plus I with P minus I then P minus I to L then R minus I oh yeah here it will be plus sorry my right what will be plus we are incrementing it not decrementing sorry so I found the mistake what I did was I said we are going down so I thought it's decrementing but it's implementing it so top will be incremented so if I run this now it should work of n Square it's often Square this time complexity is over n Square it's pretty interesting this one yeah so it took me more than one hour hopefully if I encounter such problem next time onwards I will be able to do it so | Rotate Image | rotate-image | You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000` | null | Array,Math,Matrix | Medium | 2015 |
1,679 | Jhal Ajay Ko Hello Friends Welcome to my YouTube Channel Tier-3 Today Khayal Mintu Solid Problem Tier-3 Today Khayal Mintu Solid Problem Tier-3 Today Khayal Mintu Solid Problem Se Zauq Ne Smack Number for Example You are One and Jerry in Interior's In One Operation You Can Take Two Numbers from Tere Ko Sham Ko Remove from the Return of you can perform something like this 1234 Okay, first of all we will do the joint, now it is sorted then it is okay then told us that if we should understand the maximum then when should the element be how much should be five then we can apply two point approach in this Let's keep I can see here we check what darkness from IPL 8i A Plus Edit is needed if is equal to that scientist we got a leg you will Laxman in your purse increment I will jail We will decrement it, okay criminal, this is the same approach and if it is laddu, if it is airtel element i plus airtel element, if it is loot, Aniket, then there are so many other things like the rally that took place and the sewer line, both of them are small, so we know that The index of i is small i.e. if the small i.e. if the small i.e. if the person is hunted in increasing order then the value of i will be increased so this yogi is small and increasing the indiscriminate cutting that i is needed so i will increment i is empty and its in this If it is reverse then I will delete J. This question is exactly the same. S2 Even if you did tourism question and two probably this is exactly the same question. So if we fold it then simply what do we do first of all? I said, let's fold it, hey, at this time, short notes are sent in the to-do list, I send the notes are sent in the to-do list, I send the notes are sent in the to-do list, I send the i20 request, not the length - i20 request, not the length - i20 request, not the length - now what do we do, we check the file till it comes, but whatever it is, what do we do with this? Alarm set i-slam set Jain has been i-slam set Jain has been found on our business according to the Sanskrit question of date from drought and because once we get it, those elements have now been used, so now what can we do with Champcash? Let's increment the G and delete the G. It was found here that NCF is Hello friends Shiv. If the name is beating candy crush, the name is Ra G A but what does it mean now, what is the value going, how is it going small, then what does the value mean? There is a need to increase my oath, how should Assam grow because there is a shot in the border, then I will have to be increased and if it is contrary to this, cricket will have to be deleted, na a return to the return dancer that here we make it under control, now all these requests are made in that. Geo, we can do this question in Off N also, leave it at this, let's color it again, here it is on the test case, one Shami has been looted, okay, tomorrow in this later video, please comment, share and subscribe our channel, thank you. | Max Number of K-Sum Pairs | shortest-subarray-to-be-removed-to-make-array-sorted | You are given an integer array `nums` and an integer `k`.
In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array.
Return _the maximum number of operations you can perform on the array_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], k = 5
**Output:** 2
**Explanation:** Starting with nums = \[1,2,3,4\]:
- Remove numbers 1 and 4, then nums = \[2,3\]
- Remove numbers 2 and 3, then nums = \[\]
There are no more pairs that sum up to 5, hence a total of 2 operations.
**Example 2:**
**Input:** nums = \[3,1,3,4,3\], k = 6
**Output:** 1
**Explanation:** Starting with nums = \[3,1,3,4,3\]:
- Remove the first two 3's, then nums = \[1,4,3\]
There are no more pairs that sum up to 6, hence a total of 1 operation.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109`
* `1 <= k <= 109` | The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix. | Array,Two Pointers,Binary Search,Stack,Monotonic Stack | Medium | null |
108 | hey everybody this is larry this is me going over day 26 of july's leco daily challenge hit the like button and subscribe and join me on discord let me know what you think about today's film so i'm in sunny san diego today and for this week i suppose uh so yes i'm excited uh hopefully the sound is quieter because i'm not around people as much um but yeah let me know what you think about these songs sound quality hopefully it's good um today's problem is gonna be convert sorted away to binary search tree so i usually solve this live um so if it's a little bit slow fast forward do whatever you need to do to kind of yeah do whatever you need to do to you know i'll get to where you need to go okay so yeah sorry this given away converted to a height balanced binary search tree okay is that we have depth of the sub trevor we know okay this isn't um so it's in there strictly increasing order i mean that part's not that i don't know how to think about wanting to do this because this is very silly right and in that this is literally a textbook problem uh and by that i mean literally a problem that you may see in a textbook and just doing it and it doesn't really have uh yeah and you may learn this in algo um algorithms class or something like that in college but beyond that i don't know how would i um i think the biggest thing is just to do it um recursively um and recursively you can think about and maybe this is a good practice for to write and conquer now that i think about a little bit because then now what are you trying to do well you basically given a list of nums and you're going to you know just put the middle in the root and then kind of just recursively construct with the sublist right so then the question is do you have to be careful and in that you can't imagine a case where well i'm trying to think uh the tricky case is that you know if you have some degenerate case where you keep on putting everything to the left or putting everything to the right um then things are going to be unbalanced at some point but we can probably play around with that and fix that later uh let's just get the core idea correct and then we'll play around with the edge cases i think there are there's some techniques that i know off my head that can kind of either probabilistically fix it or just you know i think there are ways to kind of enforce it but um and you can even maybe do some rebalancing but i think you know let's not get ahead of ourselves let's see if this is a problem before we get started so anyway so let's do that let's go um let's call it construct and then we just take a node and then the index of left and right say and here is that what i want to do no that's not what i want to do just construct left to right and then i can do something like okay if left is equal to right then we have one node left so then we just return a new node a neutrino a value of num sub left and because num sub left is equal to numbers of right and there's nothing to left or right so that should be good according to these definitions and otherwise then we just said middle is equal to left plus right divided by two we know that tree node or we uh current is a tree node of num sub middle and then now we want left right so that's constructed left is going to left middle but in something like this right um so let's actually just to make this we can add more if statements but to make this slightly easier if enough is greater than right then we just return none so that means that if this is left is greater than middle minus one then we turn nut and here we can do current dot left is equal to construct that and current that right is equal to construct below plus one right um inclusive right and i think that should be good enough uh return coin at the end and then maybe just return construct of zero and n minus 1 where n is equal to the length of nums i think that's good enough to start off we'll see if this is good see if this is gucci this looks i don't know if this is actually let me take a look to see if that's right um so this is because now we have to draw it out a little bit so i wish there's like i feel like there's an interface somewhere where they show you um one three and three one is this the right answer i don't actually even know because they say that this is one three but i think this is technically one note three so i think they give us the wrong thing uh if i'm correct about this format and then okay so zero negative ten on the left 5 on the right and okay let's just give it a submit i think this is right on the input hopefully this is good like i said the only thing i worry about is that if it becomes too unbalanced because this has a sort of a so this does have a left bias and why what i mean by that is that it can um it rounds down right so you can in theory imagine a case where it gets too unbalanced but i cannot prove it's just that my skepticism right um and now we proved by ac kind of uh it's not exhaustive and we'll have to figure it out i think the only thing that you can tell is that um like the numbers itself don't matter it's about length and i guess if it's good for say one two eight digits or eight elements then i'm i'll probably satisfactory um but yeah that's what i would test but or some powers of two are close to positive two so either powers of two or powers of two minus one or something like that and that would maybe generate these kind of imbalances um okay am i gucci yeah so this is going to take linear time humidor is very awkwardly constructed and it may you know you may intuitively think it is and again or maybe login or something like that but actually if you look at it just get constructed if we well so looking backwards we do construct a tree note for each number on this so because of that this is going to be o of n linear time because we only construct n3 nodes and we don't really fall away i mean minor extra work but that's gonna be constant amount extra work so yeah so each element get so you can think about this as i mean it breaks to be in the pieces but it brings to n number of pieces where n is the number of numbers so it's going to be linear time and it's going to be linear space both in the number of tree nodes and just a recursive base stack type thing so even though you could also say that this is all h but h is going to be dominated by n at some point um for some inputs um but yeah so linear time linear space that's all i have for today happy monday hope y'all have a great rest of the week i'll see you later and yeah stay good stay cool stay healthy and take a mental health i'll see you later bye | 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 |
202 | all right welcome back to day two everyone this is happy number so in this question we are given an input 19 and we want to split up its digits and then square them so 1 squared plus 9 squared 82 and then what we want to see is if we continue doing this if we end up hitting the number 1 so if we hit number 1 it'll just loop endlessly at 1 because 1 squared equals 1 or if it's unhappy it's going to loop endlessly in a cycle that doesn't include 1 so in both cases there's a cycle one of them the cycle is 1 and the other one doesn't have one ok so to do this and show you how we can split up integer into its digits and then the second thing that we'll do is how to detect a cycle and then here we can go over briefly if we use a hash set versus something like Floyd's cycle detection algorithm all right this get started so first we need to figure out how to split up this integer to its digits so for us it's pretty easy we see that there's a 1 in 9 so you know we're done but how do we tell a computer you know 19 consists of the first digit is 1 in the second digit is 9 so to do that we're going to use an operator called the modulo so the modulo if you haven't seen it before it returns the remainder of a division so for example if we had something like you know 19 what happens if we modulo it by 10 so well you can see as we have 10 and then we have 19 and then it fits into it once we get 9 left so here this is going to be our modulo now the cool thing that we can do to extract the digit as you can see that right here this is already the first digit so the pattern we're going to use is we're going to have our number and then we're going to modulo it by 10 and then we're going to module it by 10 and now we're also going to divide it by 10 and let's see what happens when we do this so let's choose bigger number let's say 681 modulo by 10 is going to give us that one in the last because we have 680 divisible by 10 and then only divided by time we get 60 8.1 now we're divided by time we get 60 8.1 now we're divided by time we get 60 8.1 now we're storing it into an integer so that means that all these decimals they get truncated they we can't store them so they just becomes 68 now if we feed this in into our next run we have 68 here modulo by 10 we have 60 so the remainder is 8 and then when we divide again by 10 we're gonna get 6.8 and again this gets we're gonna get 6.8 and again this gets we're gonna get 6.8 and again this gets truncated so we actually just get left with 6 and then we repeat again we have 6 and then here um we can't fit any tons so 6 by itself is the remainder and then when we divide by 10 we get 0.6 and when we divide by 10 we get 0.6 and when we divide by 10 we get 0.6 and again currently so we get 0 then we'll hit 0 here we've noticed that by this time we've actually extracted every digit we're attracted 1 8 and 6 and the reverse order but it is the digits of this number so let's go ahead and code this up we will create a new function let's call it next and we have some sort of output and while and that's not equal to 0 what we'll do is we have our digit as equal to whatever n is modulo by 10 and then our sum is going to increased by the square of that digit and then finally our digit we just divided by time to get the next and here we can return her some so if we want to check that this works we can do something really quickly say team I plus that's just printing like the first fifteen so let's do this and see what we get all right so nineteen is the happy case Oh missing return statement rate so let's return something dummy here for now return code whose time limit exceeded did I go wrong oh sorry about that this should be a we divide so we feed in and by divided by ten is divided by n okay nice so this is what we saw above and then we can see once we hit one we kind of keep leaping into one and let's see another example a not happy number so I run it on sixty two and now we see that with sixty two we see a loop so let's see one forty five is the same surround here so we have from 16 to 4 and then we cycle again back to sixteen 3750 okay so now our goal becomes how do we detect this cycle and then when we detect it all we have to do is when we're in that cycle is it equal to what if it is then it's a happy number if it's not if it's any of these other you know 13:42 then it's not a happy you know 13:42 then it's not a happy you know 13:42 then it's not a happy number so there's two ways that we can do this or there's more than two ways but the two ways that I want to talk about one is we could use a hash set so with the hash set what we do is we keep track of every number that we've seen so far so we've seen 62 for D 16 all blah and then when we get down here to 16 we would see that hey we've seen 16 before so therefore there must be a cycle and then we'd exit now the problem with a hash set is that we need to keep track of all the numbers that we've seen leading up to the start of the cycle so an alternative algorithm we could use as we could borrow the ideas of Floyd's cycle detection algorithm so what's Floyd let's see here what's Floyd what we avenge what we have is a turtle and a hare or rabbit and so what happens is that on every step the turtle only moves by 1 while the hair moves by 2 and then what's going to happen is the hair moves by 2 the turtle moves by 1 the hair moves by 2 we check turtle moves by one hair moves by two we check turtle moves by one and hair moves by 2 we check turtle moves by one and lastly hair moves by 2 recheck there is a point where they both the hair basically catches up to the turtle because it's looping around and then we can see if this number is equal to 1 or not in the happy case when we hit 1 is just going to keep looping around what so they'll catch up pretty fast so we'll do a quick proof at the end of this video showing that you know the turtle the hair will always catch up to the turtle within one loop but for now that's assuming that this works and we'll code it up okay so what we want to do here is we want to introduce a turtle and I hear the hair can take the next one and while this turtle it's not equal to the hair we're going to move the turtle next and the hair will move twice and then what we returned here is whether or not our turtle is equal to one not a question mark okay so that should give us what we want and we'll try running it this should be false okay and let's try submitting it and it's accepted so it works but when I first heard about Lloyd cycle detection I remember in the back of my mind I was like okay but is there ever a case where the hair just happens to skip over the turtle every time and they just in this loop endlessly just always skips over and they never meet up so we can actually prove that this case doesn't happen so the way we'll do that is let's give some labels let's say this is X 0 X 1 and blah we have 2 3 4 5 so here X 6 X 7 so you can see with what when they're going through and we have this relationship that X at a is equal to X at a plus however many loops that we've gone across times the length of the loop so in this case the length of the loop six so that's how we get X 0 is equal to X 6 X 1 X 7 this will be 2 times 6 is 12 plus 1 is 13 so we have this relationship and what we want to prove is you know when we get into when the turtle starts the loop the hair is already gone around multiple times maybe and it's like somewhere here at some offset and we will call this offset here Y so Y is the offset of the hair so in this case in this example we have 1 2 3 so Y is equal to 3 what's the offset so we want to say well when the turtle starts in the loop so that's let's say mu is the start of the loop after it takes you know I turns i steps does it equal to the hair which also began into the loop and has circled around for a couple of times now plus that's at some random offset here and the hair every time it moves twice so here we do plus 2 I do these two equation can we get these two to reconcile somehow so in this case a is equal to u plus I so what we really want to know is u plus I plus KL is equal to MU plus to me K 2 L plus why plus 2i you want to see if this happens so that's cancelled out some variables I hear there's a 2 here we end up getting K L is equal to K 2 L plus y plus I we clean this up a bit rid of that let's see we have that L K minus K 2 minus y is equal to I so that's let's dig into this equation a little bit so we have Y which is fixed it's whatever the offset of Y is when the turtle finally starts the beginning of the cycle k2 is also fixed its whatever how many times the air has circled around before the turtle finally arrived L is also fixed it's the length of the loop but we can control K which is from this equation like which one do we want them to equal so we can set K to be equal to k2 plus 1 meaning that we want to meet them within one loop so if we do that we get the equation I'll write it up here L minus y equals hi so that's try it out here so in this case we have L is 6 minus 3 equals 3 what this tells us is that within three moves of the turtle they're going to end up at the same node so let's see this play out so the turtle will move once twice we check nothing and then one two check nothing and this is a third one Chuck they're at the same note so it guarantees us that in I steps they will meet now what we notice about this equation is that why it's always going to be you know a number between zero and now because it's the offset between the start of the loop so that means this high will also be a number between zero and L so we basically proven that when the turtle hits the start of the loop you know and the hair is wherever this hair is whatever offset Y is within eye steps these two will definitely meet up again so that's why the floyd cycle detection works okay that's the end of the video and i'll see you guys on day three | Happy Number | happy-number | Write an algorithm to determine if a number `n` is happy.
A **happy number** is a number defined by the following process:
* Starting with any positive integer, replace the number by the sum of the squares of its digits.
* Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
* Those numbers for which this process **ends in 1** are happy.
Return `true` _if_ `n` _is a happy number, and_ `false` _if not_.
**Example 1:**
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
**Example 2:**
**Input:** n = 2
**Output:** false
**Constraints:**
* `1 <= n <= 231 - 1` | null | Hash Table,Math,Two Pointers | Easy | 141,258,263,2076 |
300 | everyone welcome back let's solve another problem today longest increasing subsequence and this is another tricky dynamic programming problem and i'm going to show you how to go from the recursive solution to the dynamic programming solution so we're given an array of numbers and we just want to return the length of the longest increasing subsequence and if you don't know what a subsequence is it's basically like let's say this is our input array we're basically taking a subarray but that subarray does not have to be contiguous so like we have from here so uh subsequence is three six two seven basically we took this subarray and we removed one two from it and we removed a one from it and now it's three six two seven but you notice about this subsequence it's not an increasing order right we have six and then we have two that's not increasing order so this is not a increasing subsequence so in this example we're given about nine elements and we want the longest increasing subsequence which we see is this and so how did we get that subsequence well you go from 2 all the way to 101 but you notice that unfortunately this is not an increasing order we have a 5 and then we get a 3 right after so we actually have two choices if we remove the three we have an increasing subsequence if we remove the five we also have an increasing subsequence but we just care about the length which in this case is four so we return four so the first idea you might have is brute force using depth first search so let's say that this is our input array so we have six elements for if we wanna know the brute force meaning we want to generate every possible subsequence we have a choice for each value right so for the first 0 we have a choice are we going to include this 0 in our subsequence or are we not going to include it in our subsequence so in reality for each value we have two choices now when we get to the next value we also have a choice are we including it or not so again we have two choices if we want to generate every possible subsequence so we do that for every single value and then we see that there are actually 2 to the power of n possible subsequences where n is the number of values given in our input array so already you can see the time complexity is not going to be great but can we take this brute force approach and then somehow modify it to get a better solution like n squared so let's look at another example and this time we're going to do depth first search with caching and we're going to see how that improves our time complexity so we have an example of four elements so it's kind of obvious that this is our longest increasing subsequence so the result is going to be three elements but how can we do this with an algorithm that's efficient well let's start out with the brute force approach let's check all subsequences starting at index 0 and then repeat that starting at index one starting at index two and starting at index three right so these are the indices so we take one decision to start at index zero we take one decision to start at index two and one decision to start at index three so in these cases these are going to be the subsequences we have so far so we know index zero has value 1 index 1 has value 2 index 2 has value 4 index 3 has value 3. so now let's go along the first path so index 0 so we know if we start at index zero we have three values that come after it so we can try all three of these possible decisions so we can go along index one index two and index three and we see that all three are possibly valid because all three of these values are greater than one so we can continue these subsequences so we know index one has value two index two has value four so we can add a four index three has value three so we can add a three to our subsequence that originally was just one so now we took index zero and index one so for here we only have two indices that come after these two values so let's continue our decisions we see that both four and three are greater than the last value in our subsequence which is two so we can choose both of these decisions so if we take index 2 then we can add a 4 to our subsequence if we take index 3 we can add a 3 to our subsequence so now let's continue here we have three values so far in our subsequence and there's one index that comes after two index three it has a value three so can we add a three to our subsequence we'll get one two four and then 3 but this 3 is not greater than the last value in our subsequence so we technically cannot make this decision so we cannot continue to increase the subsequence anymore so we can mark this as reaching its limit we cannot continue it anymore what about this one well it stopped at index three which was over here so are there any elements that come after it now no there's not any elements so this subsequence has also reached its limit so we cannot increase it anymore but so now let's focus on this caching part what kind of repeated work have we eliminated well let's just do this out of order instead of doing these first let me show you what happens if we try to extend the three now we try to get another element right we started at index three but we know that no values come after index three so this one cannot be continued but what do we know about index three if we start at index three and we want the longest increasing subsequence we just get a single three so that tells us that lis starting at index three is one we don't need to repeat this work and isn't that what we just learned over here even though this subsequence is length 3 we are talking about starting at the 3 and we noticed we could add a 3 to it right this was the element that we added but as soon as we added that three we could not add we could not increase this subsequence anymore right that's what this x tells us we were only able to add one element if we start at index three and that's exactly what this two told us as well if we start at index two we can add a four but this three that comes after it cannot be added we cannot include that and there aren't any more elements to add so as soon as we finish this and we found this x meaning we could not go any lower we knew that the longest increasing subsequence starting at index two is also one so therefore if we start at index two we cannot go any lower we cannot continue this and we don't even have to attempt to do that and what about this branch so if we chose if we started at index one we would start with the subsequence of two right that's what this tells us and so now i'm gonna repeat i'm gonna do some more stuff right i'm gonna choose the next indices two and three but wait a minute do i actually have to do that because look over here we started with index one and we already did that so when we started with index one we saw we had two choices a two or a three index right we could choose this or we could choose that we saw both of them ended right we could not continue either of them so if you want the longest increasing subsequence that starts at index 1 over here no matter what you choose the subsequence is gonna be length two either way right because if we start with a two then we can add a four or we can add a three but we cannot add both of them so we can mark the longest increasing subsequence starting at index one to be length two so we actually don't even have to go down this path once we already go down here because it's just gonna be repeated work and we also see for these two trees that we have not finished yet once we add a four the longest increasing subsequence at index two which is where four is at is going to be 1 so we cannot continue this anymore similarly once we add a 3 we know no values come after it the longest increasing substituent starting at index 3 is just 1 we cannot increase this anymore so when we finally in our depth first search get back to the root we're gonna see that the longest path is one of these right either that or of course you could go down this direction but either way the longest increasing subsequence starting at index zero is going to be three and so when you look at these four right because these are our subsequences these are the longest subsequences starting at each index the greatest one is three and so therefore the result is three but now if you actually wanna do the dynamic programming solution you might notice how we're doing this recursively we're kind of starting at the last index right three and then working our way up backwards to zero so then going back here so can we use that to do dynamic programming so now let me show you the dynamic programming solution and it's actually easier than you might think so we're going to work we're going to start at the last index 3 and then work our way backward so we know this is kind of the base case right no values come after it so the longest increasing subsequence we could make from here is just going to be length one anyway so we can say the lis starting at index three is just one that's the max length now how do we get the longest increasing subsequence starting at index two which is just one shifted to the left well one possibility is just four by itself right so that's one possibility it could just be one or it could be one plus the longest increasing subsequence starting at position three and what this means is if we take both of these right because lis of three is just one right so three by itself but we're only allowed to do this if the value nums at index 2 which we know is 4 is less than nums at index 3 which we know is 3. is this true this is not true so we are not allowed to do this so normally we would take the max of these two values but we know that the condition to take the max of this does not satisfy so we only have one choice one so the lis of this is going to be one i'll put it over here like in the corner so again we're gonna work our way backwards so let's get the longest increasing subsequence one index back at index one so we're going to do the similar thing that we just did so we know we could take a subsequence two by itself right that's one choice one is a choice length one we also have a choice one plus the longest increasing subsequence starting at four and we're allowed to do this because two is less than four so it is increasing the subsequence is increasing so another choice is one plus lis of two and another choice is l i s starting at index three because two is less than three right two is less than three so the subsequence is in increasing order so one plus l i s of three now we know that this is two and this is two so it doesn't really matter which one we do the lis of one is going to be equal to two regardless so now we want the longest increasing subsequence starting at index zero and we're just going to repeat what we just did so we could take one by itself which is just one or we could take one add it with the longest increasing subsequence starting at two or this longest increasing substitution starting at this index or this index so we know we're going to get 1 plus 1 from here and we're going to get 1 plus 2 from here and we're allowed to do all of these because you notice 2 is greater than 1 4 is greater than 1 and 3 is greater than 1 so they're an increase so they are an increasing order so then we know that the longest increasing subsequence of this is going to be equal to 3 which is what we want so this is a much better solution the dynamic programming solution is much better than brute force because the time complexity is o of n squared but why is it o of n squared well you see we're working backwards we start at three and then we check every position afterwards which is not too bad right so then we iterate through basically every value here when we start at four we have to look at every value that comes after it there's only one value that's good for us so we iterate through these two values when we start at two we have to check these subsequences starting at these two values so then we have to end up iterating through two and every value that comes after and we do the same thing for one so we iterate through one and every value that comes after so you can tell by looking at this pattern is similar to an n squared pattern so now let's finally write the code so we know we're going to do this dynamic programming style so let's have a cache or a list it's initially going to be set to 1 every value is going to be set to 1 it's going to be the length of the input array that we're given so every longest increasing subsequence starting at every value or every index is initially just set to one we're going to try to find what the max is so we want to iterate through every index in the range of our input array and we want to do it in reverse order so that's what i'm going to do in python it if you're not familiar with python this might look a little weird but basically what i'm doing is starting at the last index and then going all the way to zero and just like i showed in the example we're going to start at index i like this could be i and then we want to iterate through every subsequence that came after it so i'm going to have another nested loop for j in range so starting at i plus 1 and then going to the end of the input array and before we can update lis we want to know is the value at i actually less than the value at j because j comes after it if we want this to be an increasing subsequence this condition has to be true and only then are we allowed to update the longest increasing subsequence at index i and we can set it to the max of itself and or the max of 1 plus the lis starting at j because we know for sure j is going to be in increasing order with i and literally that is it we made sure to evaluate that it's an increasing order we did it backwards we made sure to cache the repeated work what do we have left to do well we want to return what the max is how can we do that well in python you can just take the max of a list so whatever uh the long whatever the greatest value is in here is going to be returned and they're actually so this is o of n squared and there actually is a better solution big o of n log n but i really doubt your interviewer is going to expect you to get this on your own without a hint if they do i would personally just walk out of the room but i hope this was helpful if you enjoyed please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon | Longest Increasing Subsequence | longest-increasing-subsequence | Given an integer array `nums`, return _the length of the longest **strictly increasing**_ _**subsequence**_.
**Example 1:**
**Input:** nums = \[10,9,2,5,3,7,101,18\]
**Output:** 4
**Explanation:** The longest increasing subsequence is \[2,3,7,101\], therefore the length is 4.
**Example 2:**
**Input:** nums = \[0,1,0,3,2,3\]
**Output:** 4
**Example 3:**
**Input:** nums = \[7,7,7,7,7,7,7\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 2500`
* `-104 <= nums[i] <= 104`
**Follow up:** Can you come up with an algorithm that runs in `O(n log(n))` time complexity? | null | Array,Binary Search,Dynamic Programming | Medium | 334,354,646,673,712,1766,2096,2234 |
279 | hi everyone good morning today we are going to discuss one dynamic programming questions like perfect square so this is the problem that given integer n return the least number of perfect square the number that sum to n so if you consider 12 like it's like 2 square plus 2 the minimum is 3 so it would be also like if you consider this problem it could be like this way like find mini number perfect square to add such than sum equals to zero n equals to six it could be like one square and it could be like this way so minimum is three so first approach is greedy approach like and n minus state is per factor square and then we'll just add one then example n equal to 6 minus 2 square goes to 2 minus 1 square again 1 minus 1 square equal to 0 and then n equals to 10 minus 3 square equal to 1 minus 1 square equals to 0 so here this is for this n is equal to 10 the 2 is the answer like this one but this 3d approach will not work for every case suppose n equals to 12 so if you approach 3d approach 12 minus 3 square then 3 minus 1 square 2 minus 1 square 1 minus 1 square equals to 0 so in this way answer is 4 but the real answer is 2 square plus 2 square and s equals to 3 so it's a kind of uh it's not greedy approach is not working so we can see that we have uh some overlapping sub problem we have optimal substructure how suppose firstly we consider 12 so 12 is like 1 square 2 square plus 3 square okay this is 12 okay and for 11 we can see that 1 square 2 square 3 square and for 8 1 square 2 square we cannot go for three square okay we have to traverse this until it becomes one for each of the sub node okay and here we have to take the minimum out of three eight eleven whichever the minimum like length of this node we will return that one which one is the minimum length of this maybe this branch length of this branch which but the minimum we will return that so dp 12 equals to 1 plus mean dp 11 ppa pp3 and x could be 1 2 3 so dp n equals to 1 plus t p n minus x square and for all such that x square less than equals to n dp of 0 equals to 0 no per factor square is required to make sum equals to 0 now here if you see dp 0 visualize is 0 and i will iterate till i less than was 12 and dp of i equals to y because we are assuming adding one square i times so we are assuming that maybe the one square uh we have to uh by adding one square that if you consider this case 1 square this case so we are adding it i times okay and here dp of i equal to mean dp of i 1 plus dp i minus x square time complexity this is this small part is root n and this whole is n so n root n express complexity we have used one space so n and here is the code of this if you run this dbfi we have slides a plus one and similar thing i have written it here if you run this code now it works now | 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 |
71 | hey everyone welcome to Tech wide in this video we are going to solve problem number 71 simplified path first we will see the explanation of the problem statement then the logic on the code now let's dive into the solution so here I have taken an example which covers all the conditions for the problem that is required so we need to convert this string path to a canonical path so the canonical path has some conditions so that should not be double slash between two directories here A and B are directories and this should be separated with only one slash right and whenever I detect two dots which means I need to go to the Parent Directory I need to ignore B and directly jump to the previous directory of B right that is a in this case so we are going to use pack to solve this problem so and we will see how we are going to do this so initially I will split this path string based on the slashes right and if I split it I will be getting empty space for a single slash and I will be getting a and when I have continuous slashes I will still get a single space right then I will get B then again I will be getting empty space then I will get two dots then again empty space then C and again empty space right so whenever I have consecutive slashes I will be getting only single space right when I split based on slash so we will use split function to do this so here I have taken this splitted path right this will be in a list then I'm going to use a stack now so initially I will check whether it is a empty stack or not yes it is an empty stack right then I will pick the first element so initially I will pick the first element that is going to be empty string right first I will check if it is a space or it is a single Dot or it is a double dot with an empty stack right so when I have a something in stack and if it is a double dot then there is a separating we will do first we will see for the empty space so whenever I deduct an empty stack and one of these Three Special strings that is empty space or a DOT or a double dot right and simultaneously the stack should be empty if that is the case I will just ignore I will not append anything right then I will pick a now again I will check and that is something in stack or not no it is not right it is a then I need to check whether it is one of these three special characters and it is an empty stack no it is not one of these characters so I will just directly append a right again we have space then I need to check whether it is a double dot or not right no it is not double dot and it since it is also a space I will not do anything I will pick the next one now it is B again I need to check whether my stack is non-empty and it is a double dot is non-empty and it is a double dot is non-empty and it is a double dot right so since it is not a double dot and it is not one of these three things I will just directly append the character B again we have space I will just ignore then I will have double dot now so the double dot means I need to go to the Parent Directory I need to ignore the previous directory and I need to go to the Parent Directory right now I will check whether my stack is empty or not if it is not empty and it is also a double dot which means we need to go to the Parent Directory so I will pop the previous directory and I will keep the Parent Directory a right so basically we had a and b so a is the parent directory of B so double dot means I need to go to the Parent Directory from B and I will ignore B right now I will again going to take the next element from the list that is empty space I will just ignore then I will pick C since this is not any special string I will just append that directly to my stack then again I will be getting empty space I will ignore then now I need to join these directories in a path format canonical path format so I will join them based on the format that is I will put a slash in front of the directory a and I will separate these two directories with Slash again and I will not put a slash at the end of the path that is end of the last directory I should not put a slash in that way I will join at the end and I will return this as my answer right that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially I will be having an empty stack then I will split the path right I will split the path based on slash right then I will iterate through the path I will pick each and every element from the path right now I will check whether I have an non empty stack and the element is equal to a double dot right if this condition is true I will pop the last element from the stack then I need to check whether the current element is not equal to any special strings that is it should not be a DOT and it should not be a space and also it should not be a double dot right if my stack is not empty and if it is a double dot I will pop the last element so if this condition is true which means if I have a character I will append that to my stack right finally I will join based on the given format that is Slash then I will put a slash between directories then I just joined the stack right that's all the code is now we will run the code as you guys see it's pretty much efficient so the time complexity will be order of N and space will be order of n as well thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future not to check out my previous videos and keep supporting happy learning cheers guys | Simplify Path | simplify-path | Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names.
The **canonical path** should have the following format:
* The path starts with a single slash `'/'`.
* Any two directories are separated by a single slash `'/'`.
* The path does not end with a trailing `'/'`.
* The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`)
Return _the simplified **canonical path**_.
**Example 1:**
**Input:** path = "/home/ "
**Output:** "/home "
**Explanation:** Note that there is no trailing slash after the last directory name.
**Example 2:**
**Input:** path = "/../ "
**Output:** "/ "
**Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
**Example 3:**
**Input:** path = "/home//foo/ "
**Output:** "/home/foo "
**Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one.
**Constraints:**
* `1 <= path.length <= 3000`
* `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`.
* `path` is a valid absolute Unix path. | null | String,Stack | Medium | null |
703 | okay let's talk about okay largest element in the stream so you'll be assigned a class to find the k largest element in the stream and look like this is okay large cell meaning sorting order another k distinct element so you have to implement the k largest class so this is constructor and this is add method so for the constructor you have the size of the accessible string and then the rate and the value you just have to add into the string and this is how it is right and for example one right you have in the ring the size and then you need to pop the smallest one because the smallest one is not loud because it's sorting array so if you if the size is if the string size is greater than the size we eat right then we need to pop so 4 5 two then this is size of four right we need to pop one which is two and we add another three so they'll become three four five eight right but three four five eight sets of four which is greater than three right so you know popular three and then we pop i mean we publish three and then you have to pick the current minimum which is four and then five if uh the current carrier minimum is five 10 5 9 8 4 8. so they just start coding without too much talking so what i have to do is i need to know priority queue so priority queue is the sorting i mean is adding a value into the string which is from smallest to largest and you can also reverse but that will have a different scenario on this case but we are definitely like using a default depot priority q so i'm going to say priority q is equal to integer because we are sorting integer right so i'm going to say p q and we do need to know the size of the sets of the priority q then i'm going to say in size then uh the size is equal to k right because this is how u actually initially says then i need to initial my priority q mu equal to mu p pi priority queue and the sizes become okay the maximum for the pq is size of k right so what i have to do i have to add every number into a priority queue so i'm not recommending you to do this include the add and the num because this would give you a little bit trouble when you're just adding so since we have add method right then what we act uh what we can do is we just say so what we're doing for add so we are going to say p 2. and we need to check um if p q the size is greater than the actual size we given the exercise the i mean size of k right if we when we add right when we add a value into priority q at some point it will greater than the size for the i mean for the restriction right so we need to pop so i mean pq is pull right into that pole then we need to return the current parameter i mean current minimum of the uh industry so p dot p and this will be the solution and if you're concerned why i use if because uh for every single time we add we definitely add from size of zero right and then we add when you hit one point you are definitely greater than the size of the k right then we just pull if you are concerned while using speed you can change too well but the solution will be the same and you just run the code and then see if i have any error or not and this will be it right so let's talk about timing space complexity so if you know the priority queue you are adding every number into the string and you have to compare the value between right so that'll be unlocked n right but the problem is we only have the size of k right so that will be uh a lot of k right um represent the numbers in the in array and then k represent the size of the k you only have size of k and then how many number a number that will be time and the space is definitely going to be all of k right you can only store k numbers in the string which is p q so that will be all k for space time is unknown k and this will be a solution if you have any question leave a comment below subscribe if you want it and i'll see you next time bye | Kth Largest Element in a Stream | kth-largest-element-in-a-stream | Design a class to find the `kth` largest element in a stream. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
Implement `KthLargest` class:
* `KthLargest(int k, int[] nums)` Initializes the object with the integer `k` and the stream of integers `nums`.
* `int add(int val)` Appends the integer `val` to the stream and returns the element representing the `kth` largest element in the stream.
**Example 1:**
**Input**
\[ "KthLargest ", "add ", "add ", "add ", "add ", "add "\]
\[\[3, \[4, 5, 8, 2\]\], \[3\], \[5\], \[10\], \[9\], \[4\]\]
**Output**
\[null, 4, 5, 5, 8, 8\]
**Explanation**
KthLargest kthLargest = new KthLargest(3, \[4, 5, 8, 2\]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8
**Constraints:**
* `1 <= k <= 104`
* `0 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `-104 <= val <= 104`
* At most `104` calls will be made to `add`.
* It is guaranteed that there will be at least `k` elements in the array when you search for the `kth` element. | null | null | Easy | null |
792 | Ajay Ko Hello Everyone Welcome 2016 Find On Chalu Notification Number Of The Thing Subsequent Inspiration Which Giveth Now School Video Like Solution Subscribe To Loot Number Matching Subsequent To 0.4 Subscribe Over All Subscribe Video Subscribe subscribe and subscribe the Channel subscribe to the Page The report in the string in subsequent Suryakund Intermediate 2nd 201 9 Subscribe Video Subscribe See Again subscribe Video that Bihar Chief and Counted for this is not think about this question On's reporting do is suicide note over all characters water in such strength and enters into * Subscribe hai enters into * Subscribe hai enters into * Subscribe hai to madhav od to start with subtitles in the important hai so let's do right and left side reddy idi pintu mama ki yeh si bhi to connect with half baje nd sudhir wa ki biwi k e want with oo ki no what we do We Will Do Tractor Input Supersonic All Characters We Subscribe Anil Dhairya Chief Will Remove Subscribe And What The Meaning Of C D Subscribe Video Subscribe That And What Will Be The Meaning Of Date Announce Vihar Phase subscribe to the Page if you liked The Video then in Knowledge Country The Process of Baroda Next Entry And What Do We Call The Road To Subscribe To I Want To What All The Characters And Between Left And Dip There Is That Did Not Exist In This Defect In Subscribe And Subscribe 108 Stage A Protest That Andeshwar Parshvanath aur electronic jo process ki handi sahib SIM activate civil dhandhe all the best subscribe hai so let's get started * If you are in real hai so let's get started * If you are in real hai so let's get started * If you are in real locations and this subscribe to andar Gandhi was latent in the process was taken its quite amazed e salute all the day in The Life Into Depression Adhir Who Subscribe To In The Mix It Actresses Reminder Account And To Four The Answer Is Were Widowed And What Volve Widowed Who Viewers Got A Difficult Half Final Maaf Character Como Curir Pink Veeraval And Vasundhara Ne Excited Veer Vidya Widowed Its subscribe The Video then What is Related to be Complete List of Absolute Elements Sundar List One by One Android Check What is the Meaning of Subscribe Otherwise That I Check Weather Do a Second Difficult Posted Subscribe Meaning of Subscribe Dot Write the Please subscribe and subscribe the Video then subscribe to the Light Play List PDF This is Updated I am Android To Like Share and Subscribe Our Channel Subscribe | Number of Matching Subsequences | binary-search | Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
* For example, `"ace "` is a subsequence of `"abcde "`.
**Example 1:**
**Input:** s = "abcde ", words = \[ "a ", "bb ", "acd ", "ace "\]
**Output:** 3
**Explanation:** There are three strings in words that are a subsequence of s: "a ", "acd ", "ace ".
**Example 2:**
**Input:** s = "dsahjpjauf ", words = \[ "ahjpjau ", "ja ", "ahbwzgqnuk ", "tnmlanowax "\]
**Output:** 2
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `1 <= words.length <= 5000`
* `1 <= words[i].length <= 50`
* `s` and `words[i]` consist of only lowercase English letters. | null | Array,Binary Search | Easy | 786 |
1,886 | all right guys day 56 the 100 days elite code um we're doing another matrix problem today it's determine whether matrix can be obtained by rotation let's get right to it so given two n by n matrices binary matrices uh matte matrix i'm just going to call it and target return true if it is possible to make matte matrix equal to target by rotating matrix and 90 degree increments or false otherwise so this one of course is true because you just rotate that 90 degrees you get one so that is true this one of course is false um because there's always going to be that extra one no matter how much you rotate it you can't make it equal to that and this one i mean you can look at it but basically it's true because you can rotate it twice and get that okay so let's solve the problem so yesterday day 55 i'm going to link it uh we did another matrix problem called rotate image so i'm just going to go to that i'm going to copy and paste some of that code and put that into a helper function okay so this code here so now we have that code from yesterday and um we're gonna explain a little bit about how that works in case you didn't watch the video again that's linked down below but basically the way it works is this first transposes the matrix and then this basically reverses each of the rows okay and that is what gives you that 90 degree rotation okay so now we want to figure out if we can do any amount of 90 degree rotations and turn this matrix into the target matrix so once we have the code to rotate the matrix it becomes pretty easy we can just do four i in range four right so we're going to do a for loop that's going to happen four times um and then we're just going to call self dot road sate uh matt and then if matt equals target return true and then obviously if we get through that and we don't have it we are going to return false okay so that's how we solved that one that was day 56 if you guys enjoyed it please like subscribe see you tomorrow day 57 | Determine Whether Matrix Can Be Obtained By Rotation | minimum-limit-of-balls-in-a-bag | Given two `n x n` binary matrices `mat` and `target`, return `true` _if it is possible to make_ `mat` _equal to_ `target` _by **rotating**_ `mat` _in **90-degree increments**, or_ `false` _otherwise._
**Example 1:**
**Input:** mat = \[\[0,1\],\[1,0\]\], target = \[\[1,0\],\[0,1\]\]
**Output:** true
**Explanation:** We can rotate mat 90 degrees clockwise to make mat equal target.
**Example 2:**
**Input:** mat = \[\[0,1\],\[1,1\]\], target = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** It is impossible to make mat equal to target by rotating mat.
**Example 3:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\], target = \[\[1,1,1\],\[0,1,0\],\[0,0,0\]\]
**Output:** true
**Explanation:** We can rotate mat 90 degrees clockwise two times to make mat equal target.
**Constraints:**
* `n == mat.length == target.length`
* `n == mat[i].length == target[i].length`
* `1 <= n <= 10`
* `mat[i][j]` and `target[i][j]` are either `0` or `1`. | Let's change the question if we know the maximum size of a bag what is the minimum number of bags you can make note that as the maximum size increases the minimum number of bags decreases so we can binary search the maximum size | Array,Binary Search | Medium | 1335,2188 |
1,727 | hey everybody this is larry this is q3 of the weekly contest 224 largest matrix or just sub matrix of a rearrangement uh i found this one really hard it might have been the hardest one for me um i think it's just because i don't know i just had issues with it and i found cute for a little bit easier but yeah hit the like button hit the subscribe button join me on discord let me know what you think about today's problem and this problem uh was pretty tricky i'll do it a thousand people got it so maybe not that tricky but um but yeah the key observation for this problem is that okay you just um going from top to bottom you look at each slice and then you know looking backwards kind of just see how far each one extends and once you do that um and that's kind of the idea of that behind the algorithm is that you know for each and with a little bit help from maybe you could call it dynamic programming uh for each point you can count what's the longest um you know from here going back how many ones are there uh going up in that row right um and once you kind of uh have that uh result then you can just go for it one by one you could sort or you could do it uh a sorting or i did accounting sort um and that will allow you to get the answer and let me demonstrate a little bit by pointing out the paint brush right give me a second let me set this up technology is hard um okay wow that actually worked without me anyway so basically for example if you have you know your matrix is you know zero one okay maybe let me add a one zero one then you know at this point the longest length going up will be zero uh here will be one here it will be zero again oops that's an algorithm uh this is one this is two uh this is zero and this is one right so that's basically you know filling out from top to bottom um and then now you do it for each column right so each column is going to look like something like that you have zero one two three zero one two zero i don't know i'm just making numbers up um two zero one two three right uh maybe i should use a different color but it's a little late for this one but okay and then now you have these uh really ugly looking numbers um you know we just do it uh yeah yellow is not a great color either but basically you just look at each one at a time here well there's zero so it doesn't matter nothing happens right and then we just kind of look at it one way at a time that means there um now here we could see that the three ones so that means that the longest is going to be 3 times 1 which is the area of 3. here you see that they're two twos and that means that you know that at least two um two columns that has two with so that means that um you know you want to multiply by that area is going to be four so then now you keep track that way and that's basically the idea uh of how we do it for example here is one and three that means that you know and you could what i did was that um and you could i'll show you the code as a second that i go from higher number to the lower number so then in this case uh you know we have one row of uh size of at least three so it's kind of like similar problems that you might have practiced with respect to kind of getting this but um but yeah you have you know at least one column of uh of length three and then you have at least two columns of length one so you take the max of those and of course of the previous answers so that's how you do it here you have uh one column of uh a of length two and two columns of at least length one right and that's basically the idea and skipping ahead here you have one column of length three two columns of length two and three columns of length one so that's basically uh how we kind of go for it and as you kind of you know look at the complexity which we'll talk about in a second um let me get rid of this for a second okay so basically that's the idea behind this problem um i actually did some unnecessary stuff so um i might clean this up uh actually i should uh though i might this code might be wrong now because i'm gonna clean it up but basically yeah we get the um from the previous row right if matrix of x y is greater than zero so this is just you know regular dynamic programming um of you know like we said if this number is uh greater than zero um then we add it to the previous row um to get the longest uh running sequence right and then here um for each column now for each row we check each column right of um for each row we check each column of each count we put in a hash table uh to make it uh simpler uh though you can you could probably you can actually sort this and it will still work there are definitely a lot of solutions for that but uh but basically um yeah i um i keep in a hash table and then i look at the keys in reverse order so i do a sorting here um and for each i you know this is the running sum basically this is the number of uh previous columns that have at least y uh that is at least y height or higher right um so this is a pre uh prefix sum counting from the high number to the lower number um so once we do that then this is the number of um number of columns that have at least y sum uh y like height so this is the height this is the riff uh which is the number of columns and that's the uh a possible candidate for the area and that's basically and then we just max it over all these columns and that's pretty much the idea behind this problem uh what is the complexity right well this is going to be linear in terms of the space because it's just rows times columns this is a little bit trickier this is going to be rows times um columns like columns right because for each row we sort all the columns which is y log y um oh sorry which is columns like columns so yeah so given that um r is equal to rows c is equal to columns the total complexity is going to be o of r times c log c right um because we have all rows you know the outer loop and then each loop does c lock c time because it gets dominated by this sorting and that's pretty much it um and the space is you know it's going to be dominated by this hash table which at worst is going to have one entry per um per matrix element so it's going to be linear in terms of the size of the input which is rows times columns that's all i have for this problem i struggled a lot during the contest so feel free to fast forward but you could watch me solve it live and come into it uh slowly um i really was stuck on this farm for a while i just have no idea um but yeah let me know what you think and i will see you later hmm what am i doing hmm um it's just greedy hmm i have no idea you let's take a look no one's gone it yet so let's come back okay wow some weird query really have no idea okay keep track so you how do you combine them i don't know i'm gonna skip ahead again these cute trees have been hard but no one's getting on q4 yet either so this is probably hard as well a lot of states though let's go back to this one people have gotten this one but i don't know it almost quick summit by accident sorting out now sony doesn't have a kindle example how do you even do it i don't know if this works right here okay figure this out why did i delete that you yeah that's what i should have done okay is just tp let's go you that means that just and i'm mixing my rows and columns it's not good oh wait did i miss read this one because that's an input that's sad uh i'm i've rushed it i said to slow down be careful but instead i added five minutes for no reason okay i swapped them um i even knew to check for it now let's time limited why what is that oh because it's both square that's silly okay so because this could be sparse that's why uh okay fine dumb mistakes uh thanks for watching everybody uh hit the like button hit the subscribe button join me on discord and ask me questions about this problem or other problems uh have a good year and all that stuff and i will see you next problem bye-bye | Largest Submatrix With Rearrangements | cat-and-mouse-ii | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. | Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory | Hard | 805,949 |
566 | hey everyone welcome back and today we will be doing another lead code problem five sixes reshape The Matrix in the Matlab and easy one this is an easy problem in the Matlab there is a handy function called reshape which can reshape MXN Matrix into a new one with the different size or XC keeping its original data you are given an MXN Matrix mat and two integers R and C representing the number of rows and number of columns of The Wanted reshape Matrix the reshape Matrix should be filled with all the elements of the original in the same row traversing order as they were if the reshape operation with the given parameters is possible and legal output the new reshaped Matrix otherwise output the original Matrix that's it so we have given a grade or you can say the Matrix and we have to return and they are passing alongside that the row and column so if they want one row and four column we will just reshape The Matrix and return it like this and if you want a two by two which is already two by two but uh you got the idea how things are going to be done so we'll be making a flat list and a Matrix we are going to return and flat list just to take the elements in the you can say from the mat itself so every sublist in math for every item in sub list so this is going to just append character to Flat list uh note characters just elements to the flat list which will be item and now we will check if the length of the flat list if it is not equal to our product C then we know that this is just not possible and in that case we will just return our mat and in the else case we are going to see like for I in range of 0 till the length of the flat list and taking C steps at a time column steps at a time and now we will just append Matrix with the slice of flat list which will be I starting from I and till I plus C and we can just return at this point return The Matrix itself so that's it foreign example like let me just copy this and then we will see we have a matrix this will be the mat which are which is passed and R is equal to 1 and C is equal to 4 so what we have here is for every flat list is empty so flat list is empty flat list is an empty list and the Matrix is also an empty list and now what we'll be doing is for every sublist in math so the sub list will be like 1 and 2 so the for every sub list we will just append characters that item so the item from that sub list is going to be uh one and we will just depending one to our flat list and then again two then it is going to be updated because we are done by the you can say at the first index of the mat note the sublets or of the not the sublet list part of the mat so now we're going to the you can say the second index which is just basically 0 1 so taking one index so one will be three and four and now the item will be uh three and we will append three and then the item will become four and we will append four also and now the item is uh like we have Traverse through this four double for Loop and now we will just go to the flat list and check if the length of the flat list is equal to the r product C so the r product C is four and the length of the flat list is also four so what we'll be doing is just slicing the flat lace so after slicing the flat list like for the iteration I is equal to zero so for I is equal to 0 and see is you can say 4 here yes C is 4 so what we will be doing is just slicing so the zero index is this and the fourth index is obviously going to be this and that's it so we'll be slicing obviously we do not take the fourth index because we ignore the fourth index and just excluding including the first one and it's excluding the last index so we can have 0 1 2 3 so the output will be one two three four so that's it and that's our output and yeah if you have any questions you can ask them in the comments and that's it | Reshape the Matrix | reshape-the-matrix | In MATLAB, there is a handy function called `reshape` which can reshape an `m x n` matrix into a new one with a different size `r x c` keeping its original data.
You are given an `m x n` matrix `mat` and two integers `r` and `c` representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the `reshape` operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
**Example 1:**
**Input:** mat = \[\[1,2\],\[3,4\]\], r = 1, c = 4
**Output:** \[\[1,2,3,4\]\]
**Example 2:**
**Input:** mat = \[\[1,2\],\[3,4\]\], r = 2, c = 4
**Output:** \[\[1,2\],\[3,4\]\]
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `-1000 <= mat[i][j] <= 1000`
* `1 <= r, c <= 300` | Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols.
This is the one way of converting 2-d indices into one 1-d index.
Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d indices. M[i] => M[i/n][i%n] Will it result in right mapping? Take some example and check this formula. | Array,Matrix,Simulation | Easy | 2132 |
1,288 | hey what's up guys this is john here again so uh so this time i want to talk about today's uh daily challenge which is number 1288 remove covered intervals so this is a this is like another interval problems where you of course you know every time when you see interval problems you know you need to sort it in some way right okay so again so basically we have a bunch of intervals here right and you need to remove the total cover interval so an interval is covered by another one if it's basically division let's say there's interval a and b and c and d here a is covered by a b is covered by cd only if the c is smaller than a and these d uh d is greater than b basically only when there's a like interval and there's like another interval that's uh starts starting is before this one and ending is before this one okay that's how you call like this interval is covered by the second one okay so and ask you to it asks you to remove all the covered intervals by any of the other uh intervals and then it asks you to return the number of remaining intervals so for example this one we have 1 4 three six and two eight basically the three six is covered by two and eight that's why i mean the uh the three six will be removed and the remaining is two okay yeah those are a bunch of other like intervals pro the bunch of examples here so i mean let's say we have a bunch of intervals i mean the easiest way is just we just store it by the starting time okay if we simply sort by the starting time okay and then we are guaranteeing that like the uh and the second one right and the second one will be uh be before the i mean the current one will be for the uh the previous one basically we're sorting by the start time so that i mean the first condition it is matte okay now we just need to check if the ending point is within the previously at the previous uh the previously intervals to be able to do that right i mean of course in this case i mean since we have a here oh sorry we have this intervals here and when we uh see these intervals we see the okay so the current ending is before the uh the previously ending basically what this means that will be maintaining like the biggest ending uh previously okay and this one simply it works because the uh we will process this interval first and then this is one but the issue is let's say we have a two intervals that starting i mean have uh happens to have the same start time so let's say this one i mean if that's the case right i mean based on if we only do a simple sort by this intervals dot sort so which one will come first this one so why is that when the starting time is the same so this interval is basically the sorting will basically will sort uh the ending time accordingly and we in this case this ending time is smaller than this one that's why the uh basically it won't give us the results okay so what we are trying to achieve here is that we always want to pro in the in case of the same starting time we always want to process the ones with the it's a long with the bigger ending time right so that later on when we process the smaller one we can compare this one we can compare with the current one the current ending time with the uh where's the previously biggest ending time that's how we can uh that's how we can determine i mean if this current interval is covered by the previously by the previous one uh okay so with that being said like i said i mean in this case i mean since we have basically one sort we want stored by the first we want to sort by the start but we want to sort it uh like the uh descending order for the uh for the ending time okay that's why we need to create a like a lambda key here lambda okay equals to key right sorry key equals lambda sorry key equals to lambda and then x here right so and here will be uh basically we'll create our custom customers a customized key here where the first one is x zero and the second one is since we're going to sort it like from a descending order we simply can just use this right basically we just do what i use the negative value to sort the second one so now we can do a for loop here right so and start and end in enumerate interval okay so like i said uh we will have like removed zero and then we'll have like uh max ending time okay equals to zero so basically every time when we have like intervals here all we need to check is that we just need to check if the current ending time is smaller or e smaller or equal than the previously max ending time so this one since we can start from the first intervals because the uh because the end the ending time right because the ending time will always be greater than zero so which means so for the first one it will never go inside here but and here we just need to maintain this one right maintain the current ending time with this with the uh with the current with this ending time sorry the max ending time not the current one and with this one right so now if this ending at the ending time is smaller or equal smaller than the max ending time then we know okay so the current so this current intervals must have been uh covered by the previous by one of the previously previous uh intervals so right so that we can simply add this removed by one yeah and then here we simply return the length of the uh the intervals right and then miners removed that's going to be the answer yeah run the code list and uh what oh sorry ah not enumerate sorry i don't need the index here just the starting time ending time accept it submit yeah so it's accepted all right cool so i mean it's pretty uh straightforward uh interval problems where it just sorts and then the sorting is a little bit uh different here basically we sort by the first the start time and then uh and at the ending time in descending order so that we can uh simply uh and then we're maintaining like this one the maximum ending you know every time when you assort by the first by the start time for in terms of in for this interval problems you always most likely you will be uh need to maintaining you need to maintain like the maximum ending time to do some checkings here in this way uh in this problem we just check if the current is within the current max so that we know okay it's totally covered it's completely covered by the previously uh previous interval so that we can increase this one yeah and of course the time and complexity is unlogging right because we do a sort here and here's n so it's unlocked cool i think that's it for this problem thank you so much for watching this video guys stay tuned bye | Remove Covered Intervals | maximum-subarray-sum-with-one-deletion | Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**. | How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm. | Array,Dynamic Programming | Medium | null |
414 | hello guys my name is Ursula and welcome back to my channel and today we are going to solve a new lead code question that is third maximum number with the help of python so just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and book Marti playlist so that you can get the updates from the channel so the question says given an integer Arena set and the third distinct maximum number in this array if the third maximum does not exist return the maximum number so let me explain it to you what the question is asking us that we have to return the third maximum of those so the third maximum number would be uh first Maximum number would be 2 followed by uh for first Maximum number would be uh 3 followed by two and then one so we have to return one here similarly here there are two only two numbers so this is that if there are no if there are only uh if there are not any three values means if there are only uh less than three values in the array so we have to return the maximum value in this in that array meaning that if there are only two values or one value in the array we have to return the maximum value so we have written the maximum value here that is two similarly if we talk about example number three you can see that there are four values in here and again the maximum number third maximum number is one so let's start solving this question guys so you see that we have to only apply for testing maximum number if they if we return here return um nums minus 3 means that the third index of this number we will get our answer however it's not the correct method you see here why it's not correct I will explain it to you why it's not correct because um okay so why it's not correct I will tell you that if I put 0 here you see that we are not getting our answer actually here okay so why we are not getting our answer here because let me explain it to you so if I put uh 3 here we have got the we have uh we instantly this is this number is our answer but it's not the answer here because uh oh it's actually two here so see that we have uh this is inside this had been accepted however it's not the correct why it's not correct I will explain it to you okay so we have to apply for distinct values so for that I will be creating a uh list here list and as they are asking us through the distinct value so for distinct value I will create a set and in that I will say that num so if I run a temp return temp so return temp 0 so I will get some value here which I don't know yet so see that we if we apply for set here our array has been sorted but however we do not want this value because it's not the correct method yet another yet again so what we will be doing here we will sort this array so I will create another variable here that rest is equals to sorted temp and then I will say reverse is equals to true now I will say if length RS is greater than sorry it's less than 3 then return whereas zero mean because the array has been sorted in the reverse order so if I talk about here in example number first I will be getting three two one similarly if I talk about example number two I will be getting 2 and 1 and in example number three yet again I will get three two and one so for that I will say that if we have to check for the maximum value if it is less than means the length of uh the array is less than 3 so we have to check for the maximum values maximum value is the first index at the first index so else we will say that return um areas which value this value is already that's two now we will get our answer you see that we have got our answer here we have we will apply for multiple test cases and yet it will run so you see that our answer has been accepted successfully so this was all in the question guys hope you have understood it and hope you will like the video and hope you have understood it as well so thank you guys for watching the video if you have any doubt ask in the comment section and see you next time | Third Maximum Number | third-maximum-number | Given an integer array `nums`, return _the **third distinct maximum** number in this array. If the third maximum does not exist, return the **maximum** number_.
**Example 1:**
**Input:** nums = \[3,2,1\]
**Output:** 1
**Explanation:**
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.
**Example 2:**
**Input:** nums = \[1,2\]
**Output:** 2
**Explanation:**
The first distinct maximum is 2.
The second distinct maximum is 1.
The third distinct maximum does not exist, so the maximum (2) is returned instead.
**Example 3:**
**Input:** nums = \[2,2,3,1\]
**Output:** 1
**Explanation:**
The first distinct maximum is 3.
The second distinct maximum is 2 (both 2's are counted together since they have the same value).
The third distinct maximum is 1.
**Constraints:**
* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Can you find an `O(n)` solution? | null | Array,Sorting | Easy | 215 |
128 | welcome back to code Meets World today we're looking at leak code problem 128 longest consecutive sequence so we're given an unsorted array of integers and we need to return the length of the longest consecutive sequence of elements and this must run an O of n time so what that means is given an input array we need to look and see the longest stretch of consecutive numbers so in this example 1 2 3 and four are all consecutive numbers and they have length four so the solution here would be four and then with this example down here it looks like you can make um zero all the way up to eight 0 1 2 3 4 5 6 7 8 and so that's length 9 and notice there's two zeros here but that doesn't really matter we just ignore the duplicate and just use one so this is the second example from the problem right up um and the output here the solution that we should get is nine because you can make 0 1 2 3 4 5 6 7 and 8 so for how to solve this one thing that we could do is we could go and start looping over all of the values in the array and so we would start here at this zero and we would say okay let's see how big of a list we can build so when we do that just like I showed in the example we would be able to go from zero all the way up to8 um which equals length 9 after that we can move to the next number which is a three and we could start at that three and we could go as high as we could so just like we did with the zero we would start at three and then what comes after three four 5 6 7 8 and you'll notice that is length six if we go all the way up to eight we could keep going and do the same thing starting at seven and increasing so we would just go seven and then eight so that would only be length two like that and we could just keep going and once we make all of them we could just go through our list and pick the biggest one which in this case is going to be 0 to 8 this is not as fast as it could be because we're wasting a lot of time by in this case we found the best one right off the start but then the whole rest of the time we're going to be counting ing other sub sequences that are part of this original sequence and so are obviously going to be shorter so there is something better that we can do I will mention that one way we could solve this problem is by simply sorting this input array so we could sort it and it would end up looking like 0 1 2 3 4 5 6 7 8 and then we can just walk through and count how long our sequences are so from here to here that's the same number so the sequence length is still one now it goes to two and then it goes all the way up to length n here and that's one way to do it but if we did it by sorting this would end up being o cuz sort would take log n but then after the sort we would have to go through and count how long the sequence is so this would end up being o of n log n which is good but it's not quite the O of n that we're looking for so that solution is not going to work here I just wanted to mention it but there's a way we can do this so we can skip all of the subsequences so once we've seen this big one we don't have to look at any of these other ones and the trick to doing that I think is when we're going through and iterating over and checking a number if we have already or if the array contains one digigit smaller than the value that we're looking at we don't need to process that chain because we know we're going to process it with the smaller chain let me show you what I mean by that so again we're going to start from the beginning like we did but with this new idea so we'll start with zero and we'll make that chain that's going to go through like we've showed and go from Z 0 all the way up to 8 which equals length 9 then when we go to the next value which is three last time we just started the three and counted as high as we could go to eight but what I'm thinking that we do this time is because if we take three and subtract one from it so in that case two we ask ourselves is the number two in our list and it is it's right here and the theory here is that because two is in here let's not calculate the distance from three because we know that whatever the distance is from three is going to be shorter than whatever the distance is from two so there's no use calculating the three because the two is connected to it sequentially and the one that starts at two is going to be longer so there's no use calculating the one at three so when we get to three we just don't do it and the reason we calculated zero is because we would first check is Nega one in the list it was not in the list so we'll start and calculate at zero so we'll calculate zero we're not going to calculate three when we see the seven next we ask is six in the list it is so we don't calculate the seven when we go to two we ask is the one in the list it is so no need to do this and the same thing no need to do five no need to do eight or four or six because the value minus one is in the list when we get to this zero again technically we've already done it so what I'm thinking in our final solution is we don't allow any duplicates so we could convert the list into a set at the beginning to remove the duplicates because we don't want to look at the zero and then finally we get to the one so we ask ourselves have we calculated or have we've seen zero in the list the answer is yes so we don't need to calculate one either so amazingly with this method we only have to run one sequence which is on that original zero all the rest of them we won't end up doing and at the end of it we'll just return that The Final Answer is nine because there could be other ones where we have multiple sequences that we check and we just need to keep track of this largest value at the end the first thing that we're going to do is remove all the duplicates by turning the input array into a set which will just remove all of the duplicated values no matter how many times they're there so I'll call this all and I'll set it equal to the set and then if you pass in a list into the set in Python it will just make a set out of it and set that as all so we'll do that and then we'll set a variable for the longest chain that we've seen set that equal to zero and now we're ready to Loop over all the values in the list so we can say for Num in all so We're looping over the set here and this is not going to give us the values in any order because sets are unordered so it'll just be a random ordering of all the numbers not chronologically and so the first thing we want to check is this value one in the set because like I mentioned on the Whiteboard here for any number that we see if that number minus one is in the list we don't need to check that number because we'll we know that there is a longer chain that will compute earlier on with the other number so we can say if num minus one is in the set which I called all if that happens we can just continue which will just go to the next iteration of the loop and check the next value then in the case where num minus1 is not in the list so for instance in the case of zero in this example 0 minus one is netive 1 that is not in the list so in that case what we want to do is build this actual chain and see how large it is so to do that we can set a current length and I'll set that equal to one and then I can say because I just want to Loop while num plus current length um is in all so what's happening here is I'm taking whatever number I'm on at the start here I'm adding one to it and I'm checking is that value in the list or in the set so on this example I'd be taking the zero I'd be adding one to it and saying is number one in the set end of this so while that value is in the set we can say current length plus equals 1 because we're growing the count of how many sequential numbers we've seen so we're adding that we're incrementing that by one and at the same time this is also incrementing what we're checking each time so first we check is one in the set it is so we make our current count or our current length into two and then we can check okay is num plus current count so num which was Zero at the start 0 plus 2 is two so now we're checking is the two in the list it is so we would increment this to three and then add 0 + 3 which is three and then add 0 + 3 which is three and then add 0 + 3 which is three and check is three in the set which it is so on and so forth once we eventually reach a value that is not in the set so we've ended our chain we need to see if this sequence we've found is larger than our longest because we might see multiple sequences so this time we can say longest is equal to the max of whatever longest currently is and then the current length variable that we just computed so this will just replace longest with either itself if it's still longer or the chain that we just found if that one is longer and then once we're done with all of this we should just be able to return longest so let's run this see if there are any issues that looks to be accepted so I'm going to submit it and there we go this solution passes and if you can see on the little histogram here this is as fast as you can do it so even though this is only 59th percentile all of the solutions are the same percentile here so that's how you solve this one and let me know in the comments if you have any questions I'll see you in the next video | Longest Consecutive Sequence | longest-consecutive-sequence | Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._
You must write an algorithm that runs in `O(n)` time.
**Example 1:**
**Input:** nums = \[100,4,200,1,3,2\]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.
**Example 2:**
**Input:** nums = \[0,3,7,2,5,8,4,6,0,1\]
**Output:** 9
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109` | null | Array,Hash Table,Union Find | Medium | 298,2278 |
706 | Hey guys welcome and welcome back to my channel in this video will go into song design is in snap swift problem we are design people are going to solve time problem your gift statement is here what is what you have to do here is that Today I have to do a design for you and also here you do not have to use any built-in festival here you do not have to use any built-in festival here you do not have to use any built-in festival sides and there is a class which has to be implemented, the class which is my house map class, in it a contractor has been given a function, an exit function has been given. A remove function has been given, okay, what do we have to do, we have to construct all these functions, so now the importance of this is the constructor and the food which has given two almonds in it that is the end value, what do we have to do in that map, hand smart. What we have to do is to set his unveiling to these. If he is already the president there, then what will we do with that condition, what will we do? What will we do to update his value which is said to insult ours? We will update it with the value and already if he is the President there then it is ok. We have given a gate. The gate function here means that you search here, if it is there then do 'A' and return with the value of that. do 'A' and return with the value of that. do 'A' and return with the value of that. Okay else - 110 has to be done. Okay and Okay else - 110 has to be done. Okay and Okay else - 110 has to be done. Okay and remove. Here remove functions are given more. That's what you have to do is to find the value first. If you find it then you will remove it. From here you will remove it from mother. Okay, so how will we solve this problem, the design which we solved yesterday is set SIM, this is our Hussain problem, what should we do here, we will use Singh here, again we will use festival, we will use half function and solve this problem. If we do, then first let us understand what is the function of every tempered glass at every moment, what is the housing which is warp, what is the technique, what does it do, we use this technique so that if someone has inserted any quinton size glass, then what do we do with that data? Whether it is stable, we will break it into economic sizes and on what basis we will use it, for that we use first function and Harsh function depends on you, which type you want to use, your coding can be different. If yes, then what will we do here? So I understood that I am camping here in what kind of tender, okay and we want to start this stable free-sized table lamp, how can we do it and start this stable free-sized table lamp, how can we do it and start this stable free-sized table lamp, how can we do it and Is it stable? Now what kind of type it is, that also depends on A. Do you want to get the type that you want to store the first one from the side? Okay, that also depends on you. So what will we do here? First of all, here. But what do we do, let's take a festival of tan size, understand that the address is here, we have taken it in the festival, we know the fit, this London son has given us, we do n't know how much of the side it is, leaving it to us, in the nice pick side. What is this from where how many sides is it tan so in the index from states to 9 inches it came 08 and sex of a spider were seventh and eighth 1234 so here we have to store it now we do any Where should we store it, we will do it, we will create it here, what it will actually do is send us a text for the value, okay, so how will it be, as much as you want, it will be a reminder of that. Here we do it, then we will go there and start it, okay, so we have stored it here, okay, maybe we have stored 11th here somewhere, you will have to star eleven, now you can divide eleventh also. If you do this, then what will happen to this also? Reminder, what will happen to this, there will be a forest here also, then you are not here, you can store it, no, the reminder of this is that this Science Express needs 1000 but there is already a forest here, so what will we do which is I had kept that in my mind, I will take it off the list so that what we do here on the same index of religion and we can break the data, so what we will do is we will take it off the list which was the previous problem and yesterday's one. But it was taken in that, so here we will start the eleven here, it is okay, then if it is possible, then you would have got one like this, so that you can divide it calmly, then there would be one reminder, then what would you do with it? After storing it, we check whether Twenty One is already pregnant or not. If not, Dat Mirch, then what will we do, we will start it, OK, from here, you will divide for four, how much will be your reminder from the train. If there is a photo, then you can match the fonts here. Okay, then it happens that somewhere the view for teenage has to be done inside, it is also possible that if you divide the tension with your husband, then what will happen, the complete index of which will come as a reminder. It will come completely and if you have to go and store it, then what will you do here, after this, whatever festival we take, we can take it according to our own, here we have taken the edifice, so we can store it here, right, which has side effects. No, as much as these will come, so whatever will be made in the circle, what should they do with it, we will keep adding inches, it is okay that this matter has become the last half table, in the half function we use, we have this answer bank, this is our key. Will give only one swan function and this is the data given, okay now what will we do to solve this problem, the data we have given in this problem is what we have actually given, now you will get the value tree here. If I want to support, then what we are going to use here is the festival we are going to use in this problem, we are going to do it like Oil of List of Fear, okay, you will put it on the index, maybe it will start that A is of such a type that you get a lot of it and you also include its value, for this we will use the leg, so here the one we are going to use for this problem, how is it actually stable? Now this will be 110 side, first we will take this here and now this will be the same, okay, the egg police will definitely be this, then the value will be stored in the form of a tree, the value system will do in this too, right? We will start the belt joint also in the form of leg. Okay, if you understand, then we will take a table of this type here. Festival, then what is yours, what is the problem here, let's take input, then how will we design the festival as per the maximum. Okay, what is our thing here, first of all, it is smart, okay, there is a constructor that will give you simple money, we are here like this, it will not happen, okay, then what is our something here? -There is some function then what is our something here? -There is some function then what is our something here? -There is some function Dominant, which is this put function, it is said that you have to inside the person and value, now where will you insult, it will depend on whom, this is the first value, so what will we do with it, here it is History Kanchan. Here we will create a fancy function, what will it actually do, will it return our 012 2130 to here is no then what will you do is divide it by chain so that where will this one go this one will remain intact now how will you store the value one and 1s value now its one is fine with its value that this Velvet has installed it that our output function is broken here, so what will you do to someone, but you will call this function here, it will say, can you now go and do this on the second index, this second injection, if you clarify it. Here we will start the tour toe, here we have made it two and two slow, okay sir, we have done someshwar of the tree, then what is our gate function, what is ours in the function, it is saying that this one, you have to fine it here or not. So, how will you run this thing? First of all, now you will see whose key it is on, this is ours. What should we do for this? For the trump key, we will open the hotspot setting for one and it will say that if you saw this type of reminder, it will say that one is intact. You will go and look there, okay now you will come here, then match the keys one by one, is there anyone from one key? Yes, first you will get it, but what to do if you get it, what will you do with it. Its value is open here whereas ODI has kept this point, if I have used it widely, there is a tap here from the warden type, OK, after that what are we, it is free to play cricket but everything will go on snacks, he will call here with a brush. So it will demand three and will go to sleep and then see if there is no value here then it will return minus one when no volume is found What will we do - we will when no volume is found What will we do - we will when no volume is found What will we do - we will do wonderland Then what is ours Two and One Dominus has said that you are the one who is the one. But now the value should be one, you have to set a pin here, so first where to set it, what will you do, you will call for Sanskrit, then it will say that you have to store it in two indexes, then you will go, then first check whether it is Two is already available, yes, you are already available here, its one is already available, Dominates, what will we do in this condition, this new viewers will update two, we will update its one here, two, which will remove the balance and once. Will update. Okay, updated. After that, what do we have to do, whether to call dysfunction or to call alliance? It is here, neither is it, so for this, first of all, on whose issue will it be, how will we get the decisions. We will find that it will be on this index, then we will find here and check one element, this match is happening here, first, what is the value of its from to then what will we do here, we will allocate it and this is one here. But it happened that you have to remove to, what to do to remove to do to -do, then first where will we -do, then first where will we -do, then first where will we call the help function, we will know that our to is on the index, so this is where we will go, okay here. To, you have also found that its value which is one is okay, these will remove it completely somewhere, we will remove it from here, then there is good function here, okay two, then where is your if this is this function call. You will know that to index will go here again but we will search here, we will find this because we have previously deleted it and if we cannot remove it, we will not find it, then what will happen - do 110, not find it, then what will happen - do 110, not find it, then what will happen - do 110, this is yours, how do we value it. To store it depends on what type we need, so what is this here, so I was you, our nature is to believe that when I am there, then the value will be stored in the value and we can have multiple values on one index. multiple values on one index. multiple values on one index. For this, what list will we use and here we will use the address of list of. Okay, so how will we solve this problem, how will we code, let's see, what will we do here, we have a vector of list, now pair inter MP will enter after thinking this, don't think that now we will go to the left side, Alka Yagnik, our tank depends on you can take anything, okay, I have taken the pan, what will we do here, we will make it the previous size, this will be ours. That this size of the tank will prevent this side, the mother size will depend on it is okay after that, will you create this chham, hypertension, who will share it, he will give our actual, he will give you on which index it is okay to do the studio. Here the size of tourism which we have taken is fine, then what to do, divide it, there will be a reminder, after going to the reduce reminder, he must have seen porn, going there, he will support, okay, now this is the point function, what is it saying in the foot function that your Given the value of the key, now we have to search it. If this key is already present there, then what do you do? If you don't update it, then what we will do first is that here the palace will be on its index, we will check that. Therefore, this time we will call for it has been demonstrated for whom will we use on follow and it came to know that we will start checking the index list of friends pet, it may not be in the list that Where we don't know where that chilli has been prepared then I you will believe me we will start it snowed equal .in it is fine till the last .in it is fine till the last .in it is fine till the last then little plus that it will check tomorrow I then will check that Have taken ITES room. Its first value does it match with the key? If it matches with the key, what will you do now in that condition? If the society always knows Lakshmi's key is already present then make the call coming out of it. Give Kumar value to the current volume. Keep it updated, okay, it has been updated, we will return it, we don't have to see further, now we will add it, if it is possible that this condition is not found anywhere in it, then what will you do now in that condition? Come here dot caret, there is some thing, what should we give the tree format of value, here is the entry, then the value is fine, this is done here, now we have to do the targets function here, then what do I do to do the gift function? What you will have to do is that you will have to search the value whether it is there or not as given by Vicky. If yes then return its value. Do the opposite minus one then we will add ghee here. First we will see that the bike can be on this index. This is the hash that you will call here, now it will be tightened that this is the index that you will check, see, you will use this also, first check one element from here whether it matches or not and yes it matches. So what will we do here about the second value, if we return it, I will copy it, so I will stitch it, if one matches it, then we will return it here. Return Gift Second Torch Light is unbroken, we will return it to Castor Oil Yoga. I have come here not because of Mr. but I have not marched because of this fear. If it is not done then I will aim at meter minus one, nor will I match one element or if I master then return the second value of it. Allah is this - I have to stop it, now you remove it. Allah is this - I have to stop it, now you remove it. Allah is this - I have to stop it, now you remove it. What will you do to get it? First of all, should I search because if he is present or not, then whether the President is present or not? Where will we search first? What should we do for him? We will open this function, we will bother to fry him, then we will fry him. Okay, match his name. If not, then first of all, such people activate anyone just like that, what should we do here, we will find out that we match you, if we match, what should I do about it, then you should remove that tree also from us. What will we do here, if MP returns, use Tigris team series, here the address is available, our erase it is ok, if we remove it here, we will remove it, there are two things in it is ours, it is done, it is ok. Let's run the code. Here's what happened. The cutter has cooled down. Let's submit the note. It's just time. So now this is the size. No, this is the size. You can take it any way. Okay, yes, right place. Now here. But if you change it, then this is yours here, this is your timing, this will only make a difference on the run time, okay, now check the record, check again and again, you can see that I have made it very big here, now go here and see. Lena you will understand something ok thank you it happened | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.