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 |
---|---|---|---|---|---|---|---|---|
858 | Hello Guys Welcome Problems Middling Question Adhir Vo Subscribe Number 90 Subscribe Must Subscribe subscribe to subscribe and subscribe is surface it follows this path no extent of square into another attraction this result appointed Video subscribe hai e wish e left the room is too expensive that time Laddu Rupend subscribe Video subscribe zaroor atithi subscribe and subscribe selection is than in these cases to acid porn loot do subscribe and subscribe our channel subscribe vidsho subscribe 9 a case where extension and reflection of but s possible to find a place where one Can Find Video Subscribe Suves Into Replication In To-Do List That And Deflection SP Leaders Will Tell U Behind Gif Worth RS One Ek Kiss They Are We Were Trending Was Loot Once In Bihar Values Will Be Old And Loot Once In Bihar Values Will Be Old And Loot Once In Bihar Values Will Be Old And Will Just All The Condition Will follow second condition and result navodaya vid oo e will put discus condition is china jai hind jai ho ki is election main is cord value day will return 90 is simrely famous condition and simply return minus one plus till which meeting night response is submitted. Video then subscribe to | Mirror Reflection | masking-personal-information | There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`.
The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0th` receptor.
Given the two integers `p` and `q`, return _the number of the receptor that the ray meets first_.
The test cases are guaranteed so that the ray will meet a receptor eventually.
**Example 1:**
**Input:** p = 2, q = 1
**Output:** 2
**Explanation:** The ray meets receptor 2 the first time it gets reflected back to the left wall.
**Example 2:**
**Input:** p = 3, q = 1
**Output:** 1
**Constraints:**
* `1 <= q <= p <= 1000` | null | String | Medium | null |
729 | hey what's up guys chung here again so today uh let's take a look at this lead code problem here number 729 my calendar one so which means there will be my calendar two or three but today let's take a look at my calendar one first it's a medium problem i think i kind of like this problem okay so let's take a look at the problem uh you need to implement a my calendar class to store your events and a new event has like a start and end which the end is exclusive and the start is inclusive basically and then you have this book method so you cannot have two events that are overlapping to each other for example it gives you like this example here so first you have events 10 and 20 from start from 10 to 20 and then if the event can be added then you just returns true of course and then you add the event and the sec the next time uh it actually asks you to add event 15 to 25 but 15 to 25 has an overlap from 15 to 20 then which means you cannot add this event that's why you return false and the next one is 20 to 30 which is fine because 20 is 2 and 20 it's like it's not overlapping to each other then you return true also you add the other event and yeah i mean that's the uh that's a problem right i mean it's uh the naive approach is of course we just simply like uh basically i'm going to like talk about two approach this time first one is the uh the linear search and the second one is like the binary search which will be using a binary search tree to implement this okay so first let's try to implement the naive solution which is going to be the books okay so this self.books will be maintaining so this self.books will be maintaining so this self.books will be maintaining all the other valid book in this like list here and every time um we have a start and end that's the event we simply loop through look through all the events basically for book for s and end in self dot books okay and then for each of the existing book we just need to check if that book has an overlap has any overlapping part of is the current set start and end with current book so the way we're doing the check is we simply do uh you know so to do the check right so s1 and e1 s2 and e2 so what's the way to check if this any of this like the range or the interval has any overlapping so basically we just need to check two things so it has overlap when right when the if the uh the start is smaller than the end and this start smaller than e right so basically we just check these two things as long as this start is less than this and the other star is at less than the other end then we know there's overlap what do we simply return false okay and uh if everything works fine we simply do a we simply like uh insert right let's do a self dot books dot append okay and then start and end and then we return true yeah pretty simple right so let's try to run it yeah okay submit yeah pretty straightforward all right and then what's the time complexity here so let's say that it's going to be n square right because every time we add like so i mean an n is the uh that is the time and the time we uh we call this book function right basically we have like uh yeah so let's say we call this book function end times and for every book for every bookings we need to look through all the existing books so the worst case scenario we're going to have like the o n square n times n right to loop through everything that's going to be the o and square yeah so pretty straightforward right and can we do it better oh of course right we can do it like um a better way right a better way is to keep all the books all the soft books sorted right i mean sorted means the uh things since it cannot have the overlapping when i say sorted i mean i'm talking about restored by the uh the start here let's say we have 10 20 right and then we have a this is 35 to 50 and then we have this like um 50 60 to 70. okay so i mean if we have these things here right you if it's sorted all we need to do is we just need to find let's say now we have like let's say we have like what do we have let's say we have a 55 and uh 55 and 60. okay now we want to insert this 55 and 60. all we need to do is just we can just simply do a binary search to find the position to insert this 55 and n60 okay in this case it will be somewhere here and we also check while we're doing the binary search if this one has any overlap with the existing range okay right so then we will need like a data structure to maintain these things right uh i think in java there's like this data structure called the tree map where you can just which will be a perfect fit in this situation but since i'm using python uh python doesn't have such uh data structure so um so what we will do here is we will be implementing like a binary search tree by ourselves so how does this binary search tree work i mean we so the first item the first book event will always be our route so in this case uh let me have another example here let's say the first booking will be uh be from 30 to 250 so this will be our root note and now let's have like uh another one came in so let's say that the next one is 10 to 20. okay so basically every time when we see a note we do a comparison basically first is if the uh if the new end is smaller then this node starts then we know okay so we need to go to the left side and same thing for the right side right basically and if the new start is greater than the nodes then the nodes end then we need to go to the right side okay so we keep going left and right and then we'll do a recursive call of that insert function until none of the conditions match right let's say we uh so in this for example this one basically if we see a 10 so in this case 10 20 is smaller than 20 smaller than 30 so which means we need to go to the left and basically okay then we see okay that does the left has a note if it has a note then we'll be will be recursively calling that notes that knows like uh the insert method otherwise if this is empty we simply insert this one to 20. we insert this one to here okay and yeah and let's say the next one is 15 to 25 okay so let's see this is the next one um okay then we also start from the root because every time when we do the insert we'll start from start starting from the root now this time same thing right so because 25 is smaller than 30 and then we will go to the left side so that now the card node is 10 to 20 and none of these two conditions is satisfied because 25 is not smaller than 10 and this 15 is not smaller it's not greater than 20 right so we which means so that means this one has an overlap with the current node we will just return false in this case basically we're not adding this node to our binary search tree okay yeah base i think that's basically the idea here and let's try to code these things here yeah things so for that let's create like a node structure here right class node and uh so we'll be having like a few things here so for a tree node in this case we're gonna have to start sorry um to have a node we need to have like the constructor first okay in this case it's going to be self start and end right and then start equals to start self dot end equals to end and we're going to have a left and right so at the beginning left and right are just empty none and then we will be needing like a insert method here okay so self dot uh basically we're trying to insert a note right so what are we going to check here because we're trying to insert this node to the current node here right like i said we just do a check basically if um if note so the first case we use we're going to the left so the going to left means uh if the notes end is smaller or equal than the uh self start right so and then we will be we'll go to the lab we go to left so we do a basically if not note left okay if this node doesn't have a left we simply do what we simply just assign this one to the left equals to the node and we and then we return true right because if there is nothing on the left that means it means that okay we can simply we can safely append this node to this tree okay else what do we do else here so if the left node is not empty it's not now then what do we do a recursive call okay it was soft dot what left uh sorry not south left yeah it's not this note okay uh basically if the current node left is not empty right and then we do a self load self dot labs dot insert okay we return here right so i think you guys uh i understand this right basically if the left node is not it's not empty we just keep trying we basically will we'll go to that path and try to insert the node under that cell under that node okay and same thing and i'll save i'll see if it sound it's uh this and this one is the right path so right path means um if the node if self doubt and yeah if self end is smaller than the uh then the note dot start right so if that's the case same thing we go to the left or the right side and self dot right equals to node and then we return true else return self dot right dot insert node okay and else like i said if none of things none of the conditions mat are is math are made then it means that we have a overlap here we simply return fast yeah so uh root right and our root will be equals to none i think yeah so and here what we will do is uh basically if not self dot root right we simply do a self dot root equals to a node um start and end okay else simply re return we simply return self dot root dot uh insert okay so the insert will be a note so which means we'll be having like a note here again right start and end yeah i think that's that should do it let's try to run it uh return true here okay yeah so yeah because here i forgot to return to yeah i think basically that's pretty much this right basically we're maintaining like a binary search tree with a key is like the start and end so at any time if that the range is smaller than the current range we go to left otherwise we go to right we keep doing this a recursive call right until we find an invalid node which means until this node has a overlap which means this is going to be the thing we check for the overlapping here and then we simply return fast so with this kind of algorithm we uh we improve our time complexity from o n square to o and log n right because the n is still the end time but for each insert since we're doing a binary search instead of n we'll be having like log n here okay yeah and space yeah space complex is it's one we don't we're not maintaining uh space complexity uh i think it's the it's also on because we're maintaining like uh unsized unknowns okay the size of n of a tree right for each node we will have like a class here to store each node yeah so and the tricky part for this is just we have to do a recursive call of node itself that's why we'll be we need to uh we need to like implement this insert function inside this node class okay so that we can do a recursive call on either the left or the right note okay um yeah and i the rest is just like nothing right so if it's not empty if it's empty we just return true and it re initiates the root otherwise we try to insert cool i think that's it that's pretty much it is what i want to talk about for this problem i hope guys you guys can learn this like how to implement this binary search tree yeah the key point is the uh maintain maintaining a key so in this case start and end but for the others it might not it might be something else but the key the point is we have we need a key right we need the key value to tell us when to go left and when to go right okay and then the left and right of course and other than that it's just the build this left node or the right node and try to do this recursive insert so this is this part is just like a template just remember this one cool guys thank you so much for watching the videos and stay tuned see you guys soon bye | My Calendar I | my-calendar-i | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**.
A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.).
The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`.
Implement the `MyCalendar` class:
* `MyCalendar()` Initializes the calendar object.
* `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar.
**Example 1:**
**Input**
\[ "MyCalendar ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\]
**Output**
\[null, true, false, true\]
**Explanation**
MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20); // return True
myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.
**Constraints:**
* `0 <= start < end <= 109`
* At most `1000` calls will be made to `book`. | Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added. | Design,Segment Tree,Ordered Set | Medium | 731,732 |
201 | hello and welcome to another video in this video we're going to be doing bitwise and of a numbers range and in the problem you're given a left and right that represent a range and you want to turn the bitwise and of all the numbers in that range inclusive so for example for five and seven you want to Output four because five is represented like this is six and this is seven so if you're not familiar with the bitwise and basically in order for the bitwise and of a range to be a one every single number in that column has to be a one so here this number is not a one so this is zero also and this is all one so one zero so this is four for z it's zero and for one and this thing it's zero and so you can't do this in a Brute Force like you can't just say like let me take every number from left to right and bitwise and because this is too big of a constraint so this won't pass in linear time so you have to basically kind of go back to this thing where if you take the bitwise and of a bunch of numbers if any like let's say we're looking at this bit here if any number has this bit set to zero then the bitwise and of everything with that bit will be zero so that's kind of what you're looking for you're essentially looking for like for a given bit is there a number in my range that is set to zero and also your result will always be less than or equal to left because if left is some number let's just say is like six and right is any bigger number or sorry six and right is any bigger number like let's say right has a one bit over here and then whatever over here because left doesn't have a one bit here this bit can never be one so you can't have a result bigger than left because if the right number is bigger like I said um this bit for the left will always be zero so this bit in the result will always be zero and if this bit is the same for these two numbers that means that in order for the right number to be bigger um this has to have some bits over here on this left side on that the other one doesn't and either way um whatever the left one has it will always be less so the idea so basically when you and two numbers so if you and a and b and you will never make a number bigger than a or b you will always either make the smaller of the numbers or um something smaller than both of them so that's kind of idea anding numbers never makes a bigger number so if you and a bunch of numbers in a Range your result will always be left or smaller now there is like a solution in the tutorial which I think is really weird and kind of hard to come up with using like some prefix thing so I'm going to instead um show a solution it's a lot more intuitive that you can actually come up with in a real interview so let's go through it so here I have a bunch of numbers this is just 0 to 15 um written in binary so this is like 0 one Toth and so on so what you can recognize is if you let's just take a look at like one bit at a time so this rightmost bit this is the two to the zero bit you can see how it alternates so whenever we have a one every other number goes to zero so we know if we have a one here like let's just say we have some number let's say we have a number like any number with a one here this just means it's odd right so let's say we have like nine we know that and this is our left we know that if our right is 10 or more than this bit at the end will always be zero right because whenever it's a one the next number makes it zero so we can make this assumption that for the rightmost bit whenever it is a one if the greater or if num + one if the greater or if num + one if the greater or if num + one exists then the and of those will be zero right because if like if we're on this number here if this is our left if this ex if this is our right um then these two numbers anded this bit right here will be zero right because like I said in order for this to be a one all of these have to be a one so whenever you have a one on the rightmost side if as long as you literally as long as the right doesn't equal to the left as long as it's bigger like any range here will always have one number with a zero over here right so the only way it's not is this now let take a look at the second bit so whenever we have a one at the most it takes two numbers to turn that into a zero right so like let's say we're on this number let's say this is our left this number over here takes this bit and turns it into a zero right so at most whenever this is a one at most it takes two numbers like the two greater numbers right if this is like 0o 1 two three and so on right four five and all the way down to 15 so that's what you can recognize so for the second bit at most it's two but it might also be one like let's say this is our left and this is the bit here the next number turns that into a zero so we can recognize that for the second bit at most two numbers are needed right like farther down like if we have a left so to turn um needed to turn this into a zero so if we have a number let's say any number with the spit on like six we know that if we have eight as well then we know for sure that at the end this number this like here will be zero because it takes two numbers farther down to turn into a zero now you might need less like let's say we're at seven if we have seven and eight then we don't even need two numbers down right so seven and eight also works and I'll take a look at the next bit and hopefully you're kind of getting to see the pattern so for this bit over here this third bit it takes at most four numbers to turn this into a zero right so this took at least at most one number this took at most two numbers this takes at least or at most four numbers right so if um let's say we are on this bit here so if we're on this four if left so let's say left is four if right is eight then this number will turn into a zero so you could see this is eight right here and this is left this would be left so you can see because this is in the range right if you and four with eight this bit will be zero so we know for sure that if our left is X then if right is x + 4 we know for then if right is x + 4 we know for then if right is x + 4 we know for sure that the third bit will be zero and then similarly going back to our first example so if left is X for first bit we know that if right is x + one then this know that if right is x + one then this know that if right is x + one then this bit will be zero for sure in the total land then for the second bit we know that if right is X+ 2 then we know for that if right is X+ 2 then we know for that if right is X+ 2 then we know for sure this bit will be zero the second bit will be zero then for the third bit it's X+ 4 and so on it's X+ 4 and so on it's X+ 4 and so on now the only other thing so you can literally do that right you can say like for sure I know that if I have some number from my left I can just figure out like okay the left most bit if I have l+ one then if I have L plus 2 then have l+ one then if I have L plus 2 then have l+ one then if I have L plus 2 then if I have L plus 4 then if I have L Plus 8 and so on you can just go down like bit by bit and you know like the max range you need to have that bit be a zero and you can do that literally bit by bit and we'll show that later but like I said you might need less numbers so for example if left is seven and right is eight here seven or actually let's label a couple more of these so six 7even 8 so if left is seven and right is eight we also have all of these bits on these two bits on that take at most two or four operations but here or not two or four operations you need at most four numbers down but here right is only one number down and this is still turning it into a zero so the thing you're missing here is for a given bit you need to figure out like what's the actual value right like this is two to the 0er which is 1 2 to the one which is two to two which is four but whenever you have like let's say you're on this bit be if you just look at everything that's on the right so the right is 11 one now when you add one all of these turn to zero so the thing we're missing here is not only like at most it'll be four but at least it will be four minus whatever the total is to the right of that bit right because when whenever that whole total is all ones when we add one that this bit will turn is zero whenever this total is this we have to add two for this to be zero whenever this we have to add three and so on so as a general equation we can write this down now so for a given left with some set one bit right in order for that bit to be zero in the final result the number that has to exist that has to be in the range is left plus two to the whatever bit we're on right so two to the bit we're on minus sum of the um all the bits before that so sum of all the bits to the right of it so sum of the bits to the right so meaning now we can like basically predict anything we want so let's kind of use this to show some examples of things so let's say we are on a number like five and we're on this bit here and we want to know okay we have a left of five so what number has to be in our ra range right what's the smallest number that has to be in our range for this bit to be zero well let's take a look at our equation so it's left which is five plus two to the whatever bit we're on so this is two to the two right cuz 2 to the 0 2 to the 1 2 the two is 2 this is four minus the sum to the right of this bit because basically whenever as this grows we need less numbers to turn this into a zero right because once this is one in this case then when we add just one this turns into a zero and if this was like a one over here and so on we'll go into those but essentially yeah so this is 5 + 4 minus the sum to the right of the + 4 minus the sum to the right of the + 4 minus the sum to the right of the bit which is just one so the number we need to have is 9 - one so the number we need to have is 9 - one so the number we need to have is 9 - 1 which is 8 so if our left is five and we have eight which right here if our WR is eight or bigger this bit will be zero in the final result and we can do this for a couple more examples so let's use maybe like this bit here so like what number do we need over here let's look at this leftmost bit here so our number here is nine so this is our left plus this bit value so this is 2 to the 1 2 3 so eight minus the sum of everything to the right because like I said once this sum as it grows you need less numbers to make this into a zero so this sum here is just one so it's going to be 9 + 8 - is just one so it's going to be 9 + 8 - is just one so it's going to be 9 + 8 - 1 so 9 + 7 which is 1 so 9 + 7 which is 1 so 9 + 7 which is 16 so when we get to this 16 that's when this bit turns into a zero and you can kind of see how that's going to work out right because you see all these numbers go down so this is 10 11 12 13 14 15 now finally when you get to 16 it will be one and then this will be a zero so the first number that you need to make this into a zero is 16 so you can basically use this equation to go through all of the bits in your left number and if your bits in your left number are zeros then the bits in the result will also be zero but if your bit is a one then you just calculate okay what's the smallest number in my range that I need for the one to be my final result and if I have that then you can just turn that bit into a zero okay so let's look at this example of this five and seven to kind of show what this is going to be so left is five right is seven so we're going to do the bitwise of the five so F bitwise of the five is just this and we're going to like go through this formula for this number so for this bit here we're going to check like what's the value so the value is just one so the number we need our right to contain or range to contain to make this value zero in the result is just five plus the value of the bit which is one minus the sum to the right of this which is just zero so we need a six to make this a zero in the result and we have a seven so six is fine so we'll have our result down here we'll just make it all zeros for now then we look at our next one bit every zero bit in the left will be a zero bit in the result because remember we can make we can never make our numbers bigger so now we look at this bit over here and this bit has a value of um four actually I think I drew this incorrectly yeah so instead of the a five is actually just this right yeah so five is just this so this part was correct but this part so that here's a four and we basically check okay so we have a four so remember our formula is take the left plus the value of the bit which is four minus the sum to the right which is one and it makes sense right because if this was like this then it would take four numbers to make this into a zero right because this is four so the next time this is a zero would be eight but as you increase this right part you get closer and closer to turning this into a zero because after this becomes one then when you add one this becomes a zero so as you add here you need less numbers to turn this into a zero so that's why when this is a one you need one less number so that's why it's this because it's going to go one then two then three then finally transform so 5+ 4 minus one so we have transform so 5+ 4 minus one so we have transform so 5+ 4 minus one so we have eight here and then we check do we have eight well right is only seven so eight is not in the range so this one will persist and this one will not because six is in the range so our final result here will be eight oh sorry four and you can see that is the result here so that's kind of the idea behind it um once you draw out these numbers you can see how they alternate and then you can figure out well I just really need to know like how long they take to alternate and every bit will take two to the power of the bit to alternate minus the total to the right because as you're adding numbers to the right you're getting closer and closer to flipping that bit value and yeah so we can code that up so we're going to use a couple variables you can probably clean this up but it's fine we're going to have a result variable we just set it to zero we'll have an i and the reason we'll have an i because the way we're going to get every bit is we'll just um have a one and we're going to shift it some number of bits to get it to match up to the right index so we'll start with shifting a one zero bits so one will be over here then we'll like shift it one bit to get it to be over here shift the two bits to get it to be over here and so on and this will let us um this will let us like set bits of our final result alternatively I guess you could like shift your result or something but I'm not going to do that so we're going to have a right total because like I said when we get a bit we are going to get the total to the right and this total will only um grow so like let's say our number is six like when we're on this bit it'll be zero when we're on this bit we'll have like this value and then we're on this bit we'll add like another value and so on so this total is just like a cumulative Su that we can keep track of and then we're going to make a copy of our left variable and we are going to get the rightmost bit by bit and check if it's a one or a zero so for example if we have like five is um this right so we're going to say like let's get this value then let's shift it to the right so essentially get rid of this then let's get this value shifted to the right and so on you can probably do this cleaner but this is just how I did it so we're going to have left or L is going to be a copy of left and we're going to say while this is greater than zero let's just keep getting the rightmost bit so if L and one that means that the bit is set so then we need to check what's the number that we need for this to be zero in the result and check if it's in the range so we can say if left plus oh we need one more variable which is going to be the power of two we're currently on so the power of two so this would be like two to the 0o two to the one two to the two and so on so our power of two will just be one for now and this is not like the power of two this is more like two to the zero right so this is going to be two to zero then every iteration of the loop we'll just multiply this by two so if left plus power of two minus the right total is greater than right that means that our right is not in the range right so if we calculate some number here like eight and our right is only seven that means this number is not in the range so if this number is not in the range then this will be one in our result so we can result or equal one shifted um shifted left I times so it'll start being shifted left zero times so like if we have this result basically one is going to start over here and when we or these together we'll get this and if we shift this one like one time let's say then the one will be over here and then when we order these together we'll get this and so on if we shift it twice it'll be over here if I roll This Together get this so it'll basically just set the correct bit in the result then finally what we need to do is we need to update our total so our right total we will now add the one value here so we will say plus equals power of two because if this bit was a one bit then this is going to add to our right total of sum right so like if this was set we'll have the value here and then when we check the bits to the we check bits to the left of that we're going to have this like total here so we're going to add the power of two and then we are also going to multiply our power of two by two right because we'll have like two to the zero two to the one and so on so we can just multiply by two that way we don't have to keep getting powers of two over and over although it doesn't really matter because like the most can be is like 2 to the 30th so technically this doesn't really save much like you can just do 2 to the 30th this is more good when you need to do two to like the million or something this is more useful um so then we need to take our copy of left and shift it to the right because we just used that bit we did everything we needed and we need to increment our index for the bit that we're going to use to set in the result and finally return result and yeah I do think this is a lot more intuitive than the uh let's see it looks like okay I do think this is a lot more intuitive than the solution provided in the editorial because I think that one they just have a huge leap where like I don't think it's intuitive at all and people are posting like I wouldn't come up with this in an interview but I think this kind of thing noticing this pattern that like my one alternates every you know two to the X and then I can kind of get a pattern here so if you're not seeing these patterns just draw out a few numbers and see if you can spot them and I think it's like pretty reasonable to come up with this one then in an interview definitely not super easy um definitely if you're not familiar with bit manipulation it's definitely going to be pretty tough like if you haven't done a lot of problems but if you have done bit manipulation problems I think this is like not too bad um yeah so time it's basically all one and space basically one cuz essentially we're just going through the bits of one number right we're only going through the bits of our left number um one by one so that like at most it's like 30 bits so that's why like this whole runtime stuff doesn't really matter because one Solutions just come down to like how many variables do you use or some kind of stupid stuff so it's not super important as long as you have a one solution and yeah let me know if any of this was confus confusing hopefully it was clear I don't know how much depth to go into on bit manipulation problems cuz I've done a lot but um if this was confusing or if you need clarification anything just feel free to write in the comments and yeah thanks for watching and I'll see you in the next one | Bitwise AND of Numbers Range | bitwise-and-of-numbers-range | Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1` | null | Bit Manipulation | Medium | null |
368 | okay 368 largest his largest divisible was subset given a self distinct positive integers find the largest subset such that every parent s sub I and a sub J of elements in the subset satisfy as I mod a sub J 0 s sub j sy 0 if the multiple solutions returning return any subset is fine okay so 1 2 3 give you a 1/2 or 1/3 because 23 are give you a 1/2 or 1/3 because 23 are give you a 1/2 or 1/3 because 23 are relatively prime to each other right so you basically one a set in which kind of I don't know how to phrase it in the mathematically way precisely but I you want the largest set such that all the numbers are factors of other numbers in this set yes and I mean just hmm trying to think of it with sorting yeah it means everywhere sorting so I think first thing I would do is sort to give the problem some structure I mean I think some of this is intuition and maybe I could articulate it a little bit better I think the first thing is that some whoops my soda popped but uh-oh but uh-oh but uh-oh tell me that's really going pop anyway so the first thing I would do is kind of sort of create structure in the problem then the intuition I have is that you want to go from you want to create these subsets from smaller to bigger and in this case you actually need to create output I mean because you can always imagine a similar variant of the problem in which you only need a number then you don't need to but I think this actually it's just the longest path in the dag and as long as you sort and sorting creates this kind of easier to digest directed miss of the graph so that you can kind of create long as longest paths in a graph in you know what Yumiko in basically with dynamic programming and that gives you n square time I don't know if that's fast enough depending on how they raised it but that's what I mean so the sorting it actually gets dominated by it down anyway and the things you can do to make longest path in a dag one faster than n square we may or may not explore that depending on calendar constraints I'm going to just did a naive one first and fix some diagram and if not that will kind of create the explicit graph a little bit to kind of speed things up even though sometimes it might not work depending on how dense the graph is so we'll see but yeah first bubble sort I always mix sort and sordid and all those things in five funds I'm just double checking okay I see you do this okay well I mean okay I gave it a sordid input so that actually might not mean anything let's test this real quick okay so that looks okay cool as another web sorted we I'm wanting to know is that our in dynamic programming sometimes don't need to kind of weeks we construct a path in this case you do so we need to create a little bit of structure before that so that's fine though it may be maybe we could also clean it up later with there in theory more classes instead of it which we'll talk about later okay I always get confused about x-range off I always get confused about x-range off I always get confused about x-range off by one or someone like that I'm just checking now before I dip and taken to Nobu tipper okay so this seems okay okay I just print this one I'll bring a little slow and deliberate right now but I definitely to kind of show up my understanding of the API is to be honest or like just not understanding but for familiarly I spent a while and I need to kind of practice a little bit I may be at some points to more streams but okay that looks good guys actually I guess want me to set it up yes hmm yeah because yeah so I think one thing that I don't I think I jumped a little bit ahead is that if X my P is zero then like let's say I think I jumped ahead a little bit I think if there's a thing where like effects might be zero right then if there's a see that much a is zero there's a sort of a transitive property and that's kind of why this kind of works yeah and I think I just needed to point out that transitive property of modding because in this case this implies that C also might be zero as well yeah okay and in because we sorted it beforehand I can only go one way I know that no qualm statement it in theory goes either way but because we create a structure where you know the biggest number look yeah bigger number will come later we only needed to worry about things like this in one direction right so now we're checking that yeah if the jave element can be extended with two by the element okay and then now we have two we can draw well yeah okay mmm yeah so just taking care of some edge cases but otherwise and now we have to be constructive way someone like that when it real quick mmm that's not quick let me also sort this away first I guess doesn't an action need to be sorted but uh okay that's two don't get along this way hey screw that up what is truly were just too soon mmm that's real I need to do one more maybe he doesn't know if I won that's fine no but also I need to pen not most but numbers of most that's how that goes I mean it's still off by one but it should get you closer okay to what Erica okay and this actually should not occur and that's their literary civil elements and input because by default you should get by default you get yeah at least one case where this is true if I'm just more than zero so I was just thinking okay so okay that looks good I mean I'm a story for fun even though I think technically we don't need to but okay nice to try another couple of examples just in case okay you know God just had a bunch of random numbers I don't know what yeah it doesn't tell you how big uh how Victor way can be I'm just gonna punch little bit more and then maybe yeah 312 okay so I mean we're gonna cook to a quick some in gonna slow some it I guess not good okay so accept it so yeah I think for me I yeah so this is the medium problem largest divisible subset I mean I kind of solved it in 34 lines I think this one's a little tricky I think I mean the tag portion actually is pretty good I mean that it recently good for not reasonably a problem but it's recently this reasonably standard problem that should be in your arsenal for better for worse I don't know how much I agree with is an individual question but dynamic programming using dag that's you know this code is pretty standard and you have to reconstruct the path which is maybe a little bit less tender but still doable with some practice I mean the part that get me a little bit is that you have to know a little bit about number theory to kind of get this one which is kind of I mean number theory is fun and I actually enjoy playing around number theory not intent I'm a favor like programming contest type of number theory from time to time but these are things that like unless you're doing cryptography or something like that like I don't know if it's something that's obvious to people if you know it and maybe could reasonably for reasonable reason for doing an interview but it's still kind of feel like I don't know just something that people don't think about normally or even you know read about and I think the key thing is noting that to be frank the transitive property that I kind of skipped through a little bit I brought it up and obviously I didn't even prove it or anything which you can kind of do and time but it's also something that like for me I'd call it intuition / practice for me I'd call it intuition / practice for me I'd call it intuition / practice over a long time but I don't think that's a fair thing to kind of assume candidates with I don't know easier to reasonably flew away like I mean or like it does have good predictive power for me in a sense then like a candidate might take two minutes of it I go yeah I mean you know I play around with math event and they may think that then we'd get the transfer part of it very quickly or they may take you know twenty minutes doing something like just not making the assumption and it creates more work kind of for the interviewer to be like maybe poke them in the right direction or maybe just give them a straight hand to be like hey this is a property that you should consider but it's still like but for me if you have to do that and it doesn't really have good protective power and I don't think and that's like I said you're doing some security stuff with cryptography stuff or something like that it's reasonable to expect anyone to you know given come across in a good way or even you know if you take algorithms 101 or whatever whenever this gets torn nowadays like I don't think that comes up that much I could be wrong and leave some comments and I'm wrong but that's my feeling but other than that in theory this is a good form other than there are the number theory part only because I as an individual I do like taking a couple of kind of fundamental pieces and kind of putting them together and maybe interesting ways and so that like you know you don't want it out a problem that has you don't want a problem that has like oh yeah you need to know max flow or some like grad level algorithm you know just to prove that they know and know certain like almost trivial right I mean you and to some of that you could debate how far to take that energy because to some people given any algorithm is trivial but that's it besides the point I guess but maybe my mind yeah other than maybe this stuff about the number theory I think taking a couple of kind of cone quote off-the-shelf kind of cone quote off-the-shelf kind of cone quote off-the-shelf algorithms and can put them together those are platforms I'd like to kind of challenge my interviewee interviewees well yeah so I think I inferior I mean I personally like this problem as a result but I also would use this as an interviewer just because I mean I don't know like I said like I would never expect my interviewees to know number theory and this I don't know - vocals theory and this I don't know - vocals theory and this I don't know - vocals for it and it's very clear or maybe even finance or something like that and they asked for very weird math things but uh yeah so that's my opinion otherwise I mean otherwise like you know I solve everything with 34 lines and I even five ways a little bit goes so yeah so I think it's doable | Largest Divisible Subset | largest-divisible-subset | Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**. | null | Array,Math,Dynamic Programming,Sorting | Medium | null |
707 | hey everyone welcome back and let's write some more neat code today so today let's solve designing a linked list as you may know a linked list is a pretty simple data structure where we have some nodes and typically every single node will have some type of value like one or two in this case the values are integers and also nodes will have pointers at the very least every node will have a next pointer which could be connected to a another node and then that node could also have a next pointer that may not be connected to a node and then this would be considered the end of the linked list and we could also have a previous pointer going from every single node backwards and in the context of this problem actually we have the choice of whether we want to use a singly length list or a doubly linked list and in this problem I'll be implementing the doubly linked list because it's a bit more complicated and I think that's probably what qualifies this problem as being a medium problem so I'll quickly go over what exactly we're going to be implementing and then we're going to start so first we need a instructor for our linked list class that's pretty straightforward we also want a get function which will get the node at some particular index and in this problem things are zero index so the first node would be the zeroth position the next node would be the first position and then two and then three et cetera just like an array now we do have to deal with some edge cases in the case that this index doesn't even exist in this problem if we were trying to look for index two well there is no a node at index two in that case we would return a default value of negative one we also want to be able to insert nodes in this case at the head of the link list so we're just given a value not a node we could be given the value 3 for example and we want to insert a new node with the value 3 at the beginning of our linked list so if this is our linked list we want to insert a new node here give it a value three connect it with you know the next node and then this will be the new head of our linked list next similarly we have ADD at tail that's pretty much the same thing except we would be inserting the node over here and then connecting it would be the end of the linked list we don't have to worry about edge cases with this one either but the next two are probably what make this problem a bit difficult we have plenty of edge cases with these ones one let's start with ADD at index we're given an index and a value we want to insert a node so if this was called with index 0 and value three we would just be inserting at the head just like we did previously because in index 0 when they say we're inserting at this index we're inserting before the indexed node so if we're given a value of zero for the index we're inserting before the zeroth note so we would be inserting at the head instead if for the index we were given one then we would be inserting before this node because this is zero this is one then we would be inserting in the middle over here and we'll talk about how we're going to do that but mainly we're going to be needing to update these pointers to something like this now the other one we have is delete at index actually before we move on to that if the index is greater than the length the node will not be inserted so that is an edge case that we have to worry about so if we were given index of zero that's perfectly fine if we're given index of one that's fine and if we're given index 2 that's also fine because we're inserting before index two so we would insert the node right here but if we were given a value of 3 then that is out of bounds lastly we have delete at Index this one is a bit more straightforward I think than adding that index because if we're given an index 0 this one then we're going to be deleting this node if we're given an index one we're deleting this node if we're given index two that is out of bounds there's nothing to delete here in that case we don't have to do anything now let's move on to the solution okay so now let's code it up and we'll also be going through the visualization of the solution as we do it because it's pretty helpful when we're doing a lot of like pointer manipulation things can get kind of tricky first thing we want to do is of course create a node class where we have a next pointer and a previous pointer so I'm going to go ahead and do that so we're going to have a class I'm just going to call it list node and it's going to have a pretty basic construct after where we're just given a value and we're going to initialize that value and we can by default set the previous pointer equal to null and the next pointer also equal to null now let's move on to the Constructor of the linked list class what I'm going to do is initialize two nodes actually a left node which is just going to be given a value of 0 to start with and also a write node which is going to be given a value of zero as well and I'm also going to connect these nodes together so left dot next is going to point at the right node and right the previous is going to point at the left note so what we've done so far is basically we've created two nodes over here that are connected with each other the reason I'm drawing them so far apart is because these are going to be our dummy node so we have a left dummy node and a right dummy node this is not required to solve this problem and this is not something most likely you'll come up with by yourself it's just a very helpful technique to deal with lengthless problems you'll see why I'm doing this later on but basically it allows us to not have to deal with edge cases because think about it when we have like an empty linked list like this one inserting into the linked list is basically just creating a node and then having something point at it and saying this is the new head of our linked list and when we have multiple nodes and we want to delete the head of our length list it's different because we don't actually have to move any pointers over here we're just saying that now this is our new head but when we have dummy nodes then every single operation is dealing with a node that is in the middle of the linked list so whether we're removing this node or inserting a node everything is going on in the middle of the linked list we don't have to deal with any edge cases at the beginning or at the end and imagine our real doubly linked list looks something like this where the blue nodes are the actual nodes that have real values that we inserted into the linked list and these are just kind of our dummy nodes now our get function thankfully is pretty straightforward remember that this is our zeroth node and this is our first note so when we're given an index we just want to return that value so we're going to start at this node here and then keep incrementing our pointer until we've reached the correct index the way I like to do that is so I'm going to set current equal to self dot left dot next and basically while our current pointer is non-null because we know we possibly is non-null because we know we possibly is non-null because we know we possibly could go out of bounds and our index is greater than zero the reason I'm doing it this way is because I prefer to just decrement our index by one every single time the alternative is to just declare a second variable but I'd rather just do it this more simple way and we're going to be incrementing our pointer every time so current is going to be current dot next now you might think can we just go ahead and return current.val not go ahead and return current.val not go ahead and return current.val not necessarily because we have to make sure that we haven't gone out of bounds so we have to say if car is non-null and we have to say if car is non-null and we have to say if car is non-null and we have to make sure that we haven't reached the end of the length list because remember the way we're doing it we have a dummy node what happens if our current pointer ends over here at this dummy node we definitely don't want to return that value that's considered being out of bounds we're also going to say if current is not equal to self dot right and lastly our index has to be equal to zero because otherwise that means maybe this Loop exited before we were able to reach the index that we wanted to reach that would happen if our linked list was too small to delete this index that means this index did not exist in that case we can return this value otherwise we're going to return negative one okay so now moving on to adding at head thankfully this is pretty straightforward we hardly have to even focus on the drawing in this case mainly what we're going to do is given the value that we're given let's say the value is X we're going to create this node we're going to take the left pointer and then move its pointer to point at this new node and I forgot to draw the previous pointer of this one so sorry about that but assuming that it has a previous pointer point in here what we're going to do is move that pointer to also point at the new node so its previous pointer is pointing here now and of course this new node that we're creating I'll make it blue because it's a real node we're going to be having it's an exponent point at this guy in its previous pointer point at this guy pretty simple and we'll be doing the exact same thing when we work on ADD at tail which is basically going to be inserting a new node here where this pointer is going to go here and this is going to point back this is going to point here and this is going to point backwards so I'm going to create a new node and call it just node and I'm also going to do this I'm going to create a next value and a previous value these are the next and previous nodes we know the next node is going to be self dot left dot next and we know that the previous node is just going to be self dot left so this way I think it makes it easier than having to use like these names because otherwise it can get kind of confusing if we just focus on the current node that we're inserting the next node and the previous node it's pretty simple so we'll have previous dot next point at node we'll have next dot previous point at the node and we'll have the node's next pointer pointing at the next node and we'll have the node's previous pointer pointing at the previous node as you can tell this is pretty simple I even prefer to kind of condense them into a single line like move these two into the same line and these two into the same line but that doesn't really matter and since this is very similar to adding that tail I'm just going to go ahead and copy and paste it the main difference though is that our next node in this case is going to be self dot right and our previous node is going to be self dot write dot previous otherwise these pointer manipulations are pretty much exactly the same you could even create a helper function if you wanted to simplify this now let's move on to the more difficult ones add at index and delete at index they're pretty similar we'll start with ADD at index so what we're going to do is start our current pointer here at the first node and we're going to keep incrementing until we get to the correct index that we want to be at now what happens if we reach this in index that's going to be fine because remember we're not inserting at this index we're inserting before this index so if our pointer ends here we're going to insert the node over here if our pointer ends over here we're going to insert the node over here if the r pointer ends over here we're going to insert the node here but if our pointer goes out of bounds past the dummy node then we can't insert a node so what we're going to do set our current pointer equal to self dot left dot next while current is non-null and dot next while current is non-null and dot next while current is non-null and index is greater than zero I'm going to decrement our index that's very important we don't want to get stuck and we're going to increment our current dot next well our current one or two the current dot next and now how do we know if we're actually at a valid position well first of all if our current pointer is non-null and our index is equal to is non-null and our index is equal to is non-null and our index is equal to zero in that case what are we going to do well I'm gonna first copy and paste what we did up above because it's very similar so let's copy and paste it and first we're create getting a new node with the value that we're given as a parameter what's going to be the next node in this case well current is going to be the next node so we're going to set this to occur what's going to be the previous node in this case well it's going to be Cur dot previous and then after that this is again pretty much the exact same you can see that once you get used to this you can pretty much just turn your brain off and then you know just go on autopilot now moving on to delete at index it's going to be very similar to this with the main difference being that in our drawing we are actually deleting the node itself that our pointer lands at so if this is the node that we're deleting then we delete it but what happens if our pointer ends at this position at the dummy node well we're definitely not deleting the dummy note it's not a valid node so in that case we would not want to perform the delete operation similarly if we end up out of bounds we still don't want to delete because obviously we can't delete in that case so now coding it up I'm just gonna you know copy and paste this entire thing because it's again pretty similar we're going to keep incrementing our current pointer until we get to the position then we're going to check is our current pointer non-null and not our current pointer non-null and not our current pointer non-null and not only that but is our current winner not equal to self dot right because in that case we also can't delete and our index should be equal to zero that means we were able to actually reach the position that we wanted to reach and at this point we can perform the delete in this case the next node is going to be current dot next and the previous node is going to be current dot previous just like we already have and then this is you know just making that insertion actually no we don't want to insert in this case we want to delete how do we do that though well first of all we probably don't want to actually create a new node you can see that maybe you don't want to turn your brain off too much so given a previous pointer and a next pointer the way to delete a node like this one is pretty simple we don't even have to update this node's pointers we just have to take the previous nodes next pointer and change it and we also have to update the next node's previous pointer and then change that as well this next pointer will be pointing at the next node and this previous pointer will be pointing at this note and then as far as we know this node doesn't even exist technically we do have a memory leak if we don't delete this node but we usually don't have to worry about that encoding interviews or on late code so then moving back to the code what I'm going to do is say next dot previous is going to be equal to previous and previous dot next is going to be equal to next and that is pretty much the entire code I'm going to go ahead and submit it to make sure that it works and as you can see yes it does and it is pretty efficient so I really hope that this video was helpful if it was please like And subscribe if you'd like to view the entire code you can do so on neco.io the entire code you can do so on neco.io the entire code you can do so on neco.io we should also have solutions for the other most common languages thank you for watching and hopefully I'll see you pretty soon | Design Linked List | design-linked-list | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute `prev` to indicate the previous node in the linked list. Assume all nodes in the linked list are **0-indexed**.
Implement the `MyLinkedList` class:
* `MyLinkedList()` Initializes the `MyLinkedList` object.
* `int get(int index)` Get the value of the `indexth` node in the linked list. If the index is invalid, return `-1`.
* `void addAtHead(int val)` Add a node of value `val` before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
* `void addAtTail(int val)` Append a node of value `val` as the last element of the linked list.
* `void addAtIndex(int index, int val)` Add a node of value `val` before the `indexth` node in the linked list. If `index` equals the length of the linked list, the node will be appended to the end of the linked list. If `index` is greater than the length, the node **will not be inserted**.
* `void deleteAtIndex(int index)` Delete the `indexth` node in the linked list, if the index is valid.
**Example 1:**
**Input**
\[ "MyLinkedList ", "addAtHead ", "addAtTail ", "addAtIndex ", "get ", "deleteAtIndex ", "get "\]
\[\[\], \[1\], \[3\], \[1, 2\], \[1\], \[1\], \[1\]\]
**Output**
\[null, null, null, null, 2, null, 3\]
**Explanation**
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
myLinkedList.get(1); // return 2
myLinkedList.deleteAtIndex(1); // now the linked list is 1->3
myLinkedList.get(1); // return 3
**Constraints:**
* `0 <= index, val <= 1000`
* Please do not use the built-in LinkedList library.
* At most `2000` calls will be made to `get`, `addAtHead`, `addAtTail`, `addAtIndex` and `deleteAtIndex`. | null | null | Medium | null |
1,466 | hello guys let's look at this problem this is from leadcore sweetly challenge let's see how we can solve this problem so problem statement says that we are given in cities which are numbered from 0 to n minus 1 and there are roads between these cities and there exactly n minus 1 roads and the connections are representing that there is a road from this node to this node that means if 0 & this node to this node that means if 0 & this node to this node that means if 0 & 1 are each is at Apple in this particular connections array then means there is an edge directing from 0 to 1 and similarly for 2 0 that means there is an aid that acting from 4 to 0 what we need to do is we need to ensure that by adding some roads into this particular connections graph so that from starting from any node we can reach to node 0 so if we take this example here what we were supposed to do is we needed to ensure that if we start from 1 we should be able to reach this 0 and we start from 3 we should be able to reach 0 and so on for each node so if we for example let's consider 1 for now if we start from 1 we would never be able to reach 0 because there is no age directing from 1 to 0 or directly or indirectly similarly for 3 and we can start from 2 and reach till 3 but again as we came we have seen previously that 3 cannot be I mean from 3 we can not reach 0 so starting from 2 also we cannot reach similarly from 5 we cannot go to 4 and from 4 so 4 is the only road that can lead to 0 without any modification so the minimum number of changes that we can do here is just as you can see the gray in the red ones we can just change the direction here and in that way we would be able to reach from each node to this node 0 similarly here also you can just consider in the third example both of them are already pointing to 0 so we can reach to 0 from each of them it is also given that this graph will not have any cycle and it's not given but yeah with n nodes and n minus 1 ages between them we can never have a 1 cycle also yeah the total number of nodes are given to be 10 to power 4 there will not be any self connection so let's consider how we can solve this one so in the current state when the graph given graph is a directed one it will be hard for us to do a DFS or BFS and try to find try to reach from one node to other node but what we can do is we can try to add fake node fake edges to each of these relations in the different order as well like for example if we were given 1 2 3 s we could we should add let me choose a different color so that we can distinguish we should add one more node start one more age starting from 3 to 1 then here as well we can add one more node starting from 3 to 2 so that it becomes bi-directional so that it's it becomes bi-directional so that it's it becomes bi-directional so that it's easy for us to start from one node and reach the other node let me just add for now and we'll explain you why we why do we need this so once we have all the edges as a bi-directional lace we will edges as a bi-directional lace we will edges as a bi-directional lace we will start our DFS starting from 0 and check whether we can reach from 0 to all the nodes following the vacates or the original 8 so if we are going to follow the original age this means that if there were no fake age we would have not reached from that breaker node to 0 node so for example if we were to reach from 0 to 1 then we know that using the original age we know that it would not be possible to come back to zero without this fake age so in this case we would increase the counter by one similarly now that we are at one and we would check that because now we have made one zero to one as a possible age we will not consider for the previous one we will just simply check for one now what happens for one all the nodes which are achievable from three from one we'll check for them so for one there is only one node which is achievable from three and that is also using the original one that means if there was no fake age we would have never reached back to one and then back to zero starting from the three so in this case also we would need one more age so we will increase our counter to two and so let me just add these colors here so that we can know so here we would need this one and also here we would need this one now we have reached three and we have ensured that there are ages there are roads to reach from one to zero and three to zero we will check for three from three we would need the fake age to reach to two that means there was an age is existing from four to from two to reach to three already so we would not increase this counter here and then we'll recurse back in using the DFS in the DFS itself what are we going to do now is we are going to get further another branch of starting from zero so the other branch is also using the fake age to reach the next node that is 4 so if we are not using the original node that means there was already an age coming from this node to 0 and so we will not need to add another edge here so we will just we have just ensured that they from 4 we can always is to 0 without adding any a strand H there now from 4 we have a direct originalist to 5 which is its child node so out not child we can say Addison no and then what it means is that we cannot come back from 5 to 4 without this fake age so we would need one extra is starting from 5 till 4 here so overall it added 3 nodes 3 and 3 more edges to the existing a existing network so that from starting from each node we will be able to travel back to 0 as we have seen that if we have this bidirectional networking instead of unidirectional network and if we start from 0 that means do a DFS from 0 what is the pattern that we are following is if we are following the original node to reach from 0 to the register node we will add a cost otherwise we will not add a cost so when making this age I mean when making this graph we can simply add a weight to each is like when we can add a weight from 0 to 1 as 1 and then we can add a weight from 1 to 0 as 0 similarly from 1 to 3 the weight of this edge should be 1 and then for the fake one it should be 0 here as well starting from 3 to 2 it should be 0 and starting from 2 to 3 it should be 1 so for each original age we will add weight 1 and for each fake age we can ID we can add a weight 0 so how these add edges can be added and all these fake weights that can be given to these ages let's take a look at the code to understand it better so I have already solved this one and let me just walk you through the code so we are given these connections and we can have a vector of array to create our to maintain our graph and this these are the edges the X denotes an age and zero tells you the edge is diverging from X of zero is the source node and X of 1 is a target node for each edge so we have been given that there is an edge existing from X of 0 to X of 1 so we will simply add 1 at this particular edge to our network 2 that means to our graph and as we have discussed that we can we should add a cost of this way that means our weight of this age as 1 because this is the original one and then we can add a reverse age that will be a fake one with the cost 0 and then what we are going to do is we are going to do a DFS where we will maintain a global answer and you will start the DFS from 0 to 0 I mean 0 node and the parent node should be 0 so we are going to do a DFS and we'll check if the adjacent one is not a parent 1 because now we have a bidirectional is so it can lead into an infinite loop of child node calling it's panic itself if so we will just ignore if this one is the parent itself otherwise for all the adjacent node we will check whether the second value that means if this particular age is a original one through which we have traveled to this particular adjacent node then we will increase down our answer otherwise we will just keep it that much only and do a DFS from the adjacent node so yeah I hope I was able to explain you guys please hit the like button and subscribe to my channel if you like my lord thanks for watching this video guys | Reorder Routes to Make All Paths Lead to the City Zero | jump-game-v | There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by `connections` where `connections[i] = [ai, bi]` represents a road from city `ai` to city `bi`.
This year, there will be a big event in the capital (city `0`), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city `0`. Return the **minimum** number of edges changed.
It's **guaranteed** that each city can reach city `0` after reorder.
**Example 1:**
**Input:** n = 6, connections = \[\[0,1\],\[1,3\],\[2,3\],\[4,0\],\[4,5\]\]
**Output:** 3
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 2:**
**Input:** n = 5, connections = \[\[1,0\],\[1,2\],\[3,2\],\[3,4\]\]
**Output:** 2
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 3:**
**Input:** n = 3, connections = \[\[1,0\],\[2,0\]\]
**Output:** 0
**Constraints:**
* `2 <= n <= 5 * 104`
* `connections.length == n - 1`
* `connections[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i. | Array,Dynamic Programming,Sorting | Hard | 2001 |
1,673 | everyone welcome to day 24 january record challenge and today's question is find the most competitive subsequence in this question you are given an array and a positive integer k you need to identify the maximum the most competitive sub sequence of size k that is present in this input array and what are the rules for identifying whether one sub array subsequence is comp more competitive than the other subsequence it is the it is of a lower value than the other one for example 134 is more competitive than 135 because the first portion that they differ in the final number is 4 a 4 is less than 5 hence the first sub sequence is more competitive than the second one so what you need to do you need to identify uh the point you need to identify uh the most competitive sub sequence that is present in the input error under the size k one standard solution is to add to generate all the permutations all the subsequence of size k and then compare them all one by one using a prior maybe using a priority queue uh and finding out uh and removing the one that is of lower uh or lower uh this is less competitive which is of more value and rejecting that and accepting the one which is of lower value and more competitive in nature this is a start this is the first thought process that came to my mind when i read this question but we will not solve this by the standard by the brute force approach we will go by some other solution using stacks so let me just start the slideshow i have taken the similar example that was specified in the question two four three five four nine six and the size that we are looking for on the subsequence is four now let's calculate the total length of element that are present in the stack one three one two three four five six seven eight so in the resultant subsequence uh we need to remove a four elements from this input array we need to remove four elements from this input array eight minus four and if we are able to identify those four elements which one to remove we will get our lowest uh lowest valued subsequence which will be most competitive in nature so let's start with a variable uh that will tell us how many elements we are actually intended to remove and we will use stack so this is the variable that is maintaining that count how many elements are to be removed and uh let's iterate through the input array we got two the stack is empty pushed it into the queue then we got four uh pushed it into the queue since it is of higher value i will push it into the queue then we got three and three is of the lower value than the peak element that means we found one element that can be rejected up front because we are interested in this in the numbers that are of lower value so we'll compare the peak with the current element it is lower we'll remove this element and we'll add three to it decrease uh the count that we are the number of elements that are actually to be removed because we have removed one element and the count becomes three we move ahead in the next iteration we got three gets added we got five get started and then we have four we compare the top peak element with four it is of lower value it can be safely removed we add 4 and we decrease this count so now the number of elements that are to be removed is 2. you move ahead in the iteration you got 9 gets added to the stack and let's move ahead we got six we compare nine with six nine is of greater value can be safely removed we removed nine added six and reduce the count to one so what remains is one now and then what we have uh we have an increasing sequence in the stack so it's two three four and six till the time uh till the time the size of the stack doesn't become equal to k uh the input number that is given to us keep on removing uh the from the top of the stack so we were intended to have only four elements so we keep on removing other topmost elements because it will always be in a decreasing fashion so we removed this and this becomes our answer two three four so we identified the increasing subsequence of lowest value that is present in the stack and once we have that we removed all the elements from its top because it will be greater than a greater at the top and at the bottom we'll have the lower elements that are of size k and we can generate the answer using this these elements in the stack so i'll tell you i'll code in exactly the same fashion as i have talked about the algorithm and let's walk through the code now defining a new variable number of elements to be removed equals to nums.length removed equals to nums.length removed equals to nums.length minus k and let's define a new stack integer st new stack and let's start the iteration over the input array while the stack is not empty till the time the stack is not empty and the number of elements are to be removed is greater than zero and nums and st dot the top element of the stack turns out to be greater than the current element what we'll do we'll remove elements from the stack and we'll reduce the number of elements to be deleted because we found one element that is not the potential candidate for our answer once we are done with this we'll add all the elements in the stack which is the primary step and in case the stack size is still greater than k keep on removing from the stack next we'll build an answer array new int and what will be the size side would be k for integer i equals to k minus 1 i is greater than equal to 0 i plus i minus anus of i will adding in the backward direction because the top most element would be there on the top of the stack st dot pop and once we are done with this i'll return n s pretty simple and concise looks good let me just submit this accept it let me just talk about the time complexity of this approach time complexity order of n since you are iterating through the input array once the space complexity is also similar order of n because at max the stack can hold all the elements uh all the elements that are there in my input array if they if all of them are in increasing fashion thanks for watching video hope you enjoyed it | Find the Most Competitive Subsequence | find-the-most-competitive-subsequence | Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`.
**Example 1:**
**Input:** nums = \[3,5,2,6\], k = 2
**Output:** \[2,6\]
**Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive.
**Example 2:**
**Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4
**Output:** \[2,3,3,4\]
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `1 <= k <= nums.length` | null | null | Medium | null |
1,462 | hello friends welcome back to the channel hope you are doing great if you haven't subscribed to my channel yet please go ahead and subscribe i have created bunch of playlists to cover various categories of the problems such as trees graphs dynamic programming stacks queues linked list breadth first search depth first search binary search and so on please check them out i have put all the playlists in the description section below also i have uploaded the code for this particular problem to the github repository you can get the link from the description below this video let's jump into today's problem course schedule 4 there are a total of n courses you have to take label from zero to n minus one some courses may have direct prerequisites for example take course zero you have to take course one which is expressed as a pair one 0. so basically there are 0 to n minus 1 courses so n courses basically and there are prerequisites for some courses that's what it says right some courses may have prerequisites so the prerequisites are given as uh in the form of like a two dimensional array one zero that means in order to take course zero right you have to take the course one first that's what it is so you need to take course zero but before taking zero you need to take course one right so after taking one then only you can take course zero that's what it means given the total number of courses and a list of direct prerequisite pairs and a list of query pairs you should answer each for each query whether the course query of i0 is a prerequisite of course i 1 or not written a list of boolean the answers to the given queries so please note that if a course a is a prerequisite of b and if course b is a prerequisite of c then course a is a predicate of c so basically there is a transitivity relation that we are talking about here right so it says a is a prerequisite of b so that means you have to go through a to go through b right and then b is a prerequisite of c right so that means a is a becomes a prerequisite of c so it's not a direct so you will not so you probably will be given with ac and b c that's it so from here you need to actually deduce saying ac right so in the input this is only given input is only this one right only up till this but we have to deduce this ac right sorry a b this one a b is given and bc is given but you need to deduce ac is also a valid uh prerequisite saying in order to take c you need to take a also that is also a prerequisite that's what it says right please note that if a course a is prerequisite of b and course b is a predictive set of c then course a is a of c right so essentially c has two prerequisites that is a and b right but between a and b you should do a first and then b right so that's what it is right so there are transitive predictions so we just looked at only these three right so this could be going further right this can be going further so you need to reduce some of them will be given here but not all of them right so you need to deduce some of those uh relationships right the prerequisite relationship right so what we are going to do for this particular problem is we are going to have some slight imagination so imagine all the courses are nodes in a graph okay so all the courses so 0 to n minus 1. so that means your graph has n nodes labeled 0 to n minus 1 and prerequisite each prerequisite we are going to imagine it as a edge okay so that means there is an edge from one to zero or in this particular case there is an edge from a to b a b to c to d to e something like that so there are four edges in here in this case right so likewise there are prerequisites we are going to imagine them as edge in the graph and each course is a node in the graph right so those are the prerequisites for our problem solving for this particular question okay we are saying we will have a graph where nodes are courses and edges are prerequisites right so let's go and try to understand uh through an example so let's take a good example from whatever that is available okay let's go with example three this actually looks better graph than others the first or second right so we have essentially three courses named zero one and two so one need to be taken first before taking zero and 1 need to be taken before taking 2 and 2 need to be taken before taking 0 right so that's what it is so how many relationships are given here 3 so 1 2 so that means there is an edge from 1 to 2 this is the one and there is an edge from 1 to 0 this is 1 going up so 2 to 0 so this is also going to 2 to 0 and these are the prerequisite courses we will we are given with some queries to answer whether those are prerequisites or not right so let's say input is a b ah and bc right so with that we will have only this right so we are given with a b c we came up with this graph right so let me extend just so that's a graph right for our graph so a to b to c that's a graph and now the input was this one so now the query given we are given with query right so that's what we need to answer right so query if we are given with ac we should actually return true for this because a is a prerequisite of c by following this right so we written a true so that's what we have to return so the written what we are returning essentially here is the written list of boolean for given query so given there are some specific queries given for those queries we need to answer whether that is actually true a is a prequel of c so for this case yes we need to written true this is what we are going to deduce i said right so those things we are asked to deduce so in this particular case this is a graph so 1 is a prerequisite of 0 yes right so that is straight away since it is already given but 1 is a prerequisite of that is also true that is also given here right one is a prerequisite of 2 one is a prerequisite of 0 let's say 0 1 is there right let's say 0 1 for this particular zero one right so is zero prerequisite of one right is zero predicted of one from this graph it doesn't look like right so we will return a false right so that's uh that's what we need to come up with so there are since there are n different nodes right and there could be any number of uh edges right between those nodes so minimum will be at least n minus 1 edges will be there right minimum but maximum could be anything so there will be any number of edges that could be possible so in this case we have three nodes but three edges are there right in order to have them connected we need to have at least n minus one edges but in this part like a particular case we have more than n minus one or n edges in this case right so now what we are trying to do is if there is a path from given one node to another node so in since we are imagining the courses as nodes and prerequisites as edges what are those queries we can transform we have to see whether there is a path from a to c here in this case so we input is a to b to c and queries is ac right so that means what we are essentially trying to say is there a path from given node to the given node a to given node c so we know we have a path from a to b right a to b and we know we have path from b to c we have b to c but do we have a path from a to c yes a to b and b to c so that is a path from a to c also right so this itself is a path to a to c right so we will say that's the reason why we will say true right so let's say if a query was ba right so that means is there a path from b to a no so we will written false right so if the query was ba then is there a path of course there is a path from a to b but is there a path from b to a no in that case we will say written false so this is what we need to come up with so we don't uh actually limit the relationships to the whatever they are given in the input but we have to come up with whatever the possible transitive relationships also that is one task and then answer the queries whether there is a path from one node to another node in other words in the for the description right is there any prerequisite for prerequisite relationship between those two uh courses that are given as part of the queries so what we are going to do is for this particular problem we are going to employ a algorithm called floyd warshall's algorithm okay so floyd versus algorithm so this algorithm is known for ah finding the paths between more than one input node to more than one output nodes right so we are given with several queries right it's not just one query if it is a one query then we could go with a depth first search or best first search algorithm then we can just oh okay there is a path between two nodes or not and then be done with it right but we are given with bunch of queries not just one so in that case what we could do is we could do in a different approach also we could get a graph and then do uh depth for search for the queries of i 0 to i 1 is there a path between those two so we could go that way also right so we can do in two different ways build a graph and do depth for search do dfs between the query nodes right that's one approach this is first approach we will say and we this is second approach we will say right so for flood versus one approach second one is building a graph and doing a dfs between the query nodes so the reason why i did not uh showcase this uh the second approach in this particular uh video is if you are doing do dfs between two nodes right you will need to do uh you will probably need to traverse the same paths multiple times so that's why that algorithm becomes much slower than the flawed versions algorithm right so we you need to possibly do the dfs between those nodes so many number of times we don't know how many of them right so we have to cross through so many nodes so for example in this particular tracer you start from a and go to b and then go to b to c right but what if there is something called so from b to ah from b to d is there and from d to e is there from e to f is there and not just there and from d let's say there is something called g right so from g till h right so if there is that kind of graph is there then you will have to traverse through all those different nodes right you come to a to b now you for all the b nodes so b d so you need to traverse d c let's say the a to c it's not a to c but it is a to f let's say right in this case yes there is a path you will say true but if there is no path let's say right in that case you don't say it right so a to b and you transfer a to b to c a to b to d to e to f d to g d g to h so you'll need to traverse so much of the graph for a given two set of phase so in some cases you might have to traverse the entire graph for given two nodes right one graph one thing could be so let's say a and h right so you need to traverse the entire graph almost to come to a conclusion saying okay a to h there is a uh there is a path right so for each dfs you will have to travel through all the n nodes right so you have to build a graph that is going to take some time and then you do dfs between each of those uh nodes in the queries right so it becomes a much slower approach that's the reason why i did not showcase as part of this video so we will look at the floyd versions algorithm as part of this video right so what is the floyd versus algorithm so this algorithm is known for count known for coming up with the paths between any two nodes in the graph if there exists of course right if there doesn't exist it doesn't come with the path but if there exists it's going to come with a path okay there is a path and if you want if there are weights in the path or if there are like things like that right so in this particular case there is no weight it's just the connectivity whether they are just connected or not true or false but floyd warf's algorithm has much more applications to find out whether there is a minimum or the shortest path between any two nodes so you will be able to use the flawed versus algorithm to calculate the shortest path between two nodes two given nodes uh in a graph but imagine it's not if you are given with only just two nodes and try to calculate the path right floyd warface is not the way to go just do a dfs you will be done with it because you all you have to do is just only one iteration of dfs but if you have many things like in our queries array we have to come up our answer many queries not just one query if it is one query get done with dfs that's it but if there are more queries dfs is not feasible since you will have to traverse almost entire graphs through the dfs that's the reason why we will go with flood virtuals right so it is good application good algorithm to come up with the paths between any two nodes assuming you are doing that multiple times okay let's get into the algorithm and the code right so for this flawed versus algorithm i am going to declare a two dimensional array which is equal to the length of n by n right so in this particular case we have declared a boolean ah two dimensional array which is called reachable which is equal to n by n right so i am initializing all of them saying okay they are not able to reach from one node to another node that is the initialization right so now by going through the prerequisites whatever they are there in this right in this fashion one zero i will going to mark those nodes as true right so now i know those courses are prerequisites imagine so i am talking in terms of the graph basically saying reachability and all but in the graph courses are nodes and prerequisites are edges right so now reachability of prerequisite to the course is true that means for this course that is a prerequisite i am marking it as a true right so that is the initialization so still we are in the initialization approach only so we have initialized the reachable all of them to false but only turn the prerequisites to true so now we will go through the flood version right so that's the flood virtual we are going to go through so it's a simple fl algorithm so what it's going to say is see if two nodes are already connected or not if two nodes are already not connected try to see if any name if you can connect through any neighbors right so the neighbors are not just the same node or the other node but all other n minus two nodes are neighbors right so if you have n nodes you have uh node one and node two you are trying to see if they are connected right so if they are connected you would have already got from the prerequisites array but now that we you don't have the previous you've already filled it that means these two are not connected and you're trying to find if there is a connection possible so you are going to take the help from all the different neighbors of n1 and n2 and come up with if there is a connection so that's what is flood version right so you have the node i and j so that means you have a node i and node j and you made sure they are not connected that's what i am saying so if they are not reachable if they are reachable already don't worry about it so they are reachable you do not have to enter this for loop or whatsoever right so flawed versions algorithm need not be applied since they're already connected but if they're already connected means already directly connected okay so when i'm saying already connected already directly connected if they are not connected directly or indirectly that's when we are going to enter this if loop right so what we are saying is take a neighbor okay and see if that neighbor is connected to node 2 so this is node 1's neighbor right so node 1 never that same neighbor with node 2 right so it's something like this let me represent n1 right so there is some k node right so from k to n2 right so if there is a connection like that what we are going to say is yes if these two connections are true just put all this that result saying okay n one and two can be connected so this is a simple understanding of the flood versions right so now that if you go through this particular algorithm right you come up you have all the nodes which can be connected directly or indirectly from floyd balsals algorithm right so now after this execution you know in reachable what are reachable from i to j now what you're doing to do is you have just queries right just see if they are connected right if they're connected just put true if they are not connected put false that's it so now go through the length of the queue right and from and to so just check in the reachable if they are true or false just put it there in the answer finally written the answer that's it so that's how we are going to solve this particular uh problem with the help of the flawed virtuals algorithm let's go ahead and look at the time and space complexity right before going right so time space time what is the time so we know there are n nodes right that is given in the description itself right so there are n nodes so in order to fill this particular matrix reachable we are taking n by n right n into n so order of n square so n into n that is the time complexity for this and here we are going through all the prerequisites so plus m right plus m and so coming down we are going through these three for loop right so that will be r of n into n right so order of n right and then we are going through the number of queries which we don't know right so the number of queries i'll just i'm just going to call it as order of q right so that will be the total time complexity for this particular algorithm if you say so order of n plus m plus order of n plus q so n square plus m plus n cube plus q so ah for a given n ah assuming q is less than n cube right then we will say the maximum time complexity is going to take is order of n cube right because floyd versus is order of enqueue we are trying to find the paths between all the possible nodes right so if you have n nodes you are trying to see if there is a path from any node to any node like that's why the floyd marshall's algorithm is going to take order of n cube time so you could simply say the time complexity for this particular algorithm will be order of n cube but it depends on the number of queries right and the number of uh prerequisites also so you cannot rule out m and q so one thing that you can rule out from here is since this is much better bigger much smaller than order of n cube you can possibly take this away right you can possibly take this away and call this as a total time complexity so i am going to leave like right there for that time complicated let's go to space complexity so are we using an extra space here so obviously we are using the reachable that is the extra space and we are using m and is there anything yes we are using the answer array right so we are good using order of n into n space right that is for the reachable and this is just a variable irrespective of the length it does not matter and then is there any more space we are using yes so q is just a variable we don't we do not care much but this is answer array we are using right so what is the length of the answer array since we don't know the number of queries it is going to have we are going to call it as order of q right so the space complexity for this particular algorithm is order of n square plus q right so since we don't know q if q is like very minimal right we just say order of n square but since q is unknown yet we will keep right there order of n plus q as the space complexity right so if you have any further questions for this particular problem right please post them in the comment section below this video i will get back to you as soon as i can i have posted the code for this particular problem to the github repository you can find the link in the description below this video also all the playlists are also available in the description you can check them out if you haven't subscribed to my channel please go ahead and subscribe and share among your friends as much as you can please click on the bell icon so that you will be notified about all my future videos thank you for watching i will be back with another video very soon till then stay safe goodbye | Course Schedule IV | list-the-products-ordered-in-a-period | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`.
* For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`.
Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`.
You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not.
Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\]
**Output:** \[false,true\]
**Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\]
**Output:** \[false,false\]
**Explanation:** There are no prerequisites, and each course is independent.
**Example 3:**
**Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\]
**Output:** \[true,true\]
**Constraints:**
* `2 <= numCourses <= 100`
* `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* All the pairs `[ai, bi]` are **unique**.
* The prerequisites graph has no cycles.
* `1 <= queries.length <= 104`
* `0 <= ui, vi <= n - 1`
* `ui != vi` | null | Database | Easy | null |
218 | all right so this question is the skyline problem so uh if you have time just real quick but uh the problem is pretty much uh simple so you have building eye so uh building a ray right i mean the beauty and eye is going to represent left right and height okay so i'm going to start the drawing so this is about 2 represent the left and i represent the indian so starting andy and this is h which is high which is 10 right so this is pretty much the idea right so how do we actually need to do this so uh the problem is that when we uh just imagine there is a light like shiny from the left right so basically it's like this and then um you want to know where is the point uh top of the top point uh where you where your building ends right so it definitely is right over here right you're building top left point and uh and end with here right and then you go over here and this is not the top left building so the top left building is right over here and then you keep going and just imagine the light you would just keep shining right something here right so just imagine there's a light okay and now you just keep going and then up right over here is where the light ending right then keep going keep on and then here you hear the light and here's the light keep going this is light and this is the light right so this is a solution so you want to return one two three four five six seven point right two four six seven yes so now we want to know how do we actually do this question so again i'm gonna draw this uh draw this again so uh you need to return what you need to return this of this so this is the main thing right and then uh but beforehand right we need to know how uh we have to sort this building rate based on the height right so um i'm going to have a list and then inside of this is an array and just pushing every single uh building array right building array i into the uh just i mean just pushing the height okay so i'm going to name this off in array height right and then i'm going to just sort i mean sorry i'm going to push the in 1d array building to height when the when you're starting when the starting point so this is a starting so a new int i will say what the starting index right start this with what negative height index so i'm going to just push negative h for the start index and the ending with the positive h okay so this is actually helping me at the end i when i want to find out why is the minimum height i mean because we're pushing a negative right so minimum height is going to be sorting it's going to be from negative to positive right so uh this would be the pretty uh helpful when you have a negative edge and polish distinguished right so uh once again i'm gonna i'm going to just draw it again so um so i have a list of in right so list of thing is pretty important also what also i need to sort to solve the h which is height uh based on what uh basically in this a bit based on the in this uh indexes right because the index 0 is what in this zero is either what starting and or ending right so there are two scenarios right when the index are not intersect right so you want to say okay smallest two graders okay so which is what uh a zero minus b zero right and but for what happens if the if index are the same if the a0 and b0 are the same we want to know which one is what which one we want to keep right because uh there are actually two point you want to know which one you should keep and definitely not this one right and then when we add into the list of array right we add a negative value right so this is what just imagine this is uh just imagine this is what negative alpha so imagine this one is going to be one negative 10 this one is negative 5 something like this right sorry negative 7 so negative 10 is that definitely less than negative 7 right so when we uh when we are comparing right we want negative ten first then negative seven seconds right so this is how it is right so it's still going to be one uh the smallest two graders right so once we have it then we need a priority queue so priority queue is going to be what sort based on the integer right and this is going to push my height my index one so in this one is height in this video is what sorting ending right this is index and then this is in this one height all right and then i need to push p q into the height into the priority queue but in the priority queue it's going to be what the positive number so we will just push the negative value negative index one value into the pq and then when you remove that it's going to be about pop all the height positive all right because pq is always positive number right so this is a tricky point and then we basically just keep comparing right and then we will definitely have one we will definitely have a current maps and pre-maps so have a current maps and pre-maps so have a current maps and pre-maps so pre-maps pre-maps pre-maps and maps will start pointing zero right starting from zero and if i have a send uh send x i mean sorry same coordinate i'm not worried about but if i have different height right i need to update right so this is 10 so when my current max that's not equal to the pre max right but that's not equal to pre max i need to work i need to add a coordinate which is for starting with the height right so the height is for permanent flat so i would say uh p0 something at least right i would say current into my list of lists and then i will just what i will have to update my free max to the furnace because this transit because this one is updated and this is pretty much it so let me stop recording and then follow along and this is going to be a little bit difficult for sure but don't ever give up so list of this integer and i definitely need to return result right so i need a list of in array right i'm gonna go going to call height and then i will definitely traverse my building i'm just called b beauty and then i'm going to just add height and pass in the video so the index 0 is definitely what it's definitely going to be a negative value for e2 okay and hi e1 comma positive b2 right so the zero index is going to be one left starting and then this one represents ending uh and there's two represent the height right so once i have it right i'm gonna sort based on the height and then i'm going to sort based on the height with the index so if they are if a 0 is equal to b 0 right this is going to be based on height right height smallest right so if they are not equal so is so much easier so i'm going to say a0 minus p0 but if they are equal i'm going to still going to give smallest values so imagine just imagine a0 and b0 so this is what this is a0 this is also b0 right and uh this is definitely like maybe the 10 something like this and this is like negative seven right because we push a negative value into it right and then if they are not equal uh it's going to be like this case right something like this all right so smaller two greatest so this definitely work but uh if they are equal if that equation is this case right so i need to still comparing as small as the greatest all right so let's just keep doing this now i have a priority queue and this is going to be sort based on the height right and again this is going to be my mistake this is because i want to push a positive number no matter what into it right and initial value this one is zero and i have a pre max it's gonna be zero i need to traverse i'm sorting um my sorting height right so i'm gonna say h hi all right so if mine so okay so i'm going to say i another index case here right and height is going to be h1 right i'm saying this right uh actually i cannot say height anymore because i put it pretty well okay sometimes right so if my call it's less than zero which is the starting that's right which is the starting index right uh i push the negative value into it right so which is starting this i'm gonna i'm going to push this into the party here so p q so since it's negative value right i need to convert it right so i need to say negative h 1 right which is negative 4 right actually i don't want my timing i don't want to create a local variable so i'm just going to do like this so this is what you add a negative which is positive value right and then if not so if this is not a negative value which means what is ending right and this is already positive right so i can just say that which is po h1 right okay now i need to know like is my current max is equal to p q p so i'm actually keep checking so uh just imagine so this is high of 10 so right 2 negative 10 and then this is 3 negative 15 and then what seven positive fifteen nine ten so in the priority queue i have a positive value only so i will initially have zero and i will have one i will have ten right and then i will have 15 right so i really want so when i push the proof when i add a pq the first interval so the pq.p is the first interval so the pq.p is the first interval so the pq.p is definitely 10 right because it's sorted right i'll sort it so 10 so i would say current mass equal to 10 so 10 that's not equal to probability of pre-max right pre-match was 10 i pre-max right pre-match was 10 i pre-max right pre-match was 10 i premixed was zero right zero doesn't equal to ten right so i need to add this point into this right three max because i'm equal to current uh i will have to add a result so it's something like this uh this was right i would say b uh h u right comma current max i'm adding the coordinate into it right and then once i have it right i need to update my pre-maps i need to update my pre-maps i need to update my pre-maps into my current right so if there's another point which is starting at the same current height of a diagram so i'm not going to add in right because this is my top left right just imagine if there is a point so this is my top left so if there is a point right over here i'm not going to add this accordingly into the result because this is not the top left in the diagram and this is going to be pretty much the solution so just keep traversing so you're adding you're removing you're adding removing and then you pick and to check the supreme pre-match equal to current let me run it might be a error somewhere oh no error okay something all right so let's talk about the timing space so this is what this is a space this is also a space this is space but it's constant so the space is going to be these two so it's going to be all of them right the space is all of them so time is just time this is also time so the time this is also b represent end of the building and this is going still going to be what all of uh all of b log b is sorting right b log b and this is what this is uh you determine the height right and i would say it's shorter uh shorter than this one right collection dot store because for this one you have every single interval and this one is only for height and in this one this is all of h represent this one right and in the remove it's going to be log uh it's going to be logan right so you can say although all of h logan and i mean sorry h is actually equal to n right and represent at the end of the building so it's going to be unknown and then space is all of n so this is pretty much my solution and it's a little bit hard to understand and stop holding and you have to know the logic right so this is a tricky part and i read over all the people answer so i kind of like struggle a lot for this question and this is my solution um how i understand all the people answer and i will see you next time bye | The Skyline Problem | the-skyline-problem | A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_.
The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`:
* `lefti` is the x coordinate of the left edge of the `ith` building.
* `righti` is the x coordinate of the right edge of the `ith` building.
* `heighti` is the height of the `ith` building.
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`.
The **skyline** should be represented as a list of "key points " **sorted by their x-coordinate** in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.
**Note:** There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]`
**Example 1:**
**Input:** buildings = \[\[2,9,10\],\[3,7,15\],\[5,12,12\],\[15,20,10\],\[19,24,8\]\]
**Output:** \[\[2,10\],\[3,15\],\[7,12\],\[12,0\],\[15,10\],\[20,8\],\[24,0\]\]
**Explanation:**
Figure A shows the buildings of the input.
Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.
**Example 2:**
**Input:** buildings = \[\[0,2,3\],\[2,5,3\]\]
**Output:** \[\[0,3\],\[5,0\]\]
**Constraints:**
* `1 <= buildings.length <= 104`
* `0 <= lefti < righti <= 231 - 1`
* `1 <= heighti <= 231 - 1`
* `buildings` is sorted by `lefti` in non-decreasing order. | null | Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set | Hard | 699 |
1,847 | hey everybody this is larry this is me golfing q4 of the bi-weekly contest me golfing q4 of the bi-weekly contest me golfing q4 of the bi-weekly contest 50 uh 51st closest room uh hit the like button in the subscribe button join me on discord let me know what you think about this farm and on this contest and so forth um so this is basically so this is a pattern that comes up in lead code but to be honest it's a little bit awkward because it doesn't really come up that much in real life in a way because in real life um if you have these kind of problems um the queries are usually not given to you all at the same time meaning that these queries are not live these are kind of dead curries so and one and the cool thing about that queries is that you can process them in any way that you want so with that in mind um because if these are live queries this become a much harder problem but because these are dead queries the way to answer the queries is that we come up with another way of entering the queries we basically go we basically answer the queries in the order of going from max to min or in terms of room size um for example 3 we put nothing in the set yet um and then rather two so then now we go okay room two is room two id is good one three id is good so then this one has an answer and then lastly we process the one and everything's in so that's basically the idea is just processing the queries in that way and then we slowly add in the rooms to be available and then we do a binary search on that array and i'll show you how i did in code but that's basically the idea um yeah so basically i sold them into events and i wanted to sort by uh max room size so that's hence the negative uh so my events have you know um so that's the room size that's the type that's the index of the room and this is just i needed an extra thingy it doesn't have anything um while on for queries we sort by room size we have a type of one for queries and then p is um the preferred uh i from id so this is what we're going to look at and then index is the index of the query so that we can know where to put the answer and that's basically the core idea we saw all the events we keep track of all the numbers um all the room numbers that we care about if it if the and of course we have this type here um that we also sort by to keep in mind so that the zero will always come before the first meaning that if the room size are the same we process all the rooms first before we run the curse and that's deliberate um but yeah so if the type is zero we add it to the available room so this is this sl it's just available rooms that we can uh go to um otherwise if type is one then this is a query if this is a query we go okay let's do a binary search on the available rooms um and if this is inside the list because if this is either because i think this can return the length of sl which means that it is um c is bigger than the largest element then we set it to the uh element otherwise it's uh negative one and then i and then basically because if you do a binary search you um the idea here is that we do binary search you want to look at the next number and the previous number because you're in between two numbers so i just do index minus one i do the same thing to see if it's uh whatever uh this is within bounds and if it is and then if then i just check to see the distance um and the distance is smaller than you go to then we set this to the current index um and because this index is always going to be smaller because sf index is always going to be smaller than this index we just set it to this index if it's equal to um and then we just set the answer and of course you know we call that c in this case is the it is the preferred thing so that's what we search because that's the prefer uh id um and d is the index in it for a query so then we um yeah we put it back in the answer way in the right place and that's pretty much it at the very end we return the answer which is the entire right and that's pretty much it so what is the complexity of this right well we do so defense so that is going to be and you can actually technically uh sort these independently and then just do some uh math to kind of keep track i sometimes do it that way this time i did it this way so yeah um but in any case let's say n is equal to the number of rooms and q is equal to queries then this is this sorting is going to be o of um n plus q log n plus q uh just for the sorting and for each of um these operations this is going to be o of log n just by adding it's going to be log n and two binaries are just a log n so for this is going to be o of q but i guess over q times log n so it gets dominated by the sorting of all these events as i mentioned you can actually do a little bit better and get this down um to n log n plus q log q um or something like that by sorting these independently uh these are just like very minor factors so yeah in terms of space well it's going to be linear space because we just keep track of the uh well linear for q and we have you know defense will have one item for uh the size of the input which is the number of items in rooms and cues so it's going to be linear um and this is just you know yeah um that's all i have for this problem let me know what you think and you can watch me solve it live during the contest next right ideas so at least so oh my god let's call this that's not so oh backwards all right cool looper slaughter uh yeah thanks for watching hit the like button as a subscriber and join me in discord let me know what you think about today's barman contest and so forth and whatever uh i will see y'all later bye take care of yourself stay good stay healthy and take good mental health bye | Closest Room | largest-subarray-length-k | There is a hotel with `n` rooms. The rooms are represented by a 2D integer array `rooms` where `rooms[i] = [roomIdi, sizei]` denotes that there is a room with room number `roomIdi` and size equal to `sizei`. Each `roomIdi` is guaranteed to be **unique**.
You are also given `k` queries in a 2D array `queries` where `queries[j] = [preferredj, minSizej]`. The answer to the `jth` query is the room number `id` of a room such that:
* The room has a size of **at least** `minSizej`, and
* `abs(id - preferredj)` is **minimized**, where `abs(x)` is the absolute value of `x`.
If there is a **tie** in the absolute difference, then use the room with the **smallest** such `id`. If there is **no such room**, the answer is `-1`.
Return _an array_ `answer` _of length_ `k` _where_ `answer[j]` _contains the answer to the_ `jth` _query_.
**Example 1:**
**Input:** rooms = \[\[2,2\],\[1,2\],\[3,2\]\], queries = \[\[3,1\],\[3,3\],\[5,2\]\]
**Output:** \[3,-1,3\]
**Explanation:** The answers to the queries are as follows:
Query = \[3,1\]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.
Query = \[3,3\]: There are no rooms with a size of at least 3, so the answer is -1.
Query = \[5,2\]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.
**Example 2:**
**Input:** rooms = \[\[1,4\],\[2,3\],\[3,5\],\[4,1\],\[5,2\]\], queries = \[\[2,3\],\[2,4\],\[2,5\]\]
**Output:** \[2,1,3\]
**Explanation:** The answers to the queries are as follows:
Query = \[2,3\]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.
Query = \[2,4\]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.
Query = \[2,5\]: Room number 3 is the only room with a size of at least 5. The answer is 3.
**Constraints:**
* `n == rooms.length`
* `1 <= n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= roomIdi, preferredj <= 107`
* `1 <= sizei, minSizej <= 107` | Search for the largest integer in the range [0, n - k] This integer is the first element in the subarray. You should take it with the k - 1 elements after it. | Array,Greedy | Easy | null |
977 | whenever you see any problem on arrays what do you think we can start traversing the array from the beginning or we start reversing the array from the backwards right but we often forget that we can traverse this array from both the starting and the end simultaneously right and sometimes this approach can give you an efficient solution there is one such problem on lead code squares of a sorted array that explores this example hello friends welcome back to my channel first i will explain you this problem statement and we will look at some sample test cases next we will see how you can approach this problem using a brute force method and then we will see how you can optimize this solution going forward we will also do a dry run of the code so that you understand how all of this actually works in action without further ado let's get started let us quickly try to make sure that we are understanding the problem statement correctly in this problem you are given an integer array that is in a non-decreasing order that means the non-decreasing order that means the non-decreasing order that means the elements are arranged in an ascending order correct now you need to return me an array that has the squares of each number and that is also in a ascending order right what does that mean this looks pretty straightforward right let us look at the sample test cases now in our first test case i have the array 2 4 7 and 9. you can see that this array is in a non-decreasing order correct so now if i non-decreasing order correct so now if i non-decreasing order correct so now if i have to return an array that has the square of each number in a non-decreasing order what will i do i non-decreasing order what will i do i non-decreasing order what will i do i will just square each number correct and you can see that this array is also in an ascending order and all the elements are squared so this will be your answer right but there is a catch this array is an integer array right and integers could be both negative and positive for example in a test case number 2 we have this array right and you can see that it has negative elements and both positive elements right now this array is sorted in an ascending order correct but what happens when you square each of the elements this will become 16 then 1 then 0 then 9 and then 100 right if you notice this array is no longer in an ascending order right and that is because when you find the square of a negative number it will become positive so the square of minus 4 will be 16 this is a positive number right so the correct answer to this test case would be where you took care of all the negative numbers in a correct manner right now if you want to try this problem once again on your own feel free otherwise let us dive into the solution and see what we can do about it a good developer always tries to come up with a brute force solution first that is because a brute force solution guarantees you if a solution to a problem exists right so given this array what is the most naive or the brute-force way to approach naive or the brute-force way to approach naive or the brute-force way to approach this problem you need to find the squares right so in the first step what i'm just gonna do is i will square each of the elements and then i get this resultant array right now this array is not sorted what you can do as step number two you can just sort your array right and as soon as you sort it you will get your final resultant array right and this will be your answer but what is the problem with this approach this is a correct answer right when you try to sort your array the best time complexity that you can get would be order of n log n that will be the quick sort algorithm technique right but if you notice we never take any advantage of the fact that this array is already sorted right even if this array was in any order you would get your solution in order of n log n correct so definitely we need to find an optimal solution okay so let us take up one more sample array this array is even bigger and we will try to approach this problem in an efficient manner right so what is the first thing that you notice first of all you're gonna see that okay this array is in an ascending order right to the left you have the smallest element and to the right you have the largest element correct but if you notice closely there is a certain point or you can say somewhere middle in the array if you look closely all the elements towards the left are sorted in an increasing order where all of them are negative and towards the right all the elements are positive and they are sorted in a ascending order correct so what i have here is all these elements are sorted and all the elements to the left of this midpoint are sorted now you want the squares of all the elements right so first of all let us just square each element correct if you notice the same point once again all the elements to the right of this are sorted and all the elements to the left of this point are sorted correct now what can you do you can use the approach of two pointers to arrive at your ultimate sorted array what i am gonna do is i will have two pointers one that starts at the head and the other pointer that starts at the tail and using these head and tail pointers i can start to populate my final array to populate this array what i'm going to do is i will compare the head and the tail because i know that the most extreme elements will be on both of these ends right so either this will be the largest element or this will be the largest element right so i compare 49 and 100 is greater than 49 so what i'm just gonna do is i will copy 100 to the end of this result array and i will move my tail pointer one position back now repeat this process compare tail and head this time 49 is greater than 36 so what are you gonna do you will take this 49 and add it as the second last element in your result array and once you have added it move your head pointer one step ahead once again just repeat the same process compare 16 and 36 because 36 is larger i will put 36 in the next available position of my output array and i will take the tail pointer one place back just keep on repeating this process compare 16 and 9 16 is larger so place 16 over here so you can see how these head and tail pointers will keep on moving and ultimately they will converge at this middle point and this is where your iterations would stop and you will have ultimately retrieved your final output array just try to fill in these additional elements that i just added as an exercise for you now if you have understood this approach let us do a dry run of the code and see how this actually works on the left side of your screen you have the actual code to implement this solution and on the right i have an integer array that has both negative and positive integers and it is passed in as an input parameter to the function sorted squares oh and by the way this complete code and its theft cases are also available on my github profile you can find the link in the description below moving ahead with our dry run first of all we create a result array that will store all of our squares in a sorted order and its length will be the same as the input area length right so this is the array where i will store all of my results correct now what is the first thing that we do first of all we will square all of our elements so as soon as i square all these elements it will become 16 1 0 9 and 100 right now in the next step we assign two pointers a head and a tail so the head pointer points at the first element and the tail pointer points at the last element right that is where the zero and num length minus one comes from moving on what i need to do i need to place all of these elements in their correct positions right and to do that i will start a for loop which starts at the last position in my result array and goes all the way to 0. so i will be filling this result array from last all the way to the first element correct now what i'm going to do is i will compare this head and tail right we know that 100 is greater than 16 right so what do i will land in my else condition and i will assign this tail number to the last position once i do that 100 gets assigned at the last position and then what do i do a tail minus this will move the tail pointer from the last position to the second last position correct in the next iteration this loop runs again and this time i will be comparing 16 and 9. once this happens i will get 16 in my resultant array and the head pointer will move one step ahead similarly this loop will continue to go on and ultimately you will fill up your entire array right now the time complexity of this solution is order of n that is because we iterate through the entire array only once and the space complexity of this solution is also order of n that is because we create a result array that will store all of our squares i hope i was able to simplify the problem and its solution for you as per my final thoughts i just want to say two things first of all whenever you see any array or any problem that is given to you in a sorted order trust me you have to take advantage of that fact if you try to approach this problem in any conventional way or try to come around with a different solution there is a very high chance that you will exceed your time limits so always watch out for the fact that the problem is sorted and try to take advantage of it the next thing is whenever you are given two sorted lifts it is always a good idea to iterate through them simultaneously they could be in the same direction they could be in the reverse direction or they could be in a convergent direction and when you take advantage of these facts there is a very high chance that you will land at an efficient solution did you see any other problems which used the same two-pointer approach used the same two-pointer approach used the same two-pointer approach one such problem is merging of two sorted lifts right what other problems did you see can you come up with any other solutions tell me everything in the comment section below and i would love to discuss all of them with you would be also glad to know that a text-based be also glad to know that a text-based be also glad to know that a text-based explanation to this content is available on the website on the website on the website a pretty handy website for your programming needs as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where i can simplify programming for you also let me know what problem do you want me to solve next until then see ya | Squares of a Sorted Array | distinct-subsequences-ii | Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_.
**Example 1:**
**Input:** nums = \[-4,-1,0,3,10\]
**Output:** \[0,1,9,16,100\]
**Explanation:** After squaring, the array becomes \[16,1,0,9,100\].
After sorting, it becomes \[0,1,9,16,100\].
**Example 2:**
**Input:** nums = \[-7,-3,2,3,11\]
**Output:** \[4,9,9,49,121\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
**Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach? | null | String,Dynamic Programming | Hard | 2115 |
724 | Hai Tu ok hai, something special before this deception and if we want to talk, our channel is sponsored by Spots and Akhilesh Nice day, it does not come on its own, okay then you soon after getting a job, you have to pay YouTube 29337 jobs After salary, you must subscribe to these many benefits channel because Ling send that I am fine then you go 56001 pimp tube looking our questions 50 love basically this is quite distracting if you find some of your controversial Now in the good points of this year's time like if you ignore a little then the soldiers engaged in centos became top hindi then here the Italian is given fast like because it is very good egg point question so now as many as this But if you look at it, then you will get this question from the same question for 10 minutes because next is its meaning, you will see here in which it is not called, in that you will withdraw, add this question as platform here. The test is better that in the committee and in such a situation in the company's Robert, today my wife is free, pain is fine, this cream, we will roll it here, we do all the work, after this interview, we will see what is a question, meaning you have questions but certificate Patna test. Let me print the express what is my entry that setting it here and stuffing and break down that Greece has to Institute of Management Institute and what we have to do is here to Ajay okay till now we have Look at this, if you see what it is saying to us is that we have to tell the index like this. If you are standing on this next side, then like its A, we have to tell the address. If you are standing here then on the right side of it, whoever the person is with him and laddu. Which is their vegetable people heart, here I take this induction heater, lifting or zero one two three Lord Vishnu took oath to go to school, if you cross here, stand at a little distance here. Standing, okay, if its right side boils, then it is getting friends for this, how much is their time, okay, but understand in these, label, dip function in the internet, how much one is organized, what happened to it, should it be intact, which protein or else you will say, I will talk about this only. For Equilibrium Intact, I have written this here and that this has become liquid on Amazon. If you talk about the recipe, then search for the question paper Thandak Singh. You can see this here we have to subscribe to such and such. So let's subscribe one here and subscribe that you turn it on here and from here Okay, now let's see how to do this question So one time and let's make this water and put it on it and potatoes. Sugar and our value character value our tea 173 and 666 that 173 676 will work, first of all we will take out a lot of time, put a lot of our time, prefix, now I write in it that this much will come, complete 1783 level plug 6560, subscribe that I am your own God. Read and what will we do, we will start daily wear look and area austerity, okay, just used to be intoxicated, do strategic and protesting against ad, and will amaze our lips, if you refuse to kill your ad in the chapter, then left or only 2000 in April seventh Chapter will become one of his life cycle and he will remove the bank from this time. Even after becoming 28th, he has become seven. Okay, now send it in the lips, it is set and right time, remove the scrubbing, it is twenty, okay, relax, add the committee, how many eleven and Rajasthan message free remove kitna 117 now left semester course in it electromagnetic shockwave kitna ka 17th like did your next election left side written on this index first capability and if you die at night then you take it here second when run it will add saffron and Like I will add to right commission, before removing the negative, hair can be removed, before doing this, decide that your lips subscribe button is clicked, if they are equal, then the use of fun is diet, the problem is so much here, we had to apply here, okay so If we break it here, then it's okay, not here, I do plus caret and remove it. Increase it. Dear friend, that Android Vinod Khanna, consider it as 120 phase elections and on one side there is capacity. My favorite song is Scooter Karta. And in the chaos, let's take out the APS machine, so this is done, okay, I'll take out the printer, Mithali, you check the phone, fix your right 0 toe preparation, you will get the qualification, you go to one side, I'll look at where. Vivek Roy link she just added it to your laptop and I have added it to the ladies. Check what time is happening and remove this potato from the right time. I have removed it from the item on the left. Now see what. Your lips, we have only got liter of item, like we return curd and CID fuel, make roti and from here, done photo and no, if not found anywhere then we will get registration, but if we go here and there, then we will have to return body but husk, okay So what I am doing is that I am reading and checking that it is doing the right thing or not. It is okay. Contact Aishwarya. That's why I am installing the sample. Let's wait and see whether I am able to pass it or not. Seeing the treatment, am I able to understand it or not? Yes, yes, it is okay to do the right thing, that is a very basic question, after that even you are a supporter, that is, there is tension as to how to do it, is it okay, all this will go, thank you so much ] do it is done | Find Pivot Index | find-pivot-index | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. | Array,Prefix Sum | Easy | 560,2102,2369 |
3 | what solve leak code 3 longest substring without repeating characters or back to a classic leak code problem the third one so this one's pretty simple we're just given a string and we want to find the longest sub screen without any repeating characters right like how these three don't have any duplicate characters ABC this one has two A's so this would not count as a substring without repeating characters and we only need to return the length of this substring so the first idea that comes to my mind at least is so just check every single substring check if it has any duplicates if it doesn't then it then we're just going to take the longest one of those strings and return the length so how would that algorithm run okay first we'd start at a we want to get every substring starting at a so just this one a well that doesn't have any duplicates a B that doesn't have any duplicates a C that doesn't have any duplicates either and then we get to this first duplicate a we have two A's now but remember we're checking every single sub screen starting at this first a so we're gonna keep this algorithm going even though we don't have to every substring we get after that like see how we're doing it every single substring after is also gonna have duplicates so do we even need to check all of these starting at value a this is the repeated work that we're gonna eliminate with our very fundamental technique the sliding window so we want to only check sub strings without any repeated characters so let's actually just do that let's make sure that our window right our sub array our substring is always not containing any duplicates so once we get to this next a we're gonna say well now we have to a so we need to start removing from the left wing to start shrinking our sliding window until we no longer have duplicates so I'm gonna say remove this one from our substring now our substring runs from here from the B all the way to the a now it's perfectly valid so now we can keep going it's still only length three though so now so we're gonna add this bead but wait a minute now we have two bees but my question is how would we even know instantly whether we had a duplicate or not well we can use a set for that sets will only contain one of each character so we'll automatically know if we have a duplicate we can check it instantly so we're going to check that we have two bees so now we're going to keep popping from the left we're going to keep shrinking our window from the left until we don't have until we remove a bee and we're gonna see that the first one we remove is the Beast and now we're done so now our substring runs from this C all the way to this D now we're gonna add another character once again we have a duplicate and once again we can literally just remove the farthest left character and now we're valid again no more duplicates we're running all the way from A to C next we add a B the interesting thing about this is that now we have to remove this a because we have to shrink our window our sub string has to be contiguous so we have to remove this a but notice we still have two bees in our substring so we got to remove another character we have to remove this B so now our substring runs from C to B so we are valid again but now our substring is only length two next we'll get to the last B last character we're adding and C yep it's a duplicate again and don't forget that as we're removing these characters from the left we're removing a C we're not just removing it from our window but we also have to remove it from our set because our set is going to correspond to all the characters inside of our substring that we're at so we have to remove our see from the window and move it from the set we have to take this B and do the same thing and now we have no more characters to add with this sliding window technique which is a very fundamental technique that you'll probably see a lot more in a lot of different problems we can cut the time complexity down to Big O of n we just have to go through the entire list well we might have to add and remove values from our set but that's a very quick operation the memory complexity because of our set is also going to be Big O of n because potential every character and the string could be unique and will add all of them to our set and I didn't really show it while we were going through the problem but we would want to maintain what's the longest substring we found in our case it was obvious that the long as we found was of length three so I remember the first thing we need to do is get a set to make sure we have all the characters in our window so I'll call it character set and we're going to do a sliding window so any week so we need two pointers a left pointer and a right pointer to determine our sliding window our left will be initialized to zero and our right pointer is going to continuously be changing as we visit every character so I can just use it in this for loop so the right pointer is going to go through every single character now remember if we get to a duplicate character that means we have to update our window and our set so while this character that we just visit at the right pointer s of R is equal is already inside our character set meaning it's a duplicate then we got to update our window so we have to take the left character and remove it from our set so character set dot remove the leftmost character and then of course we have to update that left pointer incremented by 1 and we're going to keep doing this while that duplicate remains in the character set after we've removed all duplicates then we can just add this rightmost character to our set and since at this point we know for sure that our substring doesn't have any duplicates we can potentially update ours our result variable which I never declared so let me declare it up here result is initially going to be 0 and now we can update our results so we can potentially make it larger than it is if the current window size is greater than what it is right now which we can compute by right minus left plus 1 and then at the end once we've gone through the entire or substring we can return the result if this was helpful leave a like in subscribe and thank you for watching | Longest Substring Without Repeating Characters | longest-substring-without-repeating-characters | Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces. | null | Hash Table,String,Sliding Window | Medium | 159,340,1034,1813,2209 |
1,372 | hey so welcome back in this another daily code problem so today it was called longest zigzag path in a binary tree and it's a medium level uh tree question where you're gonna do exactly that actually so you just want to find whatever zigzag path and that's just you have to alternate between going left right or starting at right then going left right so you just have to alternate between going left and right and so the only other catch here is that you don't actually have to start at the root node here this is an example where the longest path does begin at the root node but it doesn't actually have to you can see in this case where the output is three and that can only be achieved by not starting at the root node okay so it's actually started here and that allows you to get three edges here okay and so what we're going to give you is a o of n time and space complexity solution so you just travel to every node at most once and because this is going to be a recursive solution we will have at most o of n on the stack okay and so to do this we're just going to return the result of a helper function that we're going to create and here we're just going to pass in the node that we're looking at and then whether or not we previously went left so we can kind of maintain okay do we want to go right this time or do we want to go left this time and that depends on whether or not we went left or right last time and then we just want to maintain what the current depth of this path that we're considering at this current moment in time okay and so the base case is okay if our root is none so if there's nothing here then let's just return our depth and this just allows us to kind of propagate that result back to the top of the tree and so what we're going to do is we want to return the maximum of this helper function you just want to pass in two recursive calls this one where you start at going left and one where we start going right so we can say okay we can either go left or right here and so because this one's going right then we say okay is it left no that's false right this is left here so previously do we go left no we started right and then here on this side we're going to pass in true and in Python these have to be uppercase and so next what we want to do is we initially have our depth to zero and so that's just to show okay we're starting at zero at the row because we haven't traversed any edges just yet okay and so from there it shows an error but I think this is okay turn the max of that root dot rate which false zero awesome okay and so from here why don't we go ahead and say there's two different paths that we can go down one of them is if we went left previously otherwise we previously went right so otherwise we previously went right and so then at the end of this we want to return the maximum depth which will be this okay so we're just going to update this current depth with it with whatever is the maximum path that we can get from these two paths that we can go down and we just return at the end and so the first one is we want to set our depth equal to the maximum of either itself or we can recursively call itself but this time since we previously went left next time let's go right so we do root dot right and then is left well that's now the negation of it is not is left and so that will be okay this will now be since this is true this iteration will then I'll be false and then we just want to increment our depth by one because now we're going down another node and so we just increment it by one okay and so from here we're going to do the exact same thing but for when we go right awesome so now we want to go left this time this is now true and we still want to increment it by one so there's one other case that we have to consider for both of these paths and that's what will allow us to actually consider the case where the root node doesn't actually have the longest zigzag path but actually like a node further down the tree and we can do that by just simply performing another recursive call but say if we previously went left we can actually go left again but we'll just reset our depth back to zero oh undo we want to say true here because we're going left this time so what this does is this allows us to do the case where okay it allows to go right again after we previously went right and so that allows us to consider the cases where okay say if the longest route path was like this node here in order to get to this part and start here you actually have to go right twice and all you have to do is just reset back to zero in order to begin from there so that allows you to kind of start at this root node and to hop there by going right twice otherwise you'll just be forced to go down this right left path always and not being able to do like right and begin at this particular note okay and so you want to do that exact same thing but for the alternate case where we want to go right twice let's go ahead and run that and yeah so that's the algorithm so it's a recursive solution with once again o of n time and space complexity because you're going to go through every single node at most once and at the worst case the application stack will have n nodes and number of nodes on it so yeah I hope that helped a little bit and good luck with the rest of your algorithms thanks for watching | Longest ZigZag Path in a Binary Tree | check-if-it-is-a-good-array | You are given the `root` of a binary tree.
A ZigZag path for a binary tree is defined as follow:
* Choose **any** node in the binary tree and a direction (right or left).
* If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
* Change the direction from right to left or from left to right.
* Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return _the longest **ZigZag** path contained in that tree_.
**Example 1:**
**Input:** root = \[1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1\]
**Output:** 3
**Explanation:** Longest ZigZag path in blue nodes (right -> left -> right).
**Example 2:**
**Input:** root = \[1,1,1,null,1,null,null,1,1,null,1\]
**Output:** 4
**Explanation:** Longest ZigZag path in blue nodes (left -> right -> left -> right).
**Example 3:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 100` | Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma. | Array,Math,Number Theory | Hard | null |
532 | hey guys welcome back in today's video we're going to look at Elite code problem and the problem's name is KD fairs in an array in this question we are given an array called nums we're also given an integer K we have to return the number of unique creative face in the array a creative fair is an integer pair consisting of norms of Phi and nums of J and it holds true only when I and J are between 0 and nums dot Len and I is always less than J and the absolute difference between the two numbers present at I and J should be equal to K so in this question as you can see this is the nums array and K is the difference we have to find out the pairs which have difference equal to 2 here I can see one pair where the difference is equal to 2 also the difference between this and this number is also 2 so we have two unique pairs here one comma 3 is invalid because PSI is present here and J is present here they have mentioned that I should be less than J but here it is not passing so you can't consider this pair and also you might notice that 3 comma 1 can be formed here and also 3 comma 1 can be found here but that will give you two same pairs but we are only allowed to return the unique pair so you should count only one among them so let's take a look at the logic we need to follow to solve this problem you might notice that this problem is very similar to the first problem on lead code that is 2 sum two sum we are taking one number and checking if its complement is equal to the Target and we are checking that complement number is present inside the map or not here also we are going to follow the same logic we are going to create a hash map where both the key and value are integers the keys will represent the array elements and the value will represent their frequency next we have to create a integer variable count and initialize it to zero so this variable will keep track of the number of pairs so initially it is 0 so this will be our result so let's take this example and fill the map first I'm going to start from here that is the key and set its frequency to 1. next element is 1 add it into the map and set its frequent c21 next element is 4 you add it into the key and set its frequency to 1. the next element is 1 which is already present inside the map so you increment its current frequency with one so now the value of 1 is 2 the last element is 5 which is not present so you add it inside the map and set its frequency to 1. now our task is to eliminate one of the conditions I have mentioned that we have to ignore duplicate pairs like this 3 1 is present here so what we can do is that instead of iterating through the nums array you can iterate through the keys present inside the map so this will eliminate checking for duplicate number so we can only iterate through the keys by making a set of keys using the keysight method so if you use the key set method on the map it will give you the set of keys present inside the map so now the key set will contain these elements now you can iterate through the key set and you won't encounter duplicate numbers by this you can eliminate duplicate pairs now while we are iterating through the key set you have to divide the checking into two parts that if value of K is greater than 0 and value of K is equal to zero first let's check for this condition next time walk through this condition if K is greater than 0 K is 2 so we have to check for this condition now we have to check if I the key plus K is present inside the map or not ith key is this 3 plus K is equal to 5 we have to check if 5 is present inside the map yes it is present so you increment the count so you found one pair so 3 comma 5 you have already formed a pair so increment one count now it will keep checking for the next element present inside the key set 1 plus k is 2 so 1 plus 2 is equal to 3 we have to check if 3 is present inside the map you can increment count so notice that 3 comma 1 is a pair now so this is one pair and this is one pair now we are checking for 4 plus 2 is 6 is not present inside the map so you don't increment count Remains Two now five plus two is seven is not present inside the map so 2 remains as the final answer and you return two as the output which is the expected output as you can see here now let's check for this input one is not present inside the map so you add one and add its frequency as one three is not present inside the map so you add three and set its frequency as one is already present inside the map so you increment its current count plus one it will become two I is not present inside the map so you add 5 and set its frequency to one or is not present inside the map so you add 4 and set its frequency to one so we have completed the steps still here now we have to declare account variable initialize it to zero I've created a count variable and initialize it to zero now we have to iterate through only the keys inside the map so you can do that by making a set of keys using the key set method so the key set will give you this value now so this is the key set you can eliminate duplicates using the key set so you are iterating through the key set now the value of K is equal to 0 that means that there shouldn't be any difference between the pairs so you can find two numbers here one and one the difference between them is equal to zero so you get the expected output as one you have to check this condition because K is equal to 0 so whenever K is equal to 0 we have to check if the value frequency of ith character is greater than one we have to check if frequency of I key is 1 we have to check the frequency of 1 if it is greater than 1 yes it is greater than 1 so you increment the count variable so this is the pair Form 1 and 1 is the pair form now again K is equal to 0 you're checking if the frequency of 3 is greater than 1 no it is equal to 1 so you don't increment count similarly frequency of Phi is 1 which means that there is no duplicate present of it which will satisfy the difference as zero also you can relate to the logic that we are only checking if the value is greater than and one for example if you take one more one the frequency is three one more one and now the frequency is four you can't make these two as another pair this hash set does not encounter one more one to check for these two pairs you're only checking for one value at a time and next this number won't appear again because you are not iterating through the original nums you are iterating to the key set so only one time this number will occur inside the key set because there are no duplicates present in the case of the hash map so if this value is equal to 100 also it will only check for one pair so you're only checking for one pair by checking only ones that it is greater than one I hope you understood the logic so let's code this logica recall the steps I've mentioned in the word document we have to implement those steps in an order so the first step is to create a hash bar where the key and value are going to be integers now we have to fill the hash map with the keys being the array elements and the values being the frequency of those Arrow elements for that let's iterate through the input nums for now we have to check using the contents key method if the array element present at the ith index position is present inside the map as key if map dot contains key of nums of I if that array element is present inside the map you have to increment its current frequency by one as I've showed you for one there were two ones present in the last example so if it is checking if one is already present inside the map if it is already present increment its current frequency with one for that you have to use the put method the key will be the array element the error of I and get the current frequency using the get method and incremented frequency with one and in the else block it means that array element is not present inside the map so map dot contents K of nums of I this will return false not present inside the map you have to set its frequency to 1 so this is actually nums so Norms of I comma 1 so this else block statement will be executed for every unique element and from the next time whenever you find that element inside the map increment is frequency by one now we have filled the map the third step is to create a counter and count equal to 0 which will be our result now let's create a key set and iterate through it first let's declare a set the keys are integer so the set will also contain integer so map Dot keysight now let's access each element present inside the set so I'm using a for each Loop pull iterate through the set now this num will represent each number from left to right inside the set now coming to the check the first part of the if statement is that if K is greater than 0 and num plus K is present inside the map that is what I explained right map dot contains Key by checking if num plus K is present inside the map so num plus K is present inside the map then you have to increment count and we also have to check for second statement if K is equal to 0 and map dot get frequency of that num should be greater than 1 whenever K is the map dot get of num is greater than 1. so in this case also you have to increment count and finally outside the for Loop you can return the variable count which will be our result so let's run the code we're getting the expected output Let's test for all the test cases we are getting the expected output let's submit the code there you have it a solution has been accepted the time complexity of this approach is often because you are iterating through the array where n will represent the length of the array the space complexity is also often because you are using a map where in the worst case if all the elements are distinct the map will be filled with the length of nums that's it guys that's the end of the program thank you for watching and I'll see you in the next one | K-diff Pairs in an Array | k-diff-pairs-in-an-array | Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_.
A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true:
* `0 <= i, j < nums.length`
* `i != j`
* `nums[i] - nums[j] == k`
**Notice** that `|val|` denotes the absolute value of `val`.
**Example 1:**
**Input:** nums = \[3,1,4,1,5\], k = 2
**Output:** 2
**Explanation:** There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of **unique** pairs.
**Example 2:**
**Input:** nums = \[1,2,3,4,5\], k = 1
**Output:** 4
**Explanation:** There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
**Example 3:**
**Input:** nums = \[1,3,1,5,4\], k = 0
**Output:** 1
**Explanation:** There is one 0-diff pair in the array, (1, 1).
**Constraints:**
* `1 <= nums.length <= 104`
* `-107 <= nums[i] <= 107`
* `0 <= k <= 107` | null | Array,Hash Table,Two Pointers,Binary Search,Sorting | Medium | 530,2116,2150 |
930 | hello so today while doing this problem called binary sub-array with some it's a called binary sub-array with some it's a called binary sub-array with some it's a medium difficulty problem and it's we get an array of 0 and once only and want to count how many non-empty sub arrays to count how many non-empty sub arrays to count how many non-empty sub arrays that have the sum s so for example have this array and s is equal to 2 so the sub array that we can construct our list of that sum to two are this one and this one in this one so that's four for our sub arrays so our goal basically is to come to these with a value of s so and these are the construct you know that a the values of a are either zero point one and the sum is between zero and the length of the array so we don't need to hand on a case where it's bigger and yeah that's about all that we are given so this problem is similar to a little problem called sub race the number of sub arrays with some K except here it's a lot of special while it's a zero and one only but we can solve this problem in the same way which is using just a hash map using a map to count so basically we will use a math and in it will put us some as a key so our cube is that some in the valley would be how many number of the carats of occurrences of desam so basically what we will have is let's just write the Sun and we'll have a count that comes how many sub arrays we have so this is our map the sums occurrence and count is zero we'll go through the array call this day and we'll have an accumulative some so just a value with that kind of for an array like one zero one it would just keep track so here for example it would be so here it would be one and then if we advance one plus zero to one and then if we advance again it will be 2 so just a cumulative sum so that means same shall I sit here - yes that means same shall I sit here - yes that means same shall I sit here - yes and yeah we can just each time add the new value like we did here and the point of this is basically if we have a summer say or say some here at this value let's call this value G and then we have some somewhere else say there are lots of values here and we have this sum this point earlier pointing at I and the idea basically is that if the difference between some j minus sum I is equal to K what that means is that the values here their sum is equal to K so basically us call these bodies between so that means that the sum between I and J I plus 1 and J is equal to K so basically that means that we found this sum that satisfies the condition let's call this K here to avoid confusion so that means that we found an interval of body that sounds - K so whenever we'll body that sounds - K so whenever we'll body that sounds - K so whenever we'll find something that but if that gives us this that means we found an interval that means we can increase our count by 1 and so how can we find this so the way we can find this is since we have a map of some in their value of occurrence every time we encounter with this technology of value or a new Sun we can just check if the if it if already in the map that is a value that is a sum mindscape if that value exists that means that since this basically means some of the eye is equal to K some of J minus K so if you find this son that means would found this one that means we found the interval and we can count so basically that means when we increase the son by the new value thank you much if someone can just check if this sum minus K so essentially this condition is already in the map then we have this appearance and we have this interval that sounds to care and as a result of that we can increase count so if this is the case we can increase count by how much so we can say 1 but that's not actually the case because maybe the number of accounts is 2 so there are 2 such sons in that case we can associate this interval with the J on one of the Sun and we can associate it with the J of the other son so it's actually the number of occurrences of that of this sum here is minus K and then after doing this we can just populate some map with the new some so that would be 4 for the values that will arrive after this a basically so this would be since this counts the number of occurrence we need to say sums of map has plus 1 but since this may be it's not in the map yet so we need you just don't get s and the default value is 0 and with this we can return it out we are expecting for but we get 2 yep so there is one case that I didn't handle which is saying we have K is equal to 1 right so we need to count this array but since there is no Sun before it is this one here there is no Sun before it will counted as 0 so in order to avoid that we can just put in the map and map 0 2 to 1 so that this case can be added to +1 and so the way case can be added to +1 and so the way case can be added to +1 and so the way we do that is we can just say sums of math of 0 is equal to 1 or alternatively we can just say initialize it like this ok now it passes see if this okay so this passes now this solution can work with anybody who's not necessarily 1 & 0 with anybody who's not necessarily 1 & 0 with anybody who's not necessarily 1 & 0 so we didn't take advantage of that so let's say how can we take advantage of this one just before actually explaining that I can make this a little bit more efficient so since this is just counting I can use counter so I can just use counter yeah which is a Python 2 library utility that can just count the number of occurrences and the benefit of this one is that if verbling is not in this in the counter yet then it just returns 0 so with that we can avoid the need to check here so that means we can just do count and if the value we didn't put the value yet then we'll just get 0 and we will add nothing to our counter so that works so this is counter and since by default is 0 we don't need to explicitly say that so we just can't do this and this is the same as doing it plus 1 and we need to just handle the case where 0 & 1 0 is Method 2 1 so that we can do & 1 0 is Method 2 1 so that we can do & 1 0 is Method 2 1 so that we can do this when it's imported some pop collections on these passes now let's get back to the solution that works of nobles - that the solution that works of nobles - that the solution that works of nobles - that takes advantage of the fact that the array contains only zeros and one and once so how can we do that so the way we can explain this is same we have a set of bodies we all must say a just to map a structure of a random array that we may have and then we can have let's say B and then something like this and then we maybe have other values let's say instead 0 and so when this happened here and we traverse the array what we can do is so basically what we want is these volumes of us say are once so once you find if K is equal to 4 for example say if K is equal to 4 then we need to count this array but also all the zeros before it can construct an array because they still sound too far so this one can get added and then we can have this one so for each to 0 we can have one more array that sums to K and the same thing to the right so the way we can do this is we can have so we just need to know where the first 0 is so that we can count all of these this as occurrences of a number sub-arrays we increase by one so we just sub-arrays we increase by one so we just sub-arrays we increase by one so we just need to find this place here and in order to find this place we can just keep track of the last one we encountered so we can keep track of that using prep and in order to know this sum here we need to keep track of the start of it the start of the first value that is not zero so let's call that low and we need to keep track of the value that gives us the sum equal to K let's call that time so high can be first here and then we can find that the value is three so we haven't reached it K yet so increase so it will do so our sum is less than K so we need to increase high to reach a body bigger and then here founder is equal to four and we need to start counting this and this right and this is the main idea so in this case here if K is equal to four how can we count all of these so all of these is basically just this Plus this right the values here and the values here so the van is here arms at what are low - crap - one right minus one so that low - crap - one right minus one so that low - crap - one right minus one so that we can delete this one so this one is here in our loan - prayer - one and here in our loan - prayer - one and here in our loan - prayer - one and these values here they count for just one sub array because if you take less than that just these that's less than K so it's counts only for one party so it's plus one so these are type T is no - prayer right and so this here we no - prayer right and so this here we no - prayer right and so this here we handle the case where the sum is equal to K now what if the Sun is plus the value that we just encountered is less than K and what if it's the other cases when it's bigger than K here we already handled the case where it's equal to K that's the case that we handle all right so if it was like a that means that the Sun is lost okay that means that we need means this pointer forward so that we can find say when we are here it's three we need to move forward so that we can reach a bigger value that may be equal to K so this means that we need to reach a bigger so now if it's bigger than K that means that we need to find a smaller value and so we can leave K to reach a smaller value light the sorry we can move low to reach a smaller value there is one thing we need to handle for this case so if we move low so let's say we love was here and that was zero so we need to take care of keep moving low until we find the value that is not zero so that we can start counting there is no need to count this our values so here we need to do something where while the value at low is equal to zero keep increasing right because otherwise if it's zero we haven't changed anything so it won't help us much right so but still how can we do this and also the calculations that we did here reply on low being the first one value so we need to make sure that's always the case okay so let's start doing this solution so there is one case where if all the bodies are zeros then we don't know where to put low and high so our solution here won't work so we need to handle that separately so let's say if K is equal to zero we need to handle that so here we just forgot to do we can handle later now must initialize the bodies that we describe it's Elmo we need I and we need just this to have a length of the array and was initialized prep so first our low would be here so crappy we just can mark it with minus one anything before so that would be minus one for breath bonus star to zero and I was stopped also to zero and n is the length of array let's also have something a cumulative sum that just calculates the sum so that we can know if it's less than K or not so that initializes to zero and we need the account for how many sub arrays we have right so that would be 0 2 and now so while this is not at the end of the array yet and the value at low is equal to 0 we to just keep advancing because our formula here needs absurd when there is nothing to zero and so in that case we can just keep increasing low and keep increasing advancing high to go to the so first they start out as 0 if the value is say 0 here we need to keep advancing until we find one that is not 0 and so we advance both and then after that so we keep make sure that we are still within the bumpers and now start doing these conditions so check if s plus the bubble hat high is equal to K so our I'm here is just this value right here so if is equal to this and the other cases are if it's some bigger than 10 and comes to choose when it's like a so this case here we'll find the volume so we need to count this basically that our count so that we can just say oh my spray possibly as we calculated before and we need to advance both high so that we can check the next okay let's say we had another one here and in that case we need to also count the occurrences of so if you had another one that I need to count also this okay let's write and so we are going to do my plus one and there's some increase it by right now for this case when it's bigger than K we need to move hello toe so that we can get a smaller value and we take care of this and so moving along this list and since we moved hello so now the Sun has one less value so the body and allow is not all getting the Sun and so you can think of this sum here as moving along P along with the values mo it in hi lower and higher based in we to handle the case that we said we are so pregnant to be always the first value that the first occurrence of the previous ones based way actually the last index of the occurrence of the previous ones so that means that we need to put trip to a low here and we if Y I'll always equal to two zero weight 200 this case with me to keep increasing it hasn't said yet and we also make sure that we didn't so beyond the length of the arrow and now if it's less than K we need to move higher to it should bigger son so we need to do this and we need to increase since it's not this and that's basically it and at the end make a 10 count so yeah we need to hand on this case if this sum is equal to zero so let's just define a function and we can find this one so for this one we can just go through so we have and we have some and we can just go through the array and if a is equal to 0 then our count is plus 1 and our risk the final result was call it's going to please both count so why is it going to increase by count is because say if we had 0 we need to count 1 2 & say if we had 0 we need to count 1 2 & say if we had 0 we need to count 1 2 & 2 & 3 2 & 3 2 & 3 and so first it was just zero so this is just 1 if we add another 0 then the number of zeros is 0 1 here 2 and then 3 so it's the previous count plus the new then you count so otherwise we can just search like the counter because we encountered the body that is not 0 so we can't construct any sub arrays between that sum to 0 between these basically so whenever reach of 1 we can just start recounting from 0 and then in Clinton County and still eight this I can have more space 26 why is it complaining here yeah I need to do else--if because this yeah I need to do else--if because this yeah I need to do else--if because this is um she didn't happen if it this one is vomit right so much Ventus okay we I have a wrong answer for this case here Selma's try and see why we are expected to get 15 because the sum is zero so that means that so when the Sun is zero we call this helper sum which means our solution here is totally wrong yeah we don't we should return count because this is rich initialized during the accumulative result is in result here so that and self else did it not yeah it did that's interesting not sure is happy PLC so just to make sure that I didn't miss out any invitation I'm wrong so I'll pass ei with the value zeros and we'll go through them and we check if the value 0 increase count and we had come to result and otherwise said count to 0 and with a 10-0 run so this seems like and with a 10-0 run so this seems like and with a 10-0 run so this seems like reasonable and if K is equal to 0 it has returned that listen Kristen must print we'll just print here to see if it doesn't oh yeah I see so I just called this but I didn't write on it which is really dumb so it goes through here and this doesn't handle that case so it should be returned okay cool turned this and the solution passes so yeah so this basically second solution here uses two pointers and take advantage of the fact that we have just a zero in one in the array and yeah so basically the lesson from this one is using two pointers and basically listing all the use cases possible and have the 90 each one separately yeah that's so for now see you next time | Binary Subarrays With Sum | all-possible-full-binary-trees | Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explanation:** The 4 subarrays are bolded and underlined below:
\[**1,0,1**,0,1\]
\[**1,0,1,0**,1\]
\[1,**0,1,0,1**\]
\[1,0,**1,0,1**\]
**Example 2:**
**Input:** nums = \[0,0,0,0,0\], goal = 0
**Output:** 15
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `nums[i]` is either `0` or `1`.
* `0 <= goal <= nums.length` | null | Dynamic Programming,Tree,Recursion,Memoization,Binary Tree | Medium | null |
110 | Premature Ejaculation Sir, welcome back to the series Australia, today we will talk about the balance body, which is a very good question in itself. Those who have put the concept in deposit, then like every time I would please request you that If you are new on this channel and if you do not know the regulation of this year, then let me tell you that at this time whenever someone comes, everyone catches the question, before that he has to set it for 5 minutes, 10 minutes and 15 minutes. Give it but before that, think of something for the attempt, do it while doing it in the corporate office and then look at the question, Vikas Sikha, everyone Robert, if you want to learn, then let's start, what are you doing by asking video and technical questions? Aayi Ho, don't lie to yourself. You must be speaking and you must have tried it. Balance body is disconnected from the balance point. One is that it gives time to anything. We do not mean that we deposit this term from the market that we are saying what is the meaning of imbalance body? This question of 1981 This note is given that its height was on the left side, one or you can say it like this, if you correct the note then what is its height, its lineage and what is its height, then for this root of it means take which is on the left side, one and If I talk about this note, what is its difference? One is okay, if I talk about this note, what is its left height? What is its zero? Seat kitne zero episode difference kitna ka yeh zero allotment of flats that if I talk about it's havan isk he got - karenge jitna zero then zero against ka - karenge jitna zero then zero against ka - karenge jitna zero then zero against ka 08 means that we are the people and every node by taking out the left and right side of every note. Apps loot has been removed right and that we are checking what is coming now the question is given that we are checking each note number and the difference that is coming is the difference that your note should come greater than one it means that There should not be one greater than the other, it should be equal to one that if there is wealth then we will not give it a balance point battery. For the question, if I am giving you the second example then what is the second example saying. Look, now Shanno, tell me now. How much is its height coming? How much is its hit coming on the left side? One two three live where two? So wrong, this is where the throttle will be pressed and will stop here. In these systems, we will have to check every single note. Okay, one of its height is how much difference. Its edifice is zero, how much is this yagya, two, and this is done, one, clothes, it's fine, but after failing this, we have to check what is this every 1985 and every Day tech every node is subscribing to this condition what is the condition that loot the apps of left height - what is the condition that loot the apps of left height - what is the condition that loot the apps of left height - right height that the license should be 121 a clear-cut now see it seems to be of two concepts a clear-cut now see it seems to be of two concepts a clear-cut now see it seems to be of two concepts so if I get confused find out the correction what is it That is, loot of left height of the app should be 121 from the right side. Take out the left height of the meat, take out the right one and do both. Okay, so one concept of height has been used. Brother, we will have to find out the height. What will be the second concept? One question. It was further written that we should not check the condition of the fruit. We have to check itch and every old node to see whether every note is subscribing to this thing or not. Okay, so every note should be spied. So every node it means that we should also meet, so every node it means the method, every note is the way to do drivers, inverter traversal, preorder traversal 126 and whatever we have kept on it, okay Vinu, definitely do the latest video. We have launched one, please Apna Satellite Krishna Kumari is from the industry, play the playlist, check, everything will be clear to you, I am moving from Macrame Basic to Advanced, so that those who will be consistent in this series from its seat, will benefit the animals. What is that, there is no such thing, I talk to the right side that you got the doubt from here, it's sequence, okay, I ignore example, then Sallu Doman's 39 10 and 7 attacks, if you have to catch every single note, then his What did we do? We put this traversal right. We have to check this condition in every note. For those who are confused that this condition should be checked, then this is the condition. What did these attacks do that this is this condition? This is the notice. This note should also be called, this note should be returned, this note should be visited, this note should be tight, this note should be returned to Mittu. Understand that every node should return towards this condition in itself. It is okay if even one false in between then true end. Mishra, what is false, remember till 500, this is just sure, always remember that true and false, we have false, there is no problem till it is ripe, now look, now I say one thing, brother, tell me one thing, if I talk about the code. The question must have been clear to you that after coming to the question, Times mixed these two concepts and made the question Next It means that we will have to find out the height in people. Do you know how to find the height? The code to calculate the height is very simple, we have done this using the height function root, just like how we calculate the height of any note, so we calculate the height and now I have understood that a page has been attacked by the root. Time, what did he give, fear, Annette Schwarz, mistake, what did he put in the question, what did he give, this is the balance that the tree node, what do we do, it creates an answer, the words, which use the boolean type, return it, that the films assume that, brother, there is no problem in this. Yes, it must be working and let's make a loop n order you tell check what will we change in it what will we check then pass the route during this time pass the head ok and return a answer no problem There is no problem till now, we have created a dialect and depressed it, we will create a function, we have inverted and passed the answer in it and they have taken this height code, there is no problem till now, we have prepared the option, you use the most important function, we are working. Are going to do an in order you tell what did they take inside it Tree and Root and a satire Why do they take E.M. Pregnant Answer Ambassador Why do they take E.M. Pregnant Answer Ambassador Why do they take E.M. Pregnant Answer Ambassador I have told you this thing and explained it many times so that people who are lions will also see it, they will get the idea. Show the list of such must have been done, now let's take it so that we are connected to the roots, just before this whiskey and declare somewhere in the main function, this is not changing frequently, the innovative driver can be attacked on the institute call, what is this recceive Function Right Now what do we do, let's pick up this root is not equal to null, write it like this, no problem, have called in order, inverter you tell, call, sorry, what is the root of the call, left, I have explained the method that in 9th May, these means five. Till the minute, first left, then left and passed the node fruit research institute loot, opposition, whatever thing is there in the minute, right, made a last here, en order you, this root's right, a tract and answer, now look, whoever comes here, then we People now get this here, now this is where we get every single note, get notification, get note, like if you talk about such an interview, then note or meet people, talk about this data, sum gets root. Value text of is here node, we work on this note, see how, then I will take this color, then come here, after this, it is finished, now we will check this note, we will check the beans of this, that this is also clear, left, right side 121 that We will check this, if you can, check what we said that in our route we had kept Guru value in the answer, keep in mind that the route mention has been kept in Roman, no problem, what we did was that we took out a function one and one day one can take out that Height of the route left, no problem pant d2h Height of the route right, 6 difference taken out pant difference or ABS fennel d1 - due pant difference or ABS fennel d1 - due pant difference or ABS fennel d1 - due toe, checked that then the difference became greater than one, so we were on the track in the village. This has to be understood, what has been done, now look at this note, the set up of the note will be on this note, how will the note be first in inorder traversal, 9039 has passed, now we are here, then on this will come the f-18 Fraganate way or will seven this will come the f-18 Fraganate way or will seven this will come the f-18 Fraganate way or will seven more people come on each turn. But we have to check whether this is coming or not, the network is guaranteed, if even one mistake is made in between then ultimately the whole game will fail and that's it. To check every single note, I said that you can use any other inverter family poster, I have asked for inverter in Australia, it's your choice, you make a voice that we have to make drivers and check each note, ensure this condition. I have taken out the element ninth 1527 of the inverter. Now, when I have a normal route on this route, what did I do that on the Noida route, it went there, here and there, what is the digestive thing, this thing is where I am, its ex is the best, so what did I do with this data. Shroud is of no use, I meant fruit in the bus, so what I have done is that for this route, I have calculated the height of each route, I had to calculate the left height of each route and I had to calculate the right height of each foot. Thanks for rooting, fight for. Right, we have taken it out, add it in 20112 or do RH, take care difference, we have taken out a chakli difference of greater than by admin that this note has failed, cooked, will pause it, let's pause it, okay then falls but This meter is all true, this one's answer is with metro, comment, I put one percent on it, right, whatever is happening in the main function, which is in the root, will be included, which is fruit, it will call last here, this one needs equal answer, MP cent. Paul's right, even if it is through, but when the antecedent is implicated in it, what does the end operator and theorem do that if one goes to the Air Force, then the ultimate traps him. Ultimately, in whatever form Salman is in, then what will be false and true will always be the policy. The whole game will run if you get the codes just by worrying, that's why I kept this incident in the answer because ultimately the answers to the main function keep changing if you don't know the details of what is happening. Who is this? I selected BJP. I was explaining that if I don't use embedded then every time a new very high for will go. It is important to keep right from present because it changes in the roots and less changes in the roots by self-publicity. I hope less changes in the roots by self-publicity. I hope you have understood this game clearly, it is not very rocket science, it was very easy, just height and every note. Reversal ka game tha ok ab school bhawan isko code jhal simple hai height ka code and the chief renault route ok no after vote old is gold channel simple return hai a reader maximum of what jo bhi told in this series that direct in this video If you are planning to do so, I would request you to first watch the old video, then this trick would have been clear to you. Okay, no problem, now we have to forget to make the answer here, which will be made through check and colored in order. You tell while calling, retention means so much support, tell me the support function, its function name, it doesn't matter anything, I am just telling, so general works by taking comments, if you read the code at many places, you will see that if you use digital, then it means tight. Now I create the world in this routine here, Root and Boolean and Sentences, if you don't send, then whenever this inverter calls this function again, a new variable will be created inside Gary Kirsten, Answer Tech, we want that with this Internet Grad. Slam episode looks good must be clear by now this root not equal toe no top enter inside and inverter will absolutely do this twice one for whom left of the root and answer how a robot for torch light adventure like and there Let's play the game, find out the left height of the pant, how will the left come out first, remove the left key and right end of the IGST root, anoint the one which is ABS, first middle - R8, then it should be the first middle - R8, then it should be the first middle - R8, then it should be the same answer. Base St. Paul's David is nothing and do two times associated with the True AND operator so you understand that things are running I'm telling the truth to hate again if this condition will study and we guys Please comment like share thank you Jhala's video song Shri Ram Radhe-Radhe | Balanced Binary Tree | balanced-binary-tree | Given a binary tree, determine if it is **height-balanced**.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,3,3,null,null,4,4\]
**Output:** false
**Example 3:**
**Input:** root = \[\]
**Output:** true
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-104 <= Node.val <= 104` | null | Tree,Depth-First Search,Binary Tree | Easy | 104 |
392 | hello everyone welcome to day second of march heat code challenge and i hope all of you are having a great time the question that we have in today's is subsequence here in this question we are given two strings s and t we need to identify whether s happens to be a sub sequence of d or not for example here they have provided us with few cases where s is a b c t is a h b g d c as you can see a b and c all three characters occur in the same order in t as present in s as a result of which we have to return to it's a subsequence here we have s as a x c and since x is not present in t we have to return false if subsequence lead code 392 it's an easy level question on lead code and i totally feel the same so let's take the same example that was specified in the question and by definition of subsequence all the characters in s should occur in the same order in t so what do we take two pointers i and j to keep track of the characters that we are currently visiting in both of them what do we see first the is character in s happens to be equal to jth character in t as a result of which will increment both of them so i and i point points to b and j points to h what are we gonna do next we will keep searching for b in t till the time the jth character in d doesn't match with the ith character in s so is h equal to b it's not equal as a result of which we'll have to increment e so t gets incremented to this position and let's proceed ahead here we see that both the characters have turned equal as a result of which we'll together move them ahead now i points to c and j points to g so are these two equal these are not equal as a result of which what we have to do we simply have to increment the jth pointer till the time we don't see an ac so it gets incremented to d is also not equal to c again it gets incremented to c here we see that it's a matching case c matches with c as a result of which what we will do we'll simply increment the s pointer which is i and since we have found out all the elements of s in t it's the happy case we have to return true in case after the complete iteration of t some characters still goes missing we have to return false in those cases without further ado let's quickly walk through the coding section and i'll exactly follow the same steps as i have talked here as told in the presentation here i have taken two pointers i corresponds to s string j corresponds to three string till the time i haven't exhausted any one of them i keep on checking if my is character in s happens to be equal to th character ajith character in t if such a case is found i increment the i get pointer otherwise i keep on incrementing j pointer searching for matching cases in the end i simply check if my i happens to be equal to s dot length if it does that simply means that all the characters in s have been found out in t and it would be happy case it will automatically take care of returning true and false appropriately also there is one of the corner case which i have specified if s dot length happens to be 0 i have to return true because that signifies the input string is empty in nature the time complexity of this approach is order of length of s plus t and space complexity is constant time we are not using anything extra this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for being here have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye | Is Subsequence | is-subsequence | Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_.
A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not).
**Example 1:**
**Input:** s = "abc", t = "ahbgdc"
**Output:** true
**Example 2:**
**Input:** s = "axc", t = "ahbgdc"
**Output:** false
**Constraints:**
* `0 <= s.length <= 100`
* `0 <= t.length <= 104`
* `s` and `t` consist only of lowercase English letters.
**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code? | null | Two Pointers,String,Dynamic Programming | Easy | 808,1051 |
48 | everyone so today we are looking at leak code number 48 it is a question called rotate image and so we are given an n by n 2d matrix representing an image and we want to rotate the image by 90 degrees clockwise we want to do this in place and we do not want to allocate another 2d matrix to do the rotation so here we have one two three four five six seven eight nine we're going to rotate this clockwise and so we can see that one two three uh is on the last column four five six is in the middle column and seven eight nine is in the first column okay so if you're not familiar with matrices this problem can seem a little daunting it can definitely seem very difficult but it's actually not that bad another question i highly suggest looking i made a video on it's called transpose matrix that kind of deals with a little bit of what we're gonna do to solve this so here we are going to have this uh array here this matrix with one two three four five six seven eight nine okay and so what we could do is we could let's say we have our rows here and we're going to have our columns here okay now what we could do is we could initially go ahead and swap everything from the row and column okay so let's say we went ahead and swapped two and four three and seven and six and eight okay so what's that going to look like our new matrix is going to be one four and seven um two five and eight and then we're going to have three uh six and nine okay and we can do that with one pass we can just iterate through the matrix and just swap the rows from the columns okay and so now that we have that what we can see here is if you look at the solution here it is one two three four five six seven eight nine and if you look at after that first swap we have the answer it's just in reverse order right what we're trying to if we reverse all the rows what we're going to get is we're going to get 7 4 1. eight five and two and nine six and three which is our solution okay and so what is our time and space complexity um it depends on how you want to look at it if you want to look at the size of the array then it's going to be quadratic but if we're looking at the number of cells it's linear so we can just say this is going to be linear time or o of m as many cells there are in the matrix so time complexity we can get o of we'll just say of n and then space complexity we're not creating any new space all we're doing is just swapping the variables as we traverse through and then we're reversing it okay so space complexity we can say of one okay which isn't bad okay so let's go ahead and jump into the code so what we want to do first is we just want to swap the rows and the columns okay so we want to say 4 let row equal 0 row is less than okay and so now when we jump into the columns we don't want to go through each column we want to go through the adjacent column to the adjacent row so if we're going to be in row 1 then we want a row 0 then we want column 0. if we're going to go into row 1 we want column 1 and if we're going to go into row 2 we want column 2 as well okay so we're going to set column to row where column is less than matrix of zero dot length okay and so now all we're doing here is we're just swapping out the values so matrix of row column is going to be matrix at column row it's going to equal all right so all we did there is we just went in and we just swapped this we started here then we're coming here and we're swapping these two then we're swapping this seven with this three and then this eight with this six okay and now we just need to iterate through all the rows and reverse them okay and that's all we need to do and that's the solution not too bad if you just kind of look at how matrices work and if you can kind of step through each iteration of the like each transformation of the matrix if we transform it by swapping all the rows and columns and then we can see that we have the solution we just need to reverse the rows let's go ahead and run that and we are good okay so we are doing this in constant space and then o of uh the cells o of n time um and so that's not bad so yeah that is lead code number 48 rotate image i hope you enjoyed it and i will see you all on the next one | 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 |
473 | hi everyone welcome to lenovo in this video we will discuss about another liquid problem that is the matchsticks to square this is the middle level problem i don't see what this question is asking us to do and how we can think of finding a solution like for this type of questions so uh we'll look into the exact questions but moving on if you haven't subscribed to this channel make sure to subscribe to this channel for regular lit code videos like this so the question says uh look even in dj array mastic so this is our masters into that given to us and while mastics of i like each of the uh elements in the matrix is that length of i is matchsticks like it says like each of the uh like each of the elements in this array is the length of uh iphones okay now you want to use all the mastering so you need to use uh all the messages you're gonna request any uh to make one square okay so you need to build a square out of it using all the massive okay i also need to mention that you shouldn't break any matchsticks that you shouldn't break any matrix okay and uh further you can uh link them up like uh and each matrix must be used exactly once so what it exactly means so if there's a matrix of say uh length four over here okay that's a matchstick of length four uh you cannot do something like you break it in half like a normal sticks of length three and a stick of length one you cannot do that or a message of two to each you cannot break them in any order but you need to use the whole mastics uh in a fashion already what you can do you can uh you can link them up that is you have a massive length four so you can have a rustic of length four and honestly some other matchsticks same as domestic of length uh one and you can link them up to make a bigger one like a five length okay so you can link them up you cannot break them okay but it says you each matchsticks must be used exactly one so you cannot uh use one matrix multiple times obviously if you are making up a square you cannot do uh one message multiple time right so uh ultimately what it asks us to return uh the ask is uh return true if you can make a square or false otherwise so you need to check like if you can make a square out of it okay square in the sense what does exactly mean look here if there are bicycles in the one two and two uh then if we need to make up a square we are sure that the square has all of its length is equal right so the first thing we should need to check like was the sum over here the sum is one plus two so that says uh eight being is length so eight being is left if we just check for the first thing that eight divided by four is uh our two right so if the modulo of this eight mod four is zero or not we can check to find that whether we can actually do it or not like the first thing first it can be like this okay now see uh if our length was something like sum of something like nine then how what would have been so 9 by 4 would have resulted in 2.25 right so we cannot have resulted in 2.25 right so we cannot have resulted in 2.25 right so we cannot break any mastic so how can we go ahead with the 2.25 value right uh so that's with the 2.25 value right uh so that's with the 2.25 value right uh so that's not possible so we cannot divide uh like finding the sum and realizing whether we can uh like whether we can actually do it or not like whether is it even possible or not rather before even moving into a solution of moving into the stuff we like what are the difference of what we need to do we can actually realize that if the sum is divisible by 4 then we are sure that we can think of finding a solution to that but if the sum is not divisible by 4 we cannot think of any solution let's do that so 9 is not the case in our example one let's understand what's uh what the case we have away okay we exactly uh like what we did exactly we uh put the two one on one side but remember this is square so it doesn't matter whether to put it on the left or it would be on the top bottom right okay like it doesn't matter but something you need to realize that you need to keep a note of that but doesn't mean uh you need to check whether our uh particular matrix works in the like if we place two metrics on the right so other matching like massive size shouldn't be equal so you can place them based on what size they have and where we can put them so this actually there to understand like that we don't have any uh challenge with putting any messages like this one plus one is put two on the right so this can be good on the but that is not the way you should think that if one plus one like if while putting the masking if you are putting one unit mastics on the left the other one will basically can be put on the top bottom can be put on the top can we put on the right exactly so this can happen for the other one unit so that is the kind of check you need to have over here like if we put one if we exactly put one and one on one side it doesn't matter if the other square is like this or how is exactly square okay the final answer is actually the same but we can keep a check while we are going ahead with this now uh what exactly we are doing over here we simply place the matrix like let's understand this example we simply place the matrix and we find that the square of length 2 so we can have a target of like this like 2 being the 8 by 4 is like sum by 4 is uh our number we got so our target value of length will be that one early okay so there's a square of length two we found and one side of the square can uh came two sticks with length one okay so it says that one side of the square is a two strings of lengthwise so let's uh try to understand this uh further okay what i mean is so you were given over here one uh like this area okay so i'm just writing it down in a bigger format one uh two and then two fine now what exactly we need to do say you see you just took up like uh just uh let's see in this manner that you just took say there are four corners okay so one uh two and then three okay and then this four so this is the four corners of our square we have over here five now what we're trying to do we uh took up this one fine for this one we now have four positions to place them we can place them exactly at this position right we can place them over here so this was the exact thing i was trying to tell my minute earlier that uh this initially it doesn't matter like the fourth step you may say is all the same step yeah so that's true the all the four steps are exactly the same but it matters when you are going into the further division so like for the first one we actually came across four places to uh put the first one okay one in the left one being the right all right okay one being the top one being the uh bottom fine so these are the four places we have to uh put our uh one like first one can you put in this power okay so say you say we just went right with this left one for understanding we went ahead with this left one fine now uh let's see what are the other cases how we can replace the other values over here so once we put our left over here now uh we come across the next one fine now the next one can be again we have four options for us fine four options for us say we uh sorry i just took the top one for this case so let's uh let's change this is the left and this is the top fine so this is the top i just i'm just going there first we place it in the top okay now we uh find the left right uh top and bottom fine now after press the first one we say we took the left path forward placing the next one fine for the next one this next one so we just placed the next one over here fine that's why we place our next one now we like we had actually four places to put this we can put it in the top as well the left right top and bottom is also available for us now we push the next one in the left next we went to our two right after going to a two we know that uh it will again have like four options to be placed right uh that's the two we are trying to place okay so first is the left can you put two in the left okay can you put two in the left no we cannot so we look at the right that's the second place we have we can put two in the left so we put the two in the right okay we went ahead with this particular format now we again got four different uh parts to go that is with the second two okay that is with this particular two we got this and again we got four options we can you put it in the left no can you put in the right no now can i put it in the top no now we need to put it in the button that's the two being placed over here fine so now after this uh we place this in the bottom right so once it places in the bottom we will go ahead with again four step for this uh last two we have over here fine for this last two we have also four options can i put in the left can i put in the right can i put in the top can you put it in the bottom no so we find that all the options are closed for us fine so we cannot place our last element at any of the places without even breaking the stick okay but we shouldn't break the stick right so without breaking the stream we're gonna place it so the problem is not here problem is going ahead with the other solution or with the particular way we chose so we will simply uh we'll simply go back okay we'll simply go back each of the steps to find out what was the step we had over here so initially we took the left for this one but now we find that this is not a case so we'll take the right again so we'll take a right for this one we'll again end up finding that this is not the case we took the uh top for this one okay we will take this path and i will find four solutions so we took uh top for this one fine and then we found four solutions place the two at the first two at the left then second to the right the next two will find that the left right is not uh failed the top is also filled then you'll find the bottom is limited so once you find that all of the uh sticks are being placed and all the sticks are fully uh placed then you find okay it's possible so we'll find our ultimate solution to equation and then we need to return back our answer to this fine so that's the question over here but uh think of some other corner cases say the length is eight find the length over here is given as eight but pick up a condition where our stick is something like um three one two and two can we make a square out of it without breaking no we cannot now like if we sum this up and divide by four we know the maximum length of our stick is uh two that is possible uh like two and the two we find that we cannot place three anyway fine so this is the kind of corner classes that may be there in our equation so we need to tackle this kind of things also so uh so the first thing we need to go ahead with we need to find the sum and divide it by four so we just got a target say uh t being the what is your target under me who will be your answer like two will be taking this key so once you're finding something greater than our target we're going to place that value so once you cannot place that value that means we cannot find a form of square out of it okay but once we can place out the value that is if it's less than our target so we can place the value and we'll keep going with the other all the four uh paths so we are getting and we'll keep traversing on this part so uh this is more or less a tree like a structure are you going as with the dfs format we are going to the depth first and try to finding a solution to that but then you realizing if it is a lot of solution you go back and then try to form the solution in another format so this is the way you will keep traversing and ultimately trying to find a solution okay so that's more or less the kind of solution we are looking forward to and now uh let's try to uh run this for like write this code exactly what how we are discussing this and uh write this code so you remember to write exactly this kind of put you will need some kind of additional memory additionally you need a how many additions we did and like uh another area of length four the fire will place each of the stick at each of the particular indexes so that we can place all the sticks like we are actually dividing with all the sticks in groups of four okay so it's uh just dividing the six in groups of four so let's write this book and again i will explain how the code is working with what we are thinking over here okay so here is a solution for over here okay so uh what exactly we are doing over here we're doing exactly what we say we are doing we just checked for say which is the initial one we are finding a sum fine then we are checking like the first thing was if the mastic is null or massive the length is zero so if it's zero if there is no massive then there's no way we can find the solution right then one time we'll find the sum of all the matrix like all the elements in the mastic terms and actually finding the sum of four is not zero that is if it's uh we find that uh it's not equally divisible by four like without equality divided both sides then there's no way of going right we just returned a false to that right uh father what would you do we just sorted our array to sorted out in the sense uh so that we can have all the bigger elements and all the smaller elements in the front the reasoning we can place the first we can place the bigger elements that all the bigger elements are up first and then we can place the smaller elements at places where we can actually place them so if this saves our complexity if we just see over here uh if i just uh take uh if you just notice over here if we have something like this that we have uh like a solid like three one okay and then four uh the four fine if you have something like this what you can do is it good like if you place one somewhere and then find why to place a four it's always better if you just go ahead it's fine placing the four you'll go ahead and replacing the fourth we'll go ahead and placing all the four that's the bigger values we have so you place all the bigger values now what we are left with we are actually left with uh facing three and one so now we are we know that uh like if we if you look into we don't have multiple choices to place three and one so for three we can have only one choice to place over here and for one we can have only one choice in case we cannot place one in case there are some value like two or something like that or something that we cannot place so we know that by default we cannot place and we cannot place it over here right so once you're gonna place it over here that means it's not possible and there's no point going further but if you go ahead with placing one at a place fine and then you go ahead and placing three now three can be over here we can place t over here we can uh like three over here or we can place three over here right or we can place three over here so we are going under multiple choices for us fine so the choice becomes so much more so to reduce that kind of small complexity we just uh like to reduce some of the small cases we get so we just place all the bigger values we have in our array so let's go ahead and place them fill all the places and now whatever is left with us is we will press like a smaller whole place in the other corners so that we can find a better solution like on a faster fellow we can go out with it right uh so that's more or less the question is all about i hope this i will go ahead i'll tell you that okay next week we took a for the length four so that we can keep each of the side in our place next we've got the massive minus one so that we can start with our uh right most elements so that's what that means is the index we are going with and then some by fours on my phone being a target we shouldn't uh put any of the uh sides being greater than our target right so that's our uh objective over here now if our index is minus one like if we uh keep on traversing from the right to the left if we traverse this and after that if you read something like minus one that means we reached our time so we got true okay fine we need to stop tracking now what do we do when that is index at this position and we find that the sum plus our matrix index like whatever the matrix index is pointing to okay so if that is greater than target like that this is greater than our target follower we shouldn't go right we should simply continue the value or if the sum i or some i minus 1 is same so that means if our uh sum i minus 1 is the same value that is we already placed 4 over here so some i and i minus one are same values then what's the point of going ahead like uh right we already place those first so there's no point at uh position i so we don't need to go into questionnaire so go ahead with other positions where it is like there is a difference right so that's why i can do this like we just continue the loop this happens when we just placed all the four values so four are already there and i find that some i like four plus say three is greater than target we contribute four plus uh like all the focus is here and there is having the last time you have so they are what you need we simply need some i that's messy index is pointing at three fine sum i plus equivalence will just plus this value we said in this version and then we put uh went ahead with our uh further dfs into what gives us i minus so just move the english a bit lesser fine now uh what for the ultimate we are not finding a solution to that what we will do we will simply subtract this like we place the uh stick over at this place and then we will remove that stick from the place thinking that can you find a different way to do that fine so we just went ahead with the solution like this but ultimately we will simply do this uh like put up the places stick if we're ultimately gonna find a solution we'll revert back and take up the stickers like replace the stabilizer so that's what the idea is once you in between if you find that this is a solution possible then we simply go ahead with uh like returning truth to our ultimate answer but in case it is not really done that okay this is not a possible solution this is all our ideas all about so i don't know how uh | 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 |
958 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem check completeness of a binary tree we're given the root of a binary tree and we just want to check if it is a complete binary tree which by definition is a tree where every single level in the tree is completely full except possibly the last level if the last level is not full then it has to be filled from left to right so here you can see it does have a single missing node but the missing node is all the way on the right side so the existing nodes are filled in from the left side now suppose this node over here was missing then it's not a complete binary tree because we have a node here but we also have a node here they're not filled from left to right we have a missing one right here now if we had all four nodes then it is all also a complete binary tree so conceptually this problem is pretty simple by looking at it's pretty easy to tell if we have a complete binary tree or not and algorithmically we know there's not a ton of different algorithms we can run on a binary tree usually it's DFS but the less common one is breadth first search which one do you think is going to be more useful in this case probably breadth first search which is basically a level order traversal we're going to Traverse it level by level because that's probably what's going to allow us to know if the last level is filled from left to right so suppose we have the same binary tree over here well structurally the same the values are pretty much irrelevant so I'm not even going to put them in here because they just serve as a distraction for us in this problem as we're doing a breadth first search on this problem we're going to have a Q data structure this is going to be inside of our queue we're going to pop this and then add its two children to the queue and then we're gonna pop the left child over here and then append its children to the queue and then we're gonna pop this next guy over here append its children it has one child here and it has null over here and then we're gonna pop this guy and also append their children which are gonna be null and then once we have a cue full of nulls which is what's gonna happen in this case that's how our algorithm is going to terminate but how do we know at the end is it a complete binary tree or not well think about it like this for the last level we expect that eventually we will have some nulls either there's going to be a null here which is going to be the case for this problem or maybe this entire level is going to be full we have a node over here but then the last level is just going to be full of nulls so basically when we reach our first null value we expect that every other value we pop after that is also going to be null that's how you know it's a complete binary tree whether it's in the last level or whether it's in like the existing level maybe this node doesn't exist either we have two null values over here we expect there not to be a situation like this where there's an existing node here but there's not a node here we pop this guy it's non-null node here we pop this guy it's non-null node here we pop this guy it's non-null we pop this guy it's non-null we pop this guy it's non-null we pop this guy it's non-null we pop this it's a null value and then after that we do not expect to see a non-null that we do not expect to see a non-null that we do not expect to see a non-null value over here if we do then it's not a complete binary tree now there's one last Edge case you might be thinking about what if we have a situation like this where yes there's a null in this level but what if this is not the last level what if over here this node also has a couple non-null children does the algorithm I non-null children does the algorithm I non-null children does the algorithm I just described still work for this tree let's test it out let's say we pop all of these and then we get to this level we pop this append its two children which are null pop this append its children and then we get here we pop it we see okay it's a null value now we expect that everything we pop should also be null and if it's not the case that means this is not a complete binary tree so next we're going to pop these two notice how it's not null so that means this is not a complete binary tree so you can see that this pretty basic algorithm does work for pretty much every structure it will tell us whether a tree is a complete binary tree or not and since we're just doing a pretty basic breadth first search the overall time complexity is going to be Big O of n that's also going to be the memory complexity in the worst case so now let's code it up so as with every breadth first search you want to start with a Q we're guaranteed that the root is going to be non-null but that is going to be non-null but that is going to be non-null but that wouldn't matter the way I'm going to code this up anyway but I'm going to initialize this cue with the root value we have to pass in an array to initialize the queue so next we're going to run our breadth first search while the Q is non-empty we're going to pop the Q is non-empty we're going to pop the Q is non-empty we're going to pop from the queue we pop from the left side because we're going to be pushing to the right side it's important to do it this way because we want to Traverse every level from left to right so when we pop the node we want to take the node's children and append them to the queue so node.left and append node Dot right but node.left and append node Dot right but node.left and append node Dot right but it's possible as we're appending children to the queue that we end up appending a null value to the queue it's also possible that the root could have been null so before we try appending its children we have to first make sure that the node itself is non-null so let's the node itself is non-null so let's the node itself is non-null so let's make sure if the node is non-nulled then make sure if the node is non-nulled then make sure if the node is non-nulled then we append its children but what if the node is null remember that's important because that's what's going to tell us whether we have a complete binary tree or not so when we do have a null node then we're going to run some different logic here at this point we expect every node that we pop to be null so we're going to say while Q let's just do the same thing we kind of did up above here except we're going to do it slightly differently we're going to say Q pop left we're also going to call this node but that's not really super important but we want to make sure that this thing that were popping and actually we don't even need to assign it to a variable we're going to check if this node that we just popped is non-null then we have we just popped is non-null then we have we just popped is non-null then we have to return false because we were expecting everything to be null but now we found a non-null node that means this we found a non-null node that means this we found a non-null node that means this is not a complete binary tree so we return false now if we never execute this meaning we never execute this false we're definitely going to execute this while loop then our Q is going to be empty then we're going to come up here and we're going to exit out of this loop as well and then out here we can go ahead and return true because we know we do have a complete binary tree so now let's run it to make sure that it works and as you can see yes it does it's pretty efficient even though the runtimes on leak code are random if this was helpful please like And subscribe if you're preparing for coding interviews check out neco.io it has a ton of free check out neco.io it has a ton of free check out neco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon | Check Completeness of a Binary Tree | sort-array-by-parity-ii | Given the `root` of a binary tree, determine if it is a _complete binary tree_.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, 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`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** true
**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
**Example 2:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** false
**Explanation:** The node with value 7 isn't as far left as possible.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 1000` | null | Array,Two Pointers,Sorting | Easy | 2271,2283,2327 |
1,335 | Hey gas, so today we are going to do dynamic programming playlist. Okay but friend, before I start, I want to clear one thing very clearly, the solution means I will tell the question, I will also tell the solution and also samjhaunga the solution very well, okay but. For those who are beginners, there will be a separate place for the concepts and fundamentals of DP. Okay, so in this playlist, I will explain the questions well, samjhaunga solution also well, how I am approaching it, if you want to learn the fundamentals. And if you want to learn the concepts of DP, then there will be a separate place for that. Okay, so moving ahead, today we are going to do medium level question number 135. The name of the question is Minimum Difficulty of Jobs Schedule and let me tell you one important thing. Dunn's question has been asked recently in the interview of Amazon. Okay, this question has been asked recently in the interview of Amazon. Okay, so this question is quite good and a little bit difficult but if you understand it will be solved easily. Okay, let's see. What is the question? Looking at the input and put, it is given in the input that you will have one billion. Okay, that shows the difficulty of the job. Okay, that means there is a job whose difficulty is six and it is not necessary that it will be sorted, none in descending ascending. It is possible that this input has been given in the order and will be sent. Okay, look, I have written the important points of the question here. Okay, so first of all, jobs are dependent, what does it mean that today I take this You did one job, it is okay and the next day you are saying no, the next day you are saying let's do the three, it is not so, if you are doing the three, then you will have to do the same jobs as before. You will have to complete it, okay, it means it is job dependent, now you can do it only when you have completed your four punches and six. Okay, so the first point is, let's move ahead and you have to do at least one task every day. You are not someone. You can't sit idle even for a day. Let's take someone else's job. If you do three jobs in one day, it's okay. Whatever difficulty he faces in the day, whatever is the maximum in these three, it is okay for him. The difficulty of the day is ok, okay, now what you have to do is that you have to reduce it every day, it is okay to do the job every day and you have to keep the difficulties of every day and add the difficulties of all the days, okay maybe. These two are 654321. How many days do we have? We have given two days. D = 2. Let's D = 2. Let's D = 2. Let's reduce these two on our first day. If the number is okay in the van, then who is the maximum among the two? It is 6. Okay, that's it. After that, what did you do that on the second day you have only one day left, now you have to do all the tasks, right, you cannot leave any job, okay, so on the second day you will do all these tasks, which is the maximum among them, then it is four. Add the maximum of both the days, how much will come, 10 will come, 6 plus 4, 10, let's say this is your 10, because initially you did 6 and 5, then you did 4, 3, 2, 1. You changed your main, first you did it. First let's write 654321 man, there are three in it, I am getting even less, this is what you have to find out the minimum difficulty of the whole country, then collect from this, if it is done, then collect from all, see, which is our solution, which is our answer, what is that? Maybe 654321 Okay I have done all this in the first day okay give this equal tu mein so who is the maximum of this first day 6 who is the maximum of the second day van so what will be my answer 7 this is my output see If this is not the output, then you can do only six on the first day because you do not have to do one task every day, there are other tasks in it, then you must be having a little idea of solution 54321 in your mind, each and every thing. So it must have been that there is a question of dynamic programming so I can do this that first I will start thinking that I just took the first task in the first day in D = took the first task in the first day in D = took the first task in the first day in D = 1, okay, after that in the remaining days I took the first task. So now what we did was that how many are left, three, two, one, okay, and then made another recursive call, let's solve this function, okay, then in this, we will think the same that in the first day, we took the punch, only then the rest. Solved the problem by making a call, ' then the rest. Solved the problem by making a call, ' then the rest. Solved the problem by making a call, ' Brother give four three two one nickel. Similarly, if you write down four nickels properly, you will understand what is going on. Here, using this example, let us see how we can do it. Okay, now look, right now I have two days right now and I have a lot of jobs to do in these two days. Okay, what I said in the beginning that what I do, I will only pick the one with i = zero. Okay, I will only pick the one with i = zero. Okay, I will only pick the one with i = zero. Okay, this is my indexing. Zero One Two Three Four Five What is the maximum difficulty? I did only one job in the first day, so the maximum difficulty will also be the same, so the maximum difficulty has become six. Okay, the difficulty of the first day has become six, now what is left with me? What's left with me, six, now I have taken out six, now I will call Recojan, right, friend, to solve one, what else will I have, five, four, three, one, so on the first day, I have done six, okay, so in the beginning, my Pass two days, now I have only one day left, okay, now one day is left, so how is this base, one day is left and you don't have so many jobs, you will have to do all the jobs, otherwise you can do all the jobs, okay? How can you get the maximum out of this? You can get the maximum out of 5. So, now you give it to Max equal to you. There was only one day left, so you punched out and returned it. Here I am 11, the difficulty is okay, this is our first answer. It is clear till now see what happens because of man, okay, this one who gives our result, okay, now what I am saying is that I will make it equal to zero also, okay, so I did this and did this too, okay So it means that on the first day, if I have done six more punches, then what will be the max difficulty? On the first day, I have done six more punches. If I come on the second day, then give it equal. There is only one day left, so only one day. If there is anything left, you will have to do all the tasks. Okay, and Magazine Devan is left, I have only one day left, so how can I do it, you will have to do all the tasks, so now leave for here, you have done all the tasks and you have taken out the maxi. Yes, what will happen, which is the maximum among these, if it is three, then three is returned + 3, which is the maximum among these, if it is three, then three is returned + 3, I have collected more than that, I have collected only from 11, I have collected only from 10, okay, so let's see, so now I am saying that it is possible or not, I am 6. I will do 5 and 4 and I will also do 3 in the very first day. I will do 3 in the very first day. So I have done 6543 in the very first day and which of these is my max? Then I said let's do the rest. Hey, what are two left for me and one is left, and only Devan is left, so this is the base case, okay, then do both the tasks quietly and what is the maximum given, I had a base case, so I returned two, plus you are for every day. Maximum difficulty added, Maximum difficulty of the first day, six, Maximum difficulty of the second day, you are fine, I am getting better answers, I want the minimum of these, isn't it the minimum of the ones that have come after adding the difficulty of the entire country, ok brother. There is only one, I have returned it, I plus van, on the first day of the match of every day, I am saying that I will complete all the tasks in the first day, because you should not let any day happen in which you do not have even a single task left. Okay, this is clear, so till now you must have understood that brother, we have to write a simple for loop, zero is my index, let's take man, okay I <, you will have to keep coming out the maximum, okay, you will have to keep coming out the maximum, given the maximum and Now my new element will come and I will solve it, once I get a result that brother, if I did only zero intake in the first day, what result will come? Is it okay if I did zero intake on the first day? I did the job only on the first day, so its max di will be added, plus what I was saying is that they will call Recjan, what will I say in that, brother di - 1 that they will call Recjan, what will I say in that, brother di - 1 that they will call Recjan, what will I say in that, brother di - 1 will be saved for that and the index will increase, okay, the result that came from that. I will make the final result is ok and I will keep getting the minimum every time, ok the final result is the smallest, till now I have understood exactly what I have written that I started from index i = index written that I started from index i = index written that I started from index i = index zero, ok in the beginning I just You have done one job, the first one is fine, you have done the first one, and I am checking, after adding the maximum difficulty of the first job, and then solving the remaining ones, it is okay, then when the second form starts, who will I catch? And in Indore the maximum will be reached and after that I will add six and what will I say this time, so you mean I am saying that you should solve from index 2 onwards, okay then see, what I told you is doing exactly the same that one- I doing exactly the same that one- I doing exactly the same that one- I took one element first, checked the rest, okay then I am saying no, I will not solve one element, I will solve these two again, then I am saying and checked the rest, then you are seeing the index for the next time. They are increasing, I just checked, after that I sent it from I Plus van asking you to give me the minimum nickel for it's okay, it will be like this for us, it's okay and Han Rikjan is calling, so you can also do memories. Okay, we will store the days thing in it, we will store the index thing in it, okay and we will store it and as the results keep coming, we will keep storing the results of our analysis in it and as soon as we came to know in any such stage, Deepika is and Before that, you had to understand that this is the part that I have shown, which is the remaining solution. You are making a recursive call for it and your expecting call will bring me the correct result. Okay, so it is exactly like the story told right now. Court also does this, we will write the code from it, okay and we will do the memorization in Excel last so that we do not get a single set of time limit, it is okay for us line by line so that it gets cleared better, okay then look, the question is exactly the same as I told you. Okay, now you understand the points that I have written, now after reading this question, you will start understanding, the question explanation is a bit tricky, it is just that, you have to read it carefully to understand, but what I explained in the video. If you read and understand the points which were told to you while doing the court, then after that a question will start to be understood. Okay, and I had explained it to you with the example, so let's start doing the court exactly as told, okay first of all. So friend, let's find out the name n which is the difficulty of your job. Difficulty variable is very big, so I will make it smaller, I will say JD, okay, gd.ise, okay, we have found out the size, okay, one more thing, we are looking here. Yes, an example has been given that I have a total of three jobs and how many days have I been given, I have been given four days, it means that you will do one job every day, otherwise one day will be left free for you, brother, I have three jobs and four more days. You should not have a job every day, so in that case you have to return -1. so in that case you have to return -1. Okay, and what I said is that we write a recursive function which will solve our question. Okay, in that we send JD and send the size. Let's give the index from where to start, the index is zero. First I will say that brother, I have to start from zero. I have chosen the first one, okay and I have sent the number of days. So now let's write its solution. Ok and solve. Vector of end k di Then we will loop out for and return. This is our base case. This is the base case here. I comment here. I am the only one in the left ten. You have to do all the remaining jobs in this one. That's okay and Return it's key first I will take I index I 0 or end van take both or index ID index 012 I will open all three okay so see brick max difficulty it is equal tu something nickel which is my final result okay now see what I have done I had said that try possibility is ok or I am saying to check all the possibilities of the van job or if I try all the other children's jobs in the remaining days then the total minimum result that will come to me will be something. Okay, now look, you will have to keep max coming out every time Okay and finally, after trying all these, I will store my final result and return it here, final is okay, so this is done. Our solution is exactly as told, let's run it once and see that our submission has been accepted. Let's see after submitting. Okay, why is the time limit giving one seat because we have not yet done the memorization? There are a lot of recension calls. If we are doing this, then a lot of repetitive results will come, if we reduce one, what did I say that I will take one, look, two parameters are changing, our request is only in the call, two parameters are changing, I plus one and the - 1 Ok I plus one and the - 1 Ok I plus one and the - 1 Ok then it's ok who will store it now see what all the changes are happening, if the index is changing then let's check the maximum limit of both, index from constant means it is going up to 300, so I take it till 301 and give the change. Do, I took 11. Okay, now I will check before doing the recursive call. Okay, let me initialize it from mines van se, which is ours. I set t - 1 size of t from mines van se, I have not set t - 1 size of t from mines van se, I have not set t - 1 size of t from mines van se, I have not run it from ours. The cash that we have is also called cash, either I call it cash or it is fine, I have stored it in it is fine, now before making the recension call here, check brother's off mines so that I can do it later. If there is no mines van here, then it means it has been stored, then we will attend. Okay, so now if we submit it, then most of the family will be submitted because I had solved this question a little while ago, look at it has been submitted, neither did it come. Hope you must have understood and this is your memorization technique, okay, there is another good technique, it is called bottom approach, this is top down approach, okay, there is also a bottom up approach, there is a separate video for that. Banagi But this is the most basic and best method Reconc Plus Memorization because in DP I memorize it. Okay, if you have any doubt in this then raise it in the comment section. | Minimum Difficulty of a Job Schedule | maximum-candies-allocated-to-k-children | You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `ith` job, you have to finish all the jobs `j` where `0 <= j < i`).
You have to finish **at least** one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done on that day.
You are given an integer array `jobDifficulty` and an integer `d`. The difficulty of the `ith` job is `jobDifficulty[i]`.
Return _the minimum difficulty of a job schedule_. If you cannot find a schedule for the jobs return `-1`.
**Example 1:**
**Input:** jobDifficulty = \[6,5,4,3,2,1\], d = 2
**Output:** 7
**Explanation:** First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7
**Example 2:**
**Input:** jobDifficulty = \[9,9,9\], d = 4
**Output:** -1
**Explanation:** If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.
**Example 3:**
**Input:** jobDifficulty = \[1,1,1\], d = 3
**Output:** 3
**Explanation:** The schedule is one job per day. total difficulty will be 3.
**Constraints:**
* `1 <= jobDifficulty.length <= 300`
* `0 <= jobDifficulty[i] <= 1000`
* `1 <= d <= 10` | For a fixed number of candies c, how can you check if each child can get c candies? Use binary search to find the maximum c as the answer. | Array,Binary Search | Medium | 907,1886,2000,2027,2188,2294 |
1,913 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem maximum product difference between two pairs a pair is defined as two numbers and the product difference between two different pairs is defined as the product of the first pair a * B subtracted by the product of pair a * B subtracted by the product of pair a * B subtracted by the product of the second pair which is C * D so this the second pair which is C * D so this the second pair which is C * D so this is just the definition now in terms of like the example given an input array like this which is guaranteed to only contain positive integers and is going to have at least four elements in it we want to choose four distinct elements from the array such that we maximize this formula initially you might think let's just brute force it but actually this is math and we can try to notice some patterns which there are here what do you think is going to lead us to maximize this formula we probably want to maximize this left side and we probably want to minimize this right side because we're adding this amount and we're subtracting this amount okay how do we do that well when you're just taking the product of two numbers you probably want to maximize each individual number cuz the product of those then is also going to be maximized when you want to minimize the product of two numbers you probably just want to minimize the those individual numbers once you understand all of that you realize what this problem is really asking for is find the two maximum elements from the array they have to be distinct and also find the two minimum elements from the array and they also have to be distinct once you've done that you can pretty much just apply this formula and then return the result because that's what we're trying to do here return the product difference between these two pairs so how exactly do we do that your mind might jump to just iterating over the two arrays and try to find the two Max and two minimum elements but there's actually an easier way to do this we can rearrange the array if we want the maximum elements and the minimum elements it probably makes sense to take the input array and sort it because when you do that we have pretty much solve the problem because think of it if you had four numbers and you sort them they look like this 1 2 3 four what do you do these are the two maximum elements these are the two minimum elements we can apply the formula we just solved the problem the downside of this solution is the time complexity is going to come from the Sorting which is going to be n log n no extra memory needed though depending on how the Sorting is implemented I assume you're not going to implement that from scratch you're probably just going to use like a library method now can we do better yes we can because as I talked about the solution where we just iterate over the array and try to find the two Max and two minimum elements if we can implement it correctly is going to be Big O of N and also no extra space needed so that is the target solution before I explain this solution I do want to mention you might forget that there is another way to sort numbers with a data structure called a heap and you might forget that because the Sorting solution is just so simple but actually we can solve this problem with a heap and I think we'll actually need two heaps that can actually also be done in Big O of end time now the downside is since we are using a heap we're going to need extra space I'll briefly explain the solution for that what we would do is first create a Max Heap from all these elements we would do that with a method called heapify which actually runs in Big O of end time and once we've done that we created the max Heap we can easily get the two maximum elements just by popping from that Max Heap twice each pop is going to be log n so the overall time complexity of getting the two Max elements is going to be n plus log n and of course n is bigger than login so we can just forget this term and we would do pretty much the exact same thing to find the minimum elements only difference is we would also create a Min Heap to do that then we pretty much have solved the problem once we found these elements we can apply this formula okay so that's the Heap solution I won't code it up because there is a more efficient solution that doesn't take extra memory it is finding these two elements now the question is how do we do it well for the most part I think it's just going to be easier if I explain it within the code but I want to give you a bit of the intuition so let's say these are our numbers we're going to keep track of the max element I'm going to call that Max one and we're going to keep track of the second largest element I'm going to call that Max 2 and we're going to do the same thing with the minimum elements the most minimum is going to be Min one and I'm going to call the second smallest element Min 2 we're going to keep track of these in these variables since we're trying to maximize these elements let's initialize them to small numbers they will be initialized to zero both of them since we're trying to minimize these let's initialize them to large numbers they will be initialized to Infinity initially what we're going to do here and I guess I should add the second one for each of these two at a high level we're going to iterate over every element in the input array by the time we've gone through this entire array we should have picked out the two large lest numbers in this case six and seven and assign them to these two variables seven will be first because Max one is the largest Six will be second cuz it's uh the second largest and we're going to do the same thing with the minimum elements so two and four are the smallest two is going to go here and four is going to go here the smallest is going to be two and second smallest is four then we found our solution and you notice something as long as we put the two largest numbers here and the two smallest numbers here we actually guarantee that there won't be overlaps between these because how could it be possible that we did not choose four distinct integers if we do that the only way that would be theoretically possible is if the two largest numbers also happen to be the same as the two smallest numbers how would that be possible if we have four integers in the input it would only be possible if all four of the integers happen to be the exact same they could be all fours or it could be all like threes for example and that would be fine because that would mean two of these threes belong to this group and the other two threes belong here they technically are distinct numbers the numbers aren't distinct but the index of each number is technically distinct we're not reusing any of these individuals so that's why this solution will work now in terms of implementing it I will mostly save that for the code but at a high level I'll quickly go over it for each number the way I'm going to code it I'm going to ask myself is this number larger than the second smallest number and in this case it is next I'm going to ask myself is it larger than the largest number yes it's larger than the largest so what I would do is put the five in this spot and I would take whatever number happened to be here and then move that to the second smallest and in verely I would kind of do the same thing with the minimums as well like for example with five I'd say is this smaller than Min 2 yes it is so before we now replace this with five we're going to ask ourselves is it also smaller than the smallest number and if it is then we actually put that five over here and we would take whatever we have here and move it over there that's the idea now I'm going to code it up so here I have just initialized those two variables as we kind of talked about in the drawing explanation I don't think you want to see me type all that out now we're going to implement the algorithm go through every number in the input array like I said we're going to first ask is this number larger than the second largest number that we have okay it is so now the question we need to know is should we put n in this spot or should we put it in this spot so let's find out now is n also larger than Max one if it is then we say Max one is going to be equal to n and we would also say Max 2 is going to be equal to the original value of Max one in Python you can do this double assignment both of these will pretty much be executed in parallel at least that's how you can think about it now if this wasn't the case then we can't do that then we can only replace Max 2 with n so that's how we do this part now the next part is with replacing the minimums you might be thinking should we put an else if here should we say n is smaller than min2 and you'd actually be wrong we don't need an else and that will make the solution incorrect you don't put the else here because as we're going through an input array for example it might be 1 2 3 four initially when we get to the first one this if statement is going to execute because we initialize these to zeros so we would end up setting like Max one equal to 1 if we had an else if here then this part would not execute but that would lead to the wrong solution because we know that one actually is the minimum it's not the maximum it might temporarily be set to Max one but it's not the largest in this array what we're saying here by having both of these just be if statements is that sometimes at some point they might overlap like Min one might have the same value as Max one that's okay because we know for sure by the end of this array they will be set to distinct integers at least integers at distinct indices so that's why we don't need the else over here to finish this up if n is smaller than min2 now we need to ask ourselves is it also smaller than min1 if it is we do pretty much what we did up above Min one is going to be set to N and min2 is going to be set to the original value of min1 otherwise we just replace Min 2 and set it equal to n so that's pretty much the entire code only thing left for us to do is return the result which they pretty much gave us the formula to do that Max one multiplied by Max 2 subtracted by min1 * multiplied by Max 2 subtracted by min1 * multiplied by Max 2 subtracted by min1 * min2 so now let's run this to make sure that it works and as you can see on the left 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 NE code. thanks for watching and I'll see you soon | Maximum Product Difference Between Two Pairs | make-the-xor-of-all-segments-equal-to-zero | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**.
Return _the **maximum** such product difference_.
**Example 1:**
**Input:** nums = \[5,6,2,7,4\]
**Output:** 34
**Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 \* 7) - (2 \* 4) = 34.
**Example 2:**
**Input:** nums = \[4,2,5,9,7,4,8\]
**Output:** 64
**Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 \* 8) - (2 \* 4) = 64.
**Constraints:**
* `4 <= nums.length <= 104`
* `1 <= nums[i] <= 104` | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. | Array,Dynamic Programming,Bit Manipulation | Hard | null |
1,365 | and today we will be discussing the question how many numbers are smaller than the current number in this question we are given the array norms and for each value we need to find out how many numbers are in the array that are smaller than this particular number at the end we need to return the answer in an array so we are given certain example with the problem we'll first understand how this particular output was generated so the first input that is given to us is 8 1 2 and 3. and when we need to return the answer we'll have an array of same length we see the number 8 at first we see that all the numbers are smaller than this particular number so at this start every four numbers which is 1 2 and 3. now we'll take number one we can see that there are no numbers which are less than number ones so it will be 0. now we see number two and there is only one number which is less than 2 which is one so we will put one as the answer same for this 2 as well one for this 3 there are three numbers which are less which is one two and two so the answer will be 3 over here that will become the output we are looking for so let's clear all this let's talk about a very Brute Force solution so in a Brute Force solution for every number that we have we can check how many numbers exist which are smaller than this particular number so when we check this for 8 we'll get there are four numbers which are less so we'll return 4. now for one when we check we see that there are no numbers so we'll return 0 and so on so as we know that we are checking for each element all the other elements so the complexity in this case will turn out to be of n Square which is a very high complexity now what we can do to optimize this particular approach the easiest way of finding out how many numbers are there which is less than any particular number will be when these array is given to us in a sorted fashion so if the array would be like this we can simply know with the index of this particular number or any number that there are four values smaller than this particular number three values smaller than this number now in the case when the values are equal we need to take a special things into consideration so from the example we know that in case of duplicates the index will be the first Index this one which we saw so now we see that if we know the index of the values in the sorted array we can easily return the answer so in order to bring down the time complexity from n Square we need to use certain space to hold these particular values so if we hold the index of these particular values somewhere well suppose we hold them like this the value 1 has an index of 0 the value 2 has the first index is 1. value 3 has index of 3 and value 8 has index of 4. so if we have this mapping with us and now when we reiterate from this array we can just put the index value at the resultant array which would be 8 has a value of 4 so we'll put 4 1 has a value of 0 so we'll put 0 2 has the value of 1 we put 1 again 1 and 3 as a value of 3. so this again gives us the same result and now the time complexity is also lower now it's time to code this particular approach we'll start off with having a result array and we can easily create a clone for the input array once we have this array we will just sort the result array in order to find out the indexes and now we need to store this index somewhere so we'll use a map because it is kind of a key value pair for us we'll put the value if it is absent so by using a function that is provided by the map you can do an if else check as well for the keys if it is present or not once we have this map ready we can again iterate this time on the names array we can now change the value at this index array directly getting the index from this index hashmap at this particular position once we are done we need to Simply return the result array and that completes the coding part now let's try to run this code so it runs successfully let's submit this so it got submitted successfully the time complexity in this case is n log n down from n Square because we are doing a sorting well space complexity is O of n as we are using in results array so that's all for today's video do let us know your thoughts comments and query in the comment section below thanks for watching see you in the next one foreign | How Many Numbers Are Smaller Than the Current Number | how-many-numbers-are-smaller-than-the-current-number | Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`.
Return the answer in an array.
**Example 1:**
**Input:** nums = \[8,1,2,2,3\]
**Output:** \[4,0,1,1,3\]
**Explanation:**
For nums\[0\]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums\[1\]=1 does not exist any smaller number than it.
For nums\[2\]=2 there exist one smaller number than it (1).
For nums\[3\]=2 there exist one smaller number than it (1).
For nums\[4\]=3 there exist three smaller numbers than it (1, 2 and 2).
**Example 2:**
**Input:** nums = \[6,5,4,8\]
**Output:** \[2,1,0,3\]
**Example 3:**
**Input:** nums = \[7,7,7,7\]
**Output:** \[0,0,0,0\]
**Constraints:**
* `2 <= nums.length <= 500`
* `0 <= nums[i] <= 100` | null | null | Easy | null |
274 | hey YouTube Welcome Back and today we have this problem it's called H index uh given that if integers called citations where citations of I is the number of citations a researcher received for their eyes paper return the research on each index okay and that there is the each index occurred a current humidity then is defined as the maximum value of H that the given researcher has published at least um age people that have each been seated at least eight times what that means because yeah I read these times multiple times try to understand however if you look at this example I guess we could understand it quite easily so we have these papers we have and this the output should be three because why because the researcher has right now five papers okay and for each paper we have um three what for the first one we have three citations the second zero six one five and since we the researcher has three papers with at least three citations each and the remaining two with uh with no more than three station each their uh each index is three so for this one the index will be one so let's just I know it's sometimes this problem some a lot of people say ah it's not uh it's not easy or maybe it's not um easy to understand so first of all if we don't understand anything let's just take a hint um so we said approach to sort what are the possible values of each indexed um a faster approach is to use extra space okay so the old hint is in the problem and I just look at what um and each index so if you order an interview and right now we are in this problem that we don't understand what is the each index if let's say that I read it and I didn't understand it so I will ask my interviewer okay can you just describe more because I didn't understand this one so let's just try to read here and this uh this article okay the name purpose okay the H index is defined as a maximum value of H such the given author or Runner has published at least eight people's at each um each peoples that have each been seated at least eight times so if we looked at this one and we say that the index is designed to improve upon similar measures such that total number we don't care about that so for this example we have this would be the HP force and this will be the most um papers that was uh appeared each time so for this one we have this and we have this so we just the more density teaching so this is what we talk about so if you don't understand it I guess I hope you understand it right now but let's just try to think about it and I'll tell you something when I do the solution um I guess maybe you could understand it better so let's just start in the code so the problem it will be first we want to get the H index what is the eighth index it's defined the maximum value of H certainly the given researcher has published at least eight times so let's just say that we want to get a number that the publish has uh published at least each time touch that given research that has published at least each time people that are okay so for this one we are saying again we have three zero six one and five and the researcher has five Clippers as you can see right now and in total of each of them will have these quotations like each number is representing a specific quotation uh situation sorry and since the researcher has three papers with at least three citations we have three and five and six and remaining two with no more than three zero and one okay and so uh their H index is three so that's it so let's just try to how to find this H index because if you understand it okay we understand how we can find it so first a good approach I guess is when we talk about the maximum it's a good approach is to sort and we want to get a hint and with the good approach is to sort the array so we will make sure that the big the pickets are in the end and the small cell in the beginning so let's just make a try to make a photography let's to sort this array the sword a and B it will be the E minus B okay so right now we sold the array so what I'm going to do let oil equals zero and I will say um I'll make a while loop while oil is less than citation okay and you will understand why I'll make the other this one citation of citation let's see the significant length when this one will be in let n equals citation.ly n minus one minus oi and I will say um while oh yeah less than the length and uh and the position of on and this um position is bigger than or this index is bigger than all we'll increase I plus one I plus and we return on so uh what's going on so first of all let's just try to walk you through the code so we sort the application because right now we want to get to the maximum um the maximum value of uh of the H index which was being uh like was a period each amount of times so because of that we will just to get we will sort arrays right now let's just talk this one as an example and just try to walk you through the solution so first of all we have this array sorry we have this array let's just and we saw this array so the array will equals like that this zero and one and three and five and six okay and we have the oil you can call it answer of result is this or III like it doesn't matter call it whatever you want and we have this I and this I will be the H index that we are going to return so what I'm going to say that because the edge index again is uh which index is uh um is the maximum value of H that given a researcher has published at least each paper each at least each papers that have been seated at least each time so we have this number three and the three would at least it was publish at least three times and it was the maximum because someone say okay uh maybe we could use one because one it was uh was four times not three times so one is more but one is not the maximum three is the maximum okay so we search for the maximum so right now we have in the this maximum The Edge index for this one is three because three was appeared three times and it's the biggest one you we can say one because one was appeared four times but three is bigger than one so we would take three so I will use I will after sorting the array I would say that okay um let's just make sure that we are getting this index let's see that how this works so I will walk you through the code so I first will be zero so um let's call the citation of oil for this one so if I less than length this I guess this is quite understandable but this one we talk about because we want the biggest again let's just look at where you want the maximum value of H so I want three I don't want one so I want the maximum one so I'll start from the end and I'll say Okay um if citation of n minus 1 minus i n minus 1 is um let us make n minus one is four okay minus I will be minus zero so it will be equals um four n minus 1 minus i n minus 1 is 4 and minus I zero so equal four so we are here so it will be six is six bigger than I or is zero yes okay so increase I plus one so right now I will equals one okay so let's make another loop if I less than n yeah I is less than n okay so if citation of n minus 1 minus I is bigger than I so um situation the N minus one in response four minus I it will be one the value of this one is five it's is it minus bigger than I yep so okay add one so it will be two so let's just make a loop again so I'll say okay uh I is less than in yes oh it's listening if citation dot uh citation of uh of the index n minus one minus I greater than I so let's see um n minus 1 is 4 and the I2 so it will be two so it will be three so three yeah three is bigger so plus so it could be three when we do this one the last one it will be okay I it's more than in yup I3 and N is uh in is five if citation n minus one minus I bigger than I let's just see um situation four and three will be one and the index of one is also one so it will be one no this is not true so this while loop is in and we turn I so i3 and that's it so um are you my search is quite good I hope my solution was quite understandable uh if you like my description make sure to subscribe and hit the notification Bell so you will never miss a video and see you in future problems | H-Index | h-index | Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper, return _the researcher's h-index_.
According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times.
**Example 1:**
**Input:** citations = \[3,0,6,1,5\]
**Output:** 3
**Explanation:** \[3,0,6,1,5\] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
**Example 2:**
**Input:** citations = \[1,3,1\]
**Output:** 1
**Constraints:**
* `n == citations.length`
* `1 <= n <= 5000`
* `0 <= citations[i] <= 1000` | An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space. | Array,Sorting,Counting Sort | Medium | 275 |
1,288 | hello everyone i hope all of you are having a great time and welcome to day 20th of february record challenge the question that we have in today is removed covered intervals here in this question we are given an array of intervals wherein each interval has two endpoints the starting index and the ending index what we call as l i and r i what we need to do we need to remove all the intervals that are covered by other intervals in this interval set also we need to return the number of remaining intervals that are left after you have removed all the covered intervals up here in this example they have provided us with an interval set as 1 4 2 3 6 and 2 8 as you can see that 3 6 is already covered by the virtue of 2 weight as a result we can simply remove 3 6 the number of remaining intervals tend to be 1 4 and 2 8 and the count happens to be 2. this is what we need to return without further ado let's quickly walk through the presentation that i have created for this and i will be walking through the i'll go as well as these examples by the ppt so let's get started remove covered intervals lead code one two double it's a medium level question on lead good and i totally feel the same the approach that we are gonna use to solve this question would be a greedy approach and we have already solved couple of questions in the past with respect to the same approach to name few i can tell merge intervals was the one minimum arrows to burst balloon was another and there are few more which i'm attaching in the description below if you want to try out similar questions on the same approach do have a look at them as well now let's get to the point let's consider a slightly different example to what was specified in the question i have added a new entry 1 comma 2 to the example that was specified in the question the total number of elements that we have is 1 4 3 6 2 8 and 1 2. what i'm going to do i'll again follow the greedy approach i'll sort these intervals first on the basis of x coordinate in the increasing order and then decreasingly on the basis of y coordinate whenever there is a clash between x coordinates so one assuming that i have done it let's see the updated intervals array you can see that the x coordinate matches over here so in such case we will give precedence to a higher y-coordinate as a result of it one comma y-coordinate as a result of it one comma y-coordinate as a result of it one comma four comes at first then one comma two let's proceed ahead the next would be sorting on the basis of x coordinate so we will get two comma eight followed by three comma six now if you carefully observe this updated array you can simply assume that all the elements in this array would be in the increasing order of x coordinate so we have increasing x here one in or increasing or similar it can't be decreasing so 1 then we have 2 then we have 3 so we can simply eliminate x coordinate here and we don't need to do any manipulation over it the area of interest would remain in the y coordinate how let's walk through an example so what i'm going to do i'll create a variable and let me just change the color of pen for better understanding i'll create a variable range of y-coordinate and by default it range of y-coordinate and by default it range of y-coordinate and by default it will be mean slice to minus 1. what do we see the first element now which happens to be 1 comma 4 now is this range overpowering this 4 value no it's not that means this element will be part of your answer since we have included this range that is 4 to be part of our answer set we will increment this variable to the maximum of value that is set here versus this so what is that minus 1 and 4 you get 4 so the range gets updated to 4. now let's look at the next entry happens to be 1 comma 2 and we will not look out for the x coordinate because we know it's already increasing in nature we are only interested in looking out for the y coordinate range so what is the value here the value is 2 and the current max range that we have reached happens to be 4 that means we can simply eliminate this variable this is not needed it is already covered by some other entry in the past and we can get this information from the range variable that we have created and the value that is here is 4 here it is 2 we can simply delete this element since we are deleting this element we will increment the counter variable to 1 which is because we are also counting how many intervals have we removed let's proceed ahead next what do we see that the next entry is 2 comma 8 we are not interested about x coordinate we only look out for the y coordinate happens to be 8 is the range overpowering 8 no it's not as a result of which we have to include this as part of our answer along with this we will update the range since we have included this as part of the answer to eight so the range gets updated to eight let's proceed ahead next we see is three comma six again we will not look out for the x coordinate we are only interested in the y coordinate what is the value at the y-coordinate it is 6 y-coordinate it is 6 y-coordinate it is 6 is 8 over powering 6 yes this range that we have already reached is overpowering 6 because it's a lower value as a result of which we can simply eliminate this and delete this element because this rain has already been covered in the past as a result of it the count variable gets updated to 2. that simply signifies in totality we have removed two intervals so what is the length of the initial input data set that was given to us how many intervals were there they were in totality four intervals how many have been removed we have removed two intervals what is the remaining count the remaining amount happens to be two and this is what we need to write on pretty simple and straightforward no rocket science involved in it the crux of the problem lies in this sorting approach that we have followed because we are eliminating one coordinate and then operating on the other coordinate along the y axis in this case without further ado let's quickly walk through the coding section where i'll conclude the approach so as talked in the ppt first thing that i'm going to do is to sort the intervals first on the basis of x coordinate if it happens to be equal then i'll sort them in decreasing contour on the basis of y coordinate otherwise we'll go for the increasing x coordinate i have created an answer variable for storing the answer and i have created a previous range variable for the y-coordinate so this only signifies for y-coordinate so this only signifies for y-coordinate so this only signifies for the y coordinate we can name it better then i start the operation over the intervals uh using a for loop if my previous range happens to be greater than equal to the current element of the at the index that means the previous range is already cover covering this interval as a result of which i increment my answer variables so this answer variable is not actually storing the answer rather it's storing how many removal count let's rename it to removable count how many intervals have we removed moving ahead i update my previous range to mat dot max the current y coordinate and the previous one we always look out for the maximum out of these two in the end i simply return intervals.length end i simply return intervals.length end i simply return intervals.length minus removable count so let's summit this up accepted it returns faster which is pretty good and fine in terms of time complexity here it would be equal to order of n log n when n signifies the number of elements that are part of the intervals data set with respect to the phase complexity i think it would be constant space because we are not using anything extra here this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for being here have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then goodbye | 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 |
956 | hello guys welcome to deep codes and in today's video we will discuss liquid question 956 that says tallest billboard so guys although this question is easy to understand as well as code but the complexity arises when you have to solve this question in a memory bound so yeah guys uh in today's video we will learn how we can solve this question uh by using some smart moves right so yeah guys stick to the end and watch the complete video now here what you have to do is you have to um you know make two support of equal height and on which on the support you have to place the billboard so you need to find what is the maximum height of support you can achieve and yeah both the support one that is the left support as well as the right support must be of equal length ok so here to still supports that you need and they must be of equal height and they are a build of rods so there are lots of different lengths like length one length two length three and length six and so on so you need to use these rods in order to make left support as well as right support okay and yeah this uh you we need to try to achieve the largest or the maximum height possible to install the billboard so as the question says tallest billboard so we need to achieve the maximum height and yeah if you cannot support the billboard that means it is not possible to make a lab support and write support equal then in that case return 0. so let's try to go through a few examples here now here in the first example you are given this uh four rods first Rod is of a length one second of length two third of length 3 and 4th of length 6. so guys if you want to achieve tallest billboard with this road then what you can do is you can create the left support combining Rod uh of a length one two and three so this would be of a total length six and the right support would be of Line 6 by taking this road so now both the left support as well as right support out of equal length as well as they are the maximum possible height that can you can achieve using these rods so yeah the maximum height you can achieve is six and that is the height that or the answer that we need to return now if you take a look at the second example so here we have used three rods to make the left support and one and two rods to make the right support and here we haven't used the rod with the length one in any of them so yeah guys you can see here that a rod can be either a part of a left support or a particular Rod can either be a part of right support and it can be possible the dot is not a part of any of them right so yeah by do uh by solving this equation this way this is the left support this is the right support you can get a maximum height of 10 okay correct so yeah guys as I told you the rod can be a part of left support or can be a part of right support or none of them and the question asks us to find the maximum height or most for optimal answer so guys whenever you have something like this that there are some choices for each given index so here A Rod of index for each Rod of index there are some choices these are nothing but your choices So based on these choices you can easily write the recursive solution okay and yeah you need to get the most optimal answer that is you need to return the maximum height so yeah you will take uh the maximum of all the choices correct simple it is so yeah it is easy to write the recursive solution and if you want to uh see how the recursion tree can be built for this question then we can do it in this way so here you are given in this example of six Rod indexing from 0 to 5. so for the first index you have three choices that it would be a part of support one it would be a part of support two or none so if this would be a part let's say index 0 that is Rod of length 1 is a part of support one then you have a height one on the this is the left a support type and 0 that is the right support height So currently this is your situation if it would be a part of support then this would be a situation where the left support is of height zero and the right support is of height one okay so you have three you have you created three states now then uh take for index one so for index one either you can take it in the lab support so then the height of the left support would be 1 plus current that is 2 so overall it would be three as you can take this index one as a right support then our the height of the support would be one comma two that is uh on the left and on right and it would be a part of none then the height would be one comma zero so similarly you can take uh I equal to 3 4 5 from each Stitch so yeah now you can try to build up this recursion Tree on yourself and yeah you can get more idea of how this recursion works now moving on to the coding part for this recursion so here we have build one solve function and call this all function from here this all function takes parameter of rods index sum 1 and sum two so someone is nothing but height of a support one and this is I have taken as a height of the support too now our base condition is when there are no rods remaining in that case we checked if someone equals to sum 2 that means height of raw uh support to an equals to height of support two then simply return the height of any one of the support and indirect condition returns zero because yeah it is it was not possible to make both the height equal then in that case we simply return 0. and these are the three options that we discuss that either a rod can be a part of support one or it can be a part of support or it won't be a part of any then in that case we haven't added in any simply we take the max okay now as you all know that this is the recursive solution and it is not optimal solution uh and yeah if you see here that there are three changing variables some uh index number and some two so total States would be 3 to the power and yeah and this will result in time limit accelerated as well as memory limit accident so yeah we have to think of some better solution in order to optimize our approach and it there is no doubt that we can memorize it so whenever we have recursive solution we can easily memorize the recursive solution so our memorization does what it simply stores the changing variables or the answer at different states so this States so this is a state so this is one state and answer of this state is determined by the index as well as sum 1 and sum two right this will create someone and this will create some too so each state is determined by the changing variables that is index someone and something now if you take a look that there can be 20 different possible value of index 5000 different possible value of somewhere and five thousand different possible valuesome two this is already mentioned in the constraint so if you look at the constraint the index maximum limit is up to 20 and some of all the rod length would be up to five thousand so this is the maximum limit uh for our three changing variables so total States would be 20 multiplied by 5000 multiply by five thousand so that is five multiple ten to The Power 8 and this is very large number so this will surely give you memory limit exceeded right if you have to store this many different of states then it will give Emily so now but if you take a step back and think what was about gold or what was our base condition instead of a base condition we were simply checking what is the height of left sub left support and what is the height of right support that means uh if you look at the recursion code that we already discussed that we were checking somewhere equals to sum to or not right so this is nothing but if someone minus sum 2 equals to zero that is the difference is zero then we can say their height is same okay got it this is the theme right if the difference is zero then the height is same right so yeah instead of using three changing variables we will reduce to two changing variables there is no way possible to not to take index as a changing variables but we can reduce from this two to any one and that one would be nothing but the difference of these two and whenever the difference is zero that means that height is same so we will take the difference now if you look that what will be the range of your difference see the sum 1 ranges from zero to five thousand some two ranges from zero to five thousand so the difference would range from minus five thousand to plus five thousand right if let's say someone is zero and sum two is five thousand so it lower limit would be minus five thousand this and it makes it would be five thousand right five thousand when one of his uh let's say some two is zero and someone is five thousand then in that case maximum limit would be five thousand so if you uh see that there are total of two times five thousand that means uh ten thousand different values possible for this div this is the count of values for this diff uh total ten thousand values are possible here now if you try to find out that how many different states are possible then you can see that here there are two changing variables that is index and the diff this index can have 20 different values and this div can have two multiplier five thousand different values so total two into ten to the power 5 would be the number of states and this is the accepted solution here okay now if you take a look at the coding part it is very much simple here we initialize this DP 21 uh of size for this index and this is the size of this right ah diff and we initialize the DP with minus one and call this all function inside the solve function we have index and div as a input parameters we would check uh okay this is the base condition where no rows are remaining in that case we would check that if difference is zero then return 0 else 10 as a minimum value now guys you might be thinking here that y inside of a DP array we are adding difference plus five thousand one this is because difference can have value up till minus 5000. so uh but we cannot have negative indexes so in the inside this DP address we cannot have negative index in order to convert the negative index to positive we are simply adding five thousand one here okay this is the base condition that if already the value is calculated that means this value is not minus 1 then you simply written the answer as there are three choices so now if we are taking that rod in the left support then what we would do is we would simply add difference plus a rod length if we are taking in the right support we will add difference minus Rod length right and then here what we are checking if we are checking the only the difference okay now guys you might be thinking that why we are adding here Rod of index that is the length of this road here inside the option one or the first choice this is because we need to return what is the length of the support So at the end whatever may be the difference if the difference is zero or not if the difference is zero that means both the rod are of same length then in that case we need to written what is the length of the support right when both the supports are of same length then the difference is zero but in the answer we don't want that we want what is the length so in order to keep track what is the length of the support we would keep track of length of one of the support only and we would keep track of the difference so this difference will tell whether both the support are of same layer and if it is same less then what is the length so yeah we only keep track of one of the length of one of the support and simply add the rod that we included in the left support each time inside our choice right and in the uh and yeah when the difference is zero nothing would be adding but if the difference is not zero we are adding some weak negative number same at maximum the height of the support can be 5000 so we can take any larger value than this 5000 and return it so yeah if the difference is not zero then we are returning some negative large negative value but if difference is zero we would have some positive value and that positive value would be nothing but a height of both the support right so yeah this is how we uh are getting the answer by returning this see we are only returning this when we are uh taking the rod in the lab support in the other case that when we are taking the rod for the right support we only subtract that length from the difference and we do not do we do not return here right we don't add in the retail statement because we simply need a high okay and yeah the third option is pretty much the same that is not to take the drawer in any one of the support so yeah guys that's how we solve this question um so I hope you guys have understood that what we are trying to do here not talking about the time and space complexity the time complexity here is very much obvious that it would be nothing but 21 multiplied by two multiple to 5001 uh because these are the different possible states that we are calculating okay and the calculation of one state will take bigger of 1 only because here there is uh there is no for Loop or nothing else so these all statements we run we go one time so yeah overall this is the time complexity and space complexity is also the same but there would be some recursive check he would be used because this is a recursive function called uh so yeah guys that's all for this video if you guys have still any doubts then do let me know in the comment section make sure to like this video And subscribe to our Channel thank you | Tallest Billboard | number-of-music-playlists | You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.
Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`.
**Example 1:**
**Input:** rods = \[1,2,3,6\]
**Output:** 6
**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
**Example 2:**
**Input:** rods = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
**Example 3:**
**Input:** rods = \[1,2\]
**Output:** 0
**Explanation:** The billboard cannot be supported, so we return 0.
**Constraints:**
* `1 <= rods.length <= 20`
* `1 <= rods[i] <= 1000`
* `sum(rods[i]) <= 5000` | null | Math,Dynamic Programming,Combinatorics | Hard | null |
72 | hey everyone welcome to Tech wired in this video we are going to solve problem number 72 edit distance first we will see the explanation of the problem statement then the logic on the code now let's dive into the solution so here we are given word one and word two we need to convert word one to word two by using these three operations so I can delete 10 character I can insert a character or replace a character and by doing these operations I need to find the minimum required operations to convert word one to word two right which means there are many ways to remove insert or replace characters and I can convert this word horse to Ros but we need to find the minimum number of operations required for this conversion right so for example if I replace H with r and if I remove the center or and if I remove the end e so here I performed three operations right I performed three operations and there are other ways to convert this particular word one to word two there are many other possible ways but that requires more operations for the conversion so we need to minimize those operations so that is what required here right now we will see how we are going to do this so here I'm going to solve this problem using dynamic programming approach so initially I will create a matrix of 0 and the rows will be the length of my word one plus one and the column will be the length of my word two plus one right so I'm going to have two Loops where I will be used to keep track of the rows and J will be the column Index right so first we will start and then we will see what we are going to do at each and every step right so initially my zeroth index the 0th row will be having the column index right so I'm going to be having 0 1 2 and 3. then the zeroth column so we saw Zero throw had the values of columns right so and this zeroth column will have the values of rows so we are going to just replace the row values corresponding row values right so this will be the starting Matrix for us so we will start from iterating from first row and First Column right so we will first update this particular value so when we are updating I will show you guys what we are doing here right now let's start so initially I'm going to check I minus 1 index in my word one and J minus 1 index in my word 2 and I will check whether they are equal right so word I minus 1 is nothing but the H character and word two J minus 1 is nothing buddy our character and they are not equal then I will move to the next condition now I will take the I minus 1 and J minus 1 column value which is from I minus 1 rho and J minus 1 call I need to pick that value so here I am going to get 0 I minus 1 and 0 through and J minus 1 is the 0 and 0th column and I need to pick that value which is nothing but 0 then I will pick I throw and J minus 1 column so here I row is First Column here I is 1. and the J minus 1 is nothing but the zeroth column that is one here so I will pick one here then I need to pick I minus 1 rho and jth column I need to pick three values so I minus 1 row is 0 and J is First Column J is equal to 1 so which is nothing but 1 here then I will take a minimum of these three values so in this case it's going to be 0 and I will add 1. so I'm going to get 1 year then I'm going to take this value and replace and I'm going to update that value in my Matrix in the corresponding I throw jth column that is 1 comma 1 here I will update in 1 comma 1 as 1. right I will show you guys in the next iteration what we are updating right next my J will be 2. so I need to check I minus 1 character and the J minus 1 character so here I minus 1 characters h j minus 1 characters o right now I need to check whether H and O character is equal no they are not equal since they are not equal I will pick the three values and I will take minimum of those three values so those three values nothing but I minus 1 and J minus 1 and I throw and J minus 1 column and I minus one column and J through I need to pick these three values from a DP Matrix then I will take minimum of that and I will add one to it and I will update that in my DP Matrix so here I've updated few values and I will show you guys when the characters are equal right when the characters are equal So currently I am in second row and second column here right now I need to check my I minus 1 character which is nothing but o and J minus 1 character that is nothing but o itself when both characters are equal I will update with I minus 1 rho and J minus 1 column from my DP Matrix so here I need to go to my first I minus 1 is 1 first row and J minus 1 is First Column so I will go to this value and I will update 2 comma 2 with this value one right so what we are trying to do here so we know our row represents the word one and the column represents verb right so we know we are at the I throw on jth column this is nothing but 2 comma 2 I is nothing but the second index in my first word and so if I try to slice word one from 0 to I what I will get I will not include ith index so we will be getting H and over here right then if I try to slice word two from 0 to jth index we know our column is represented by J and the rho is represented by I so here J is nothing but 2 if I try to slice over to from 0 to 2 I will get R and O so here we have one right this one represents minimum operation I need to perform within this substring of characters so if I try to convert word one two word two what I need to do here within this substring what I need to do I need to remove I need to perform a remove operation that's it I don't have to do anything in this particular substring I don't have to do anything I need to perform only one that one is nothing but this value one operation I need to perform if I try to convert we are not converting perfectly because we are only checking its substring here if at least I need to perform within this substring if I try to convert I need to remove H right then I will add R in front of v in the upcoming stages but within this substring I need to remove R that's all we need to do here in this particular stage so as we increase our characters we will be performing the minimum number of operations at that stage right so at the end so after performing all of the operations after checking all of my characters I will get 3 at the end of my Matrix that's all we are doing here now let's see the code so before we call 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'm going to have M and N which is nothing but the length of my word one and the length of my word then I'm going to create my DP Matrix right which is nothing but I'm going to have n columns and EMB Rose M plus 1 right then I'm going to update my DP Matrix and I will be iterating through the row and columns right from M plus 1 row and N plus 1 columns then if I'm in the eighth row I will update with column numbers in my DP which is nothing but J itself then if I'm in the zeroth column I will update with the row values right then I will check my characters in my word one and quote if they are equal I'll update that particular I throw in jet column with the I minus 1 . . . 1 and J minus 1 value right else I will take and update my current I throw in J column with the minimum of my I minus 1 and J minus 1 value then I will take the I minus 1 and jth column value then I will add One Pilot then finally my result will be at the end row and column that's all the chorus now let's run the code so the time complexity is order of n m into n and space is order of M into n as well thank you for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys | Edit Distance | edit-distance | Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**Output:** 3
**Explanation:**
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
**Example 2:**
**Input:** word1 = "intention ", word2 = "execution "
**Output:** 5
**Explanation:**
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
**Constraints:**
* `0 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of lowercase English letters. | null | String,Dynamic Programming | Hard | 161,583,712,1105,2311 |
4 | Hey guys welcome back to my YouTube channel I am astrologer and in this video serial I am solving the problem of lead and today we are going to see the problem which is the media so let's see what is the problem of scientists we can see that This problem is given by the heart attack list in the problem statement that the attacks have 200 terraces with which you can see the sexual attacks returning to the medium of darkness. You can see the example. First example is the chief guest and if we have these two Let's march and what will be the element in it, so for example, if people do then put 1234 and divide by adding the media, you can see it on the gram which will be very much a problem but the problem here is time complexity, that is Bigg Boss. It should be neither, how can we find the correct one for this case, so we have seen the problem statement of this problem, so let us know how we can oppose it as we have seen that We can solve this problem by merging both the legs which we give and find out what will be the media. If we have logo and number of elements then the media that will remain will be the middle element and if we have If we make even number of elementary, then the media which will be there will be the central two elements, by adding it and dividing it, we will get it, but we cannot use it because if we do not have to do the sum of Bigg Boss, then search its meaning. We will have to do the element, then we will have to use something that we people should subscribe * element * element * element in which we have to search, then let us try to solve this problem which is dead without washing, if we do this then people So we will add this thing and this logical left side and a logical right side between share and subscribe if we decide that the war element here is to be taken on the left side element and on the right side which is If we do the media then we can set the people, know that the total element can be considered as 4.5 and refill, element can be considered as 4.5 and refill, element can be considered as 4.5 and refill, then this element is on the left side like this people are present are you consider and apply binary search in it. So we will know its left side is its lt One will be 143 on its left side. Now because we know that in the logical life which is considered in law, there are four elements and already two elements have been considered. From this A B, the remaining element is that of which is the considered element. Is that is to which is to should be aspects should get RSSB to elements should be in zoological park if we consider this then we have finalized the laptops given by these people but how will we determine that the laptops which these people have given Considered is correct. To consider this as correct, we have to compare the remote element for the left leg and the right here right now its elements of the other one and it should be smaller than that like we have to compare these five. Must be smaller with, must be equal to, and must be compared to, must be equal with, if both of these start then we will know why this minimum husband of media has done this and here the element can also do that. Can and can because there is confusion here then subscribe, it should be on the right and left side, if you consider it, then I want to say that the media has done it, I will be on the right side, whatever is right, we have considered it on the left side. Details will remain in between the left and right portion because the left portion has element 1234, the right portion has element 1234 and the other 57 will remain medium, it will remain the middle element only because we do not know in which area the President is either. By sharing the minimum of right left and right left contenders, he will have to select the minimum value of both the media, which has become an example and let's take one in which people will implement the research, if 12345 157 were melted in it, then it has validators. This means that here we can divide the face into elements and then we can calculate its media. If we go into life, then there will be elements in it. Accordingly, if we look at this matter and calculate here. Do Subscribe Share And if we do that - then you will know that do that - then you will know that do that - then you will know that this element has been assigned to compare the two elements before and after, not subscriber, this means it should be on the right side and we In the left side, consider that the young man had to ride point. Quid minus one day test index minus one of 25, this means that he will remove two one. Now after the halwa, the logical consideration in the smaller reduction on the left side is empty. One element is coming which is one and this message which is logical left motor, three elements are coming in it is one two three and for this case we can see that 143 both the corresponding elements are smaller than four and five so Now we got the logical left half and logical right half clear because in this case there is another element president in both the logical houses. Here to remind the sisters, we have to use one element from the left hand and one element from the right hand. We will have to choose, now we do not know which element is Africa near attacks which is maximum and one element because the right week is near attacks which is minimum. To know this we have considered the logical address. That is, let's use it, we will calculate the maximum between being considered left part in these three in one and we will calculate the minimum considering part of these latest point five, maximum will come to 3013, minimum will come to 154 and by adding that if we If people divide then we will get 14.5 so we will get 14.5 so we will get 14.5 so we will understand this problem by subscribing to you, this is the one appointed by subscribing and running the conditioner statement in which keep the size of both at a minimum so that we can know which of the two Which one can do and after that people considered Anshuman as a small vector in the jam so we will use the taste function and after that calculate the points in the index that this and this which will represent the friend, after adding both the persons the total His penis will remain if we do this and then set the accused then this loot has been conditioned to prevent index flu and what it is, it differentiates and represents the arrest which is different from the other is the first Life in a that the rest of the elements are witch that Saif will be in number two as the day has been noted after that we have done a condition check etc. this loosening x max and no - one is great to the number of side this no - one is great to the number of side this no - one is great to the number of side this People were checking whether the considered index is the same condition as other elements, whether it is a small or not, so that we can accurately guess what will be the left half. In these two conditioner statements, we have gased you. Which we, this number will be inside the number one vector left. After gassing you, we ran a cab statement. In the angry statement, we first calculated the max left and then calculated the mean of Friday. Maths of left means this is what will be left. After merging Arya, what will be its maximum volume and main right means whatever will be written by us, what will be the minimum value of that face? If we are Arya and there will be elements on the number then we will directly return You can say in your next left some age text, initially we have kept the loop at zero, if you index it as 0, it means that the Western Amazon which we have considered is whatever, then the max life which will be that will be of number two. Jail - Details will be that it will be the Jail - Details will be that it will be the Jail - Details will be that it will be the last value of number two. In the same way if 30 then the max which will be left will be the last element of number 1. If both of these are close then it means that whatever is there is likes from zero. For that case in larger portions, we can calculate the meat loop today. Maximum of No. 9 - 110 No. - As we 9 - 110 No. - As we 9 - 110 No. - As we saw this in the example, now we do not know that we decide in the maximum life which is If its numbers are one and two, then we will maximize both and if you turn on Totally Free Mode, then we will return the max left, which will be the result, if these are elements, then our add statement will continue further. Test Hello Main. Adams to define the right, after that we will check that I camp is equal to that SI, our considered actors has reached the end of one, has Guru reached the end, you will have minimum right, he will be number two's Jai. Similarly, if JN has reached the end. If it reaches , then the if JN has reached the end. If it reaches , then the if JN has reached the end. If it reaches , then the main right will be up to Nam Swan's I and in this case also we have considered the minimum of Friday in the same way, S is the minimum of number to Z Adams's I, which we don't even know yet. We must have heard that the minimum value will be in number two because we have reached here only when after doing the total calculation in our personality, there is an even number of elements, then we have to do the Max Loop and Main Ride in the evening. After calculating, we will have to divide it by two and return it for any reason. If it doesn't work then we will return zero. So let's run it and see what output is coming. Its solution has been accepted, let's see it by submitting it. Tomorrow the college can see that it has been successfully submitted and its runtime was only 1 millisecond and 98 per cent of the solution. I hope you liked this video. If you like this video then please like this video and subscribe to my channel. I will keep bringing interview videos in this manner for the people. Thank you for watching my video. Have a Nice Day . . | Median of Two Sorted Arrays | median-of-two-sorted-arrays | Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is 2.
**Example 2:**
**Input:** nums1 = \[1,2\], nums2 = \[3,4\]
**Output:** 2.50000
**Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5.
**Constraints:**
* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* `-106 <= nums1[i], nums2[i] <= 106` | null | Array,Binary Search,Divide and Conquer | Hard | null |
316 | hello everyone so today in this video we are going to solve a question of fleet code that is remove duplicate letters it is 316 question on lead code and it consider medium category all right so let's start with the problem statement given as string as remove duplicate letters so that every letter appears once and only once you must make sure your result is a smallest in lexographical order among all possible results so basically in this question we have given a string and in this string we need to remove all the duplicate characters as well as we need to maintain the lexographically smallest order so let's quickly understand with an example and how can we approach this question so let me make a multi-line comment here let me make a multi-line comment here let me make a multi-line comment here and let's take the first example in the first example we have s is equal to p c abc this is our first example now to approach this question let's make let's take a answer string let's initially it is zero like it is empty and let's take two vectors like the integer vector so first one is the count which will be storing the count of each characters and second one is visited which will be keeping the track whether the character is visited or not so let's count the number of characters so for b we have two occurrence so let's make it two and then we have for c we have two occurrence then for b we have already counted here so for a we have only one occurrence so initially we have not visited anything so let's make visited to zero initially it is zero and this is also zero and k is also 0 now let's sit right through our string so first we get b so whenever we get b and nothing is in our answer so let's try to push it in our answer and let's make it visited and decrement the count as we have already tried through one character of b now let's see for c b is less than c so we can push it into our answer because it is lexographically correct so let's push c into our answer and let's decrement the count by one and make it visit it now we have c now we have a so for a is less than c so it's not lexographically correct if we directly push it into our answer so let's check for b and c so for c this count is 1 it means c is available in this remaining string as well so let's pop it out from here and let's make it unvisited so let's initialize c with zero like update c with zero and the count is same because that is popping up so let's check for b is also present since count is greater than zero and let's make it unvisited now let's see for a so let us keep pushing over answer and let's decrement the count and make it visited now we have b so we can push b to our answer because it is lexographically correct so let's push it to our answer and make it visit it and just decrement the count now we have seen let's push c into our answer because it is lexographically correct because c is greater than b and let's decrement the count and make it visited now we have completed the iteration of our given string so as an answer we get abc so we will directly written abc from here as this is our desired answer so i hope the project is clear to you let's quickly fold it up all right so let's make a string initially it is empty now let's take a vector of integer let's take count 26 comma 0 we are taking 26 characters because like we are given we have only lowercase english character so let's make 26 and also make a visited vector this will be stored in 26 characters so yeah let's run a for loop to count the number of occurrence of a particular character so let's run our for loop x yes and just increment the count for each index so x minus a plus now let's run a for loop to create through our string and write the logic for it so auto x yes and let's decrement the count whenever we get a character so x minus a minus now let's check if it is unvisited like this is unvisited then we will check the remaining like the our current answer so answer dot size is greater than zero and answer dot back like the previous element like the current element which we just pushed in our answer should be greater than like it should be less than if it is greater than we will just pop it out so like if answer dot back is greater than x and the count of answer dot back minus a is greater than zero like if it is present in the remaining string then only we can just pop it out so let's make it unvisited so answer or back minus a is unvisited and let's pop it out from our answer so answer pop back all right now let's just add the current character into our answer so answer plus equal to x and let's make it visited so visited x minus e is equal to 1 and then just written answer from here i hope it should work fine let's just run it yeah it's working fine now let's just submit it yeah it's perfectly fine now let's calculate the time and space complexity of our solution so time complexity of our solution is speak off and because we are creating through all the n elements and space complexity is also big of n because we are storing all the n characters into our string as well in the vector so space and time complexities are because n so that's it for this video i hope you understood the solution if you still have an advantage in this question feel free to comment down please like this video and subscribe to our channel thank you | Remove Duplicate Letters | remove-duplicate-letters | Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/) | Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i. | String,Stack,Greedy,Monotonic Stack | Medium | 2157 |
209 | everyone welcome back and let's write some more neat code today so today let's solve the problem minimum size subarray sum we're given an array of positive integers and that's actually going to be an important detail the fact that they're all positive and we're also given a target value and all we want to do is return the minimum length of a contiguous subarray uh basically think of a contiguous subarray as like a window within our array so for example this is our array you know we want some window in this array and we want the sum of all the values in that window to be greater than or equal than the target value now there could be multiple windows like this but remember we want to return the one that has the minimum length and specifically we're going to return the length of that window so in this case our target value is seven so is there any window here that sums up to seven well there's many right like the whole array itself could be but the shortest one in terms of length is this one four and three because they sum up to seven and the length of that window is two looking at the second example you know this could be considered a window but there's a shorter one you know the value for itself it could be this one or it could be this one there's a multiple in this case but the length of each of them is one so we can return one as the result so let's immediately jump into the brute force solution because it's not too difficult to come up with i mean we could try every possible subarray or every possible window in other words right and we could do that with nested for loops what i mean is we look at every single window starting at two right this is the first window then the next window is the first two values then this and then basically keep going right and technically we don't have to actually go through the entire array because we're going to stop the first time that we find a window that sums up to the target value in this case i think it's this one because this sums up to i think these three are six plus two that's going to be eight so this is one window the size of it is four so that's the shortest window starting at 2 that will sum up to the target but there could be even shorter windows that maybe start at 3 so then we try every window starting at 3 etc we do that for every value in this entire array that's how we're going to use the nested for loops now the time complexity of that is going to be big o of n squared where n is the size of the input array so the question is can we do better yes we can do better and we can actually use this brute force solution to figure out how we can do better because there is some repeated work that we're doing here which might not be immediately obvious let's uh first you know go through starting at two right now our sum is two uh now we include the three now our sum is five now our sum is six we're still under the target we include one last value uh two now our sum is a so by doing this we found out that the shortest window that can sum up to the target starting at the two is of length four right four values and of course we could add more values to the window now but those are just gonna make the window longer so there's no point in doing that so then next what we're gonna do is then start at the three and then you know do the work that we were just doing right in other words we're gonna then include the one then include the two but didn't we kind of already do that work with the first pass so why should we repeat it now and this is where it comes into play the values in the array are going to be positive what does that mean for us because if there were negatives that would complicate things but since it's positive we know for sure one important thing and that important thing is it wasn't until we included this value that our first window was greater than or equal to the target right that's pretty obvious so then my question to you is it ever going to be possible that starting from this 3 we find a window before the last value of the previous window right that green window is it going to be possible that we find a window like this that's also going to be greater than or equal to the target no way because we know all these values are positive this value is positive now that we're starting at 3 we're not including this value anymore and we know for sure that until we reach this 2 when we just had these three values we definitely were not greater than or equal to the target so how is it going to be possible that with just these values we're going to be greater than or equal to the target it's not possible so what i'm saying is we don't have to uh even we don't have to consider this window we're never going to find a window this short starting at three we can just include the entire window except for that first value that we were doing and if you're starting to see what we're doing here this is a very common technique called the sliding window we're gonna maintain two pointers and shift those pointers accordingly as we find a valid window so let's run through this algorithm it's going to actually be pretty simple it's very standard sliding window okay i'll run through it quickly we started at the two uh we're going to take uh this is our left pointer by the way so let's actually call it left and then our right pointer is initially going to be here too we're going to maintain what the total is so far so right now we're at two and we're going to keep uh increasing our window so now our total is actually going to be five but five is still less than seven so we're going to shift our right pointer again so now our total is going to be six that's also less than the target we're going to shift again now our total is going to be eight now the question is this might be our result well what's the size of the window right now it's four so i'm not going to write it down but let's just keep track mentally of what the shortest window that we find and once we find a valid window like this one we know that we can just chop off the left value there's no point in repeating the work or just because now we're going to start at 3 we don't have to recompute all this let's just shift our left pointer so i'm going to do that like this and since we got rid of this 2 our total is actually going to be decremented by 2 so instead of 8 we're going to be now at a 6. our right pointer is going to be here but now we're going to start shifting our right pointer because our total is less than the target so uh we're going to shift the right pointer one more time to here so now our total is going to be 10 we're going to add this four that we just got so now our total is 10 it's greater than or equal to the target but this window is also of size four so it's not any shorter than the previous one but now we're going to uh shift our left pointer it was over here now we're going to shift it to this position so left is here our right pointer is still here but we have to decrement the three from our total was 10 now it's going to be 7. but our window this time is a valid right 7 is greater than or equal to the target and our window is a little bit shorter this time it's of size 3. since our window is valid we're going to take the left pointer and then shift it so it's now going to be over here our window now our target was seven now we're going to decrement it by one so our total is going to be six now that's less than the target so let's start uh incrementing our right pointer so now our right pointer is going to be over here and our window is once again uh now it's we're adding the three so now our total is nine so it's valid the size of it is three of course that's greater than the target three is what we already previously had uh but now we're going to shift our left pointer because the window is valid and now the left pointer is going to be over here is the window still valid yes it is right because we decremented the total by two so now it went from being nine to now being seven is still uh greater than or equal to the target so now our window is of size two and one thing i didn't actually mention in any of the previous cases is while our window is still valid we're going to be incrementing the left pointer because there's no need to shift the right pointer and add elements if our window is currently valid right that's when we want to be shrinking the windows it could be possible that multiple consecutive times we end up shifting the left pointer in this case we are going to shift the left pointer it's going to be here now left and right are at three but now our window is no longer valid of course we're going to take the right pointer and then shift it but now it's going to be out of bounds so that's how you know we can stop and you know we basically found all of the windows that we possibly could and the shortest one was this one of size two so two is going to be what we return that's exactly what was expected in this example problem if you noticed well we do have two pointers so in a sense we're going to be scanning through the array two times uh but that's still big o of n time complexity there's really no extra memory complexity we don't have any data structures just a couple of pointers so the memory complexity is big o of one with that said we can jump into the code now so now let's code it up we have our left pointer and our total which are two variables we're going to be keeping track of so our left pointer of course initially is going to be at the beginning our total uh sum is what the total represents is also initially going to be zero the reason we don't have a right pointer is because that we're actually just going to be incrementing our right pointer each time using a for loop we could have done it differently but i feel like it's a little bit easier to do it this way so our right pointer is just going to iterate through every position in the input array now our result is what's going to be that minimum length that we're trying to return initially we can set it to you know multi we could set it to a default value of infinity which is what i'm going to do in this case because one detail that they mention is if we don't find an array that sums up to the target then we can return a default value of zero so what i'm going to say is return zero if a result is equal to the initial infinity value and if it's not equal to infinity then we can actually return the real result which we calculated in that variable if you don't have an infinity in your language or whatever you could also set it to the length of the input array plus 1 because that's also technically an invalid value and that's also a large value you could set it to negative 1 as well if you want but the reason i'm setting it to a big value is because remember we're trying to minimize it so we're going to be using like the min function within this for loop okay but now for the actual sliding window portion remember each time we add a new value at the right pointer we're going to be taking that value and adding it to our total right that's the first and very basic step so let's add that value at index right to our total but also remember that if the total becomes greater than or equal to the target well one the first thing uh to do then is potentially we have found our result but our result is going to be the size of the window how do we get the size of the window we can take the right pointer minus the left pointer a plus one which is going to give us the size of the window and remember we're trying to minimize the result so we're going to set the result equal to the minimum of that computation right the size of the current window as well as the minimum of the result itself so of course if the result is infinity then you know this will become the new result but if the result is already a smaller value than this window then the result is going to stay the same okay that's the first step but also remember we want to increment our left pointer by one now because if the window is already greater than or equal to the target let's try to find a smaller window but remember if this condition holds multiple times multiple consecutive times then we want to continue incrementing the left pointer as well as potentially you know figuring out if we found the result so instead of having this be an if statement let's make it a while loop now just because we have a while loop inside of a for loop does not mean the time complexity is n squared think about how many times this loop is going to execute in total in the worst case the left pointer will be incremented until it's out of bounds of the nums array now we don't need to you know confirm that because if that was the case then of course our total would be zero and we know that the target is always going to be a positive number so then the loop would exit by itself anyway there's one thing that i actually forgot with this loop before we actually increment the left pointer we also want to subtract the value at the left pointer from our total right because our total represents the values in our current window if we're updating our window then we also have to update the total value and that is actually the entire code as long as i didn't make any mistakes so let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching | Minimum Size Subarray Sum | minimum-size-subarray-sum | Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`. | null | Array,Binary Search,Sliding Window,Prefix Sum | Medium | 76,325,718,1776,2211,2329 |
274 | hey guys welcome back to another video and today we're going to be solving the leaka question h index so in this question we're given an array of citations and we need to write a function to compute the researchers h index so what exactly is the h index so over here we have the definition a scientist has index h if h of his or her end papers have at least n site h citations each and the other n minus h papers have no more than eight citations each so as it is i think the definition is pretty confusing so what i'm going to do is i'm going to break it down step by step and we're going to be following this uh question over here so we're going to take this as our input so let's just go line by line so a scientist has index h so this is what we're looking for the index h if h of his or her n papers so over here let's initialize a variable called n and n over here is going to be the number of papers they have and in other words this is going to be the length of our citations area so in this case we have a length of five so our n value is going to be five okay so a scientist has index h so if each of his or her paper so we have h papers over here so out of these h papers all of these papers have at least eight citations each so the number of citations are equal to or greater than h so we don't know what the number value h is yet but h papers have a value greater than or equal to the value h okay so the second part is and the other n minus age paper so it's saying the rest of the papers so in this case it's going to be the rest of the papers are nothing else but n minus h so the rest of the n minus h papers have no more than eight citations each so have no more is equal to or less than the value h so this is what defines the h index so let's just take the example so over here our output is the number three so let's just rewrite it so we have three papers so for papers i'm just gonna write p which are equal to or greater than the number three so what that means is three papers have at least three citations each so let's just take a look at that so we have the value three so that's one we have six so that's two and we have five that's three so as you can see we have three papers which meet that criteria now let's look at the remaining papers so the remaining papers in this case are the values 0 and the value 1. and what this is saying is both of these papers no matter what have a value which is equal to or less than the h value so if you look at zero it's less than h and h is three so zero is less than three and one is also less than three and this is why the answer for this is three so now what we're going to do is let's see at how we can solve this question so this wikipedia link has a lot of the information we need and over here you can clearly see that so first we order the values of f from largest to lowest value then we look at the last position in which f is greater than or equal to the position so i think that's pretty simple and let's just write that in code so our first step over here is going to be to sort our citations so citations dot sort and we want to sort it in descending order so to do that we just need to do reverse equals to true so now we sorted it in descending order so now what we're going to do is we're going to iterate through our citations but what we're gonna do is we need to compare the citation value to the value of our index and the easiest way to do this is by enumerating the list and what that does is we get a tuple value of our index and then the citation so to do that for index comma citation in enumerate and we're going to call our citations over your citations okay over here we're going to return the index when the index has a greater value than our citation so in this case if index is greater than or equal to our citation value and in that case we're just going to return our index and that's going to be the h value but if this is not the case then we're just going to return but if that is not the case we're just going to return the length of our citations and the purpose of this is because if you go up to our definition over here so if we did not find any answer and our h index is the length of our citations that means that each of his or her end papers have at least eight citations each so obviously all the papers have more citations than that h value which is going to be the length of our citations so if none of these uh are true if we do not return anything inside of our for loop we're going to end up returning the length of our citations so let's submit to our answer and as you can see our submission to get accepted and finally do let me know what you thought about the video and don't forget to like and subscribe if this video helped you thank you bye | H-Index | h-index | Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper, return _the researcher's h-index_.
According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times.
**Example 1:**
**Input:** citations = \[3,0,6,1,5\]
**Output:** 3
**Explanation:** \[3,0,6,1,5\] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
**Example 2:**
**Input:** citations = \[1,3,1\]
**Output:** 1
**Constraints:**
* `n == citations.length`
* `1 <= n <= 5000`
* `0 <= citations[i] <= 1000` | An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space. | Array,Sorting,Counting Sort | Medium | 275 |
746 | hey what's up guys it's Nick white here I do tech inchoate hey what's up guys think white here I did technically stuff on Twitch on youtube check the description I got all my stuff there I do these premium problems on leak code there on my patreon if you want to check that out and join the discord this is min-cost climbing stairs a this is min-cost climbing stairs a this is min-cost climbing stairs a pretty cool problem gives you kind of an intro to dynamic programming if you don't know what dynamic programming is maybe look it up but I guess I can explain it's basically if your jet if you're answering problems more than once then that's usually bad and you don't want to do that so sometimes you might want to use space or you might want to save an answer or a previous answer that you calculated and use it later to speed up your run time that's generally what it is on a staircase the ID step has some non-negative cost of AI so we some non-negative cost of AI so we some non-negative cost of AI so we have a staircase and it's represented as an array of integers cost each in each value in the array is the cost of climbing a stair once you pay the cost you can either climb one or two steps so if I pay the cost 10 I can climb to 15 or I can go to 20 if I pay 15 I can go to 20 or I can just go to the end I'm done with the array I climb to finish the staircase you need to find the minimum cost to reach the top floor and you can either start from the step with index 0 or this step with index 1 so these are not sorted arrays by any means some values can be really large some can be really small we want to find the minimum cost to get to the top the end of the array we could start at either index so this is a little bit it's almost like a mix of like a greedy algorithm and dynamic programming I would say because it might be greedy in the sense that like you're making the current choice now of I think the obvious thing is like pick the smaller number right so you're gonna look at the two staircases you can go one or two steps and you could start at the first or second position so we're gonna look at these and which one are we gonna start on guys I think we're obviously gonna start on the first one because it's smaller and when you jump what are you going to jump to the larger of the smaller obviously etc so you keep going cost us six in this example on this one it's just 15 and then you jump over 20 and then you're done so that one's that's obvious so it's really not a hard problem you could there's a couple approaches they're basically this they're pretty similar but let's do a if your I guess here's the two different differences of approach if you're able to modify this array then we can do it probably this is the easier way you would do a loop you would just do I equals two you'd start at I less than cost out length in then I plus and then you would just do cost of I plus equals the math dot min of cost of I minus one the previous two steps you know this is pretty obvious it just is going to store or add to the value it's going to add to the current value whatever the cheaper step was I mean like for example in when we're at a hundred and we look at the minimum if we start at two we start at one and then we would do you know what I mean you start at the second position and you check the previous two and whatever the minimum was is the one you jumped from and then you keep doing that the whole way through so that's that makes sense right that's pretty obvious and then when you're at the end it will have added up the indices and have chosen the minimum of all the steps till you get to the end so you're at the end and you're just at the final two steps and you just returned math dot min of cost length minus one in most of cost up lane - - sorry so this most of cost up lane - - sorry so this most of cost up lane - - sorry so this is one solution I would say yeah see this one works and I didn't even test these out before but that's a good one and then you could use a little bit that's kind of a greedy one more so cuz you're kind of just picking the minimums until you get to the end putting them in the array but if you're not allowed to modify this array it might be a little bit harder so another way you could do it is more dynamic programming related so you could say you know you could call these variables whatever you want like step one in step 2 or f1 and f2 or whatever we could call step one we'll call it step one and step two so we'll say step one step two we will loop from the end of the array - one to the I the end of the array - one to the I the end of the array - one to the I greater than or equal to zero backwards and do it kind of the opposite way but we'll save these variables we'll use these variables because if we can't modify the array we have to use some kind of storage to get the final answer so what we do is we just say we'll make a new variable and we'll say you know whatever we want us to current step is equal to cost of I so the current cost plus sorry I have to blue I'm gonna sneeze plus math dot min have step one and step two and this will be nothing at first so you just start out with it's the same concept as the one we just did before so you just add the value of the last element to whatever the previous steps are going to be and we're gonna calculate those later on by just doing okay step two now step 1 is equal to step to remember the reference you don't want to lose reference and then step two is equal to current step and then you just return the math dot min of step 1 in step 2 at the end because these will get down to the first two things and you want the minimums of those and it would have all added up by the end of it so I think this one works too I haven't tested this out either right they're both good this one's more dynamic programming because you're kind of saving things but it's not I don't know it's kind of a greedy algorithm let me know what you guys think I'm kind of torn between greedy and dynamic programming this solution says dynamic programming but it seems more like greedy algorithm to me if you want me to run through I think I have this yeah if you wanted me to run through this is from the solution that they had we could do step one step two our step is it current step sorry I'll just print these out for you so you can see what's happening step one step two you know we could do one step two current step and let's run test case for you guys to see what's going on I cannot find symbol oh this has to be in the loop sorry you know you can turn this off if you don't want to watch this walkthrough but I assume some people might get confused so with dynamic programming it's probably the most confusing thing even though this is a pretty easy one so if we run test case on this one for example 10 15 20 it starts at the end and then it's 20 and then it adds you know 20 plus the minimum of the previous to two steps which aren't set yet so it'd just be zeros but later on we get to the next one and there'll be 15 plus you know the minimum of those which would be you know zero and 20 and then it would be 10 plus you know what I mean like current step is equal to the current element 20 plus the minimum of zeroes so it's 20 step one is zero still and current step two get set to current step so get set to 20 then current step is 15 plus minimum of zero and 20 so it becomes 15 step two becomes 15 after step one becomes 20 so step two is fifteen step one is twenty current step is 15 then it's ten plus the minimum of 20 and 15 so it is 10 plus 15 and then it's 25 and then step two is set step one is set to 15 and step two is set to 25 and then you return the minimum of those which is 15 so it just chooses the best choice that was a walk through sorry if it was kind of shaky and you can look through a walk through of this too if you want to just check it out sorry for making the video so long I just assume people want to know how like this stuff works so your current step is one at the end then it's zero step two get set to the current step which is one then it's 101 yeah so I'm not gonna walk this one's too long but let me know what you guys think about this let me know if you have any questions pretty straightforward link to the problems in the description thanks for watching see you guys next time | 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 |
563 | today we are going to solve a question called as binary tree tilt we are given with the root of a binary tree and we need to return the sum of every tree nodes tilt and your question could naturally be what is a tilt yeah so let us see the tilt of a tree node is the absolute difference between the sum of all left sub 3 node values and all right subtree node values if a node does not have a left child then the sum of all the left child of the left child left subtree node would be treated as zero the rule is similar if there are node if the node does not have right child so in this tree's case the tilt of this node is 0 delta of this node is 1 and then finally we add 1 0 and 0 to give 1 as the final answer let us understand this with help of another example so the tree that we are given with is 4 2 9 3 5 and 7. um this is your tree so we need to build a tilt tree first and then once the treated tree tilt tree is built then we'll add all the elements of this tilt tree and that will be our answer so let us see how to go with that i am going to first start with the leaves and then we will go slightly uh one step further up right so what about three stilt is going to be zero because it doesn't have left node it doesn't have right nodes so zero minus zero is going to be zero and once uh the tree tilt is decided it returns the total value of the subtree itself so what is the total value of this subtree it is 3 so it returns back 3 what about 5 doesn't have any left node or right node so this is also going to be 0 so it is 0 and then it also returns back 5. now we go to this particular node so for this note the return value was 3 and the return value was 5 from the right 3 minus 5 is going to be -2 and we right 3 minus 5 is going to be -2 and we right 3 minus 5 is going to be -2 and we take absolute value of this returned integer return term and minus 2 is going to be written as 2 then what is the total value of this segment 3 plus 2 plus 5 and that is 10 so this returns 10. and we reach root node now let's take care of the right subtree so let's start with 7 doesn't have left side or right child so it is also going to be 0 and then it returns 7 that is the total of the subtree we go to this node and here as well uh there is no left side so that is going to be 0 and 0 minus the returned value so 0 minus 7 is minus 7 and we take the absolute value so it becomes 7 here we write 7 then it returns the total value so total will be calculated as 7 from here return value from here was 0 so 0 plus 7 plus the value of the node itself that is 9 so 9 plus 7 is going to be 16. so 16 is returned from here and then we finally reach root node 10 from left 16 from right so 10 minus 16 is going to be minus 6 and we take absolute value so it becomes 6 here and then because we have already reached the root node we don't need to worry about 10 plus 16 plus 4 as the return value so finally this is the tilt tree that we have got and it is simple now we just need to add all the elements here so 6 plus 2 plus 7 plus 0 and we get 15 and that is our answer so let us see how to code this question so i am going to do a dfs visit to calculate this total that we need to return so i will have a function with the name dfs that will accept root and this will return the total i'll take one variable our total which is a global variable here and this is the value that we'll finally be returning back so we call dfs with root and this function will internally calculate total update total in the end and then we'll return total as a result of it this is going to be recursive function so let us take care of the termination condition first so if there is no root then just return 0 and we don't need to touch total because it is 0 by default then what happens we go to left side so left is going to be dfs of root dot left then we go to right side so that is going to be dfs of root dot right now i'm reminding you the return value was always the total of the tree the total of the subtree so total of the subtree is going to be left plus right plus root dot value while the thing that we need to calculate and we need to return is the total of tilt so let us see what is going to be the tilt of this node and the tilt of this node is going to be left minus right and we take absolute value of it so math dot abs left minus right this is the tilt so we add it to our total and then finally we return root dot value plus left plus right so total is done the return value is done that means everything is done let us see if it works it does for example cases it does let's submit it yeah i think it is good and it is faster than 100 so i think we are doing great | Binary Tree Tilt | binary-tree-tilt | Given the `root` of a binary tree, return _the sum of every tree node's **tilt**._
The **tilt** of a tree node is the **absolute difference** between the sum of all left subtree node **values** and all right subtree node **values**. If a node does not have a left child, then the sum of the left subtree node **values** is treated as `0`. The rule is similar if the node does not have a right child.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 1
**Explanation:**
Tilt of node 2 : |0-0| = 0 (no children)
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
Sum of every tilt : 0 + 0 + 1 = 1
**Example 2:**
**Input:** root = \[4,2,9,3,5,null,7\]
**Output:** 15
**Explanation:**
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 5 : |0-0| = 0 (no children)
Tilt of node 7 : |0-0| = 0 (no children)
Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15
**Example 3:**
**Input:** root = \[21,7,14,1,1,2,2,3,3\]
**Output:** 9
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-1000 <= Node.val <= 1000` | Don't think too much, this is an easy problem. Take some small tree as an example. Can a parent node use the values of its child nodes? How will you implement it? May be recursion and tree traversal can help you in implementing. What about postorder traversal, using values of left and right childs? | Tree,Depth-First Search,Binary Tree | Easy | 1609 |
211 | welcome to august leeco challenge today's problem is add and search word data structure design is data structure that supports the following operations add word and search word can search for a literal word or a regular expression string containing letters a through z or period means it represents any one letter that's basically a wild card you see in this example we add the words bad dad mad and we can search for period a d and that's going to return a true because we indeed see that word exists so this problem is an implementation of a tree we've seen this problem before there's many ways to implement one i'm going to use a nested dictionary but the big twist here is how do we get this wild card search to work notice that we can't add words with the wild card but we need to be able to search for words with that so initially let's start with initializing a dictionary we'll just call that d and this is going to be our root dictionary for our tree like structure word dictionary now when we want to add a word we want to add basically each character of the word into a nested dictionary right and basically one first see if this word exists if it does we're going to add each character with the word into a nested dictionary and at the very end we have to mark it somehow to say this is the end of the word because otherwise we're not going to be able to know if this word is indeed inside of a dictionary or if it's just like the starts with part is working so first i'm going to initialize a current pointer pointing to the dictionary that we're at and this starts with a root dictionary now if the word does not exist inside of our word dictionary then we want to add it and we'll write this search function later we'll say for i in range of the length word we're going to um let's see add to our current pointer the character being the key of the dictionary and create a new dictionary that is we only want to do this if this word doesn't exist right so we should say if um let's see word dot i not in cur then we'll set a new dictionary otherwise we don't need to do that we just move on to the next pointer we'll say current is going to be equal to cur word dot i now once we're at the end here we want to add some sort of key to indicate that this is the end right so what i'll do is just have this hashtag symbol be a marker it's going to be a key to mark the end of the word so this will just point to an empty dictionary but that's going to be what's going to help us know if we are indeed at the end all right so now the hard part now we want to write some sort of way to search for the word and the tricky part is getting that wild card part correct right and there's different ways you can do it um you could build a stack because once we hit a wild card what we're going to have to do is search for every word that's inside that dictionary so we could build a stack to do that or we could do something recursively i'm just going to go with a recursive approach start with initializing the current pointer to our root dictionary and what we do we want to do well let's write a helper method that's going to be our recursive method and we want to pass in the starting index the index number where we're at as well as the current dictionary that we're pointing at so there's going to be some base condition that's going to return true we'll come back to that in a bit let's first think about what possible things could happen here well the first thing that might happen is that this is a period so if it's a period we have to search through every single um you know diction dictionary inside of our current dictionary okay so to do that we'll say if word start is equal to period let's do a for loop and say all right for all the dictionaries we'll do key value in current dot items we'll recursively call oops we'll recursively call start plus one and pass in the dictionary which would be value now the trick is we want to return a billion right so what we'll do is say all right if at any point in this loop we return a true here then we return to true otherwise we get through this whole loop then we can just return false now there's other things that can happen this word dot start might just be a regular character and so all we'll do is check to see if that's inside of our current dictionary and if it is then we'll just do the same thing here we'll say uh if recursive method start plus one and pass in the um current word start and if that's true then we turn a true otherwise we've found the point that it does not have anything there so we just return a false all right so now we have to go back to our base condition so what would reach the end of our search well basically since we're passing the start if the start is greater or equal to the length of the word then we've reached the end of the word right so that's the point that we know yeah this word exists but keep in mind we need to remember to check to see if this hashtag exists inside of our current pointer because otherwise say that we added the word dog and now we're searching for the word do it's going to return a true if we don't check for this end word symbol so to do that i'm just going to keep it simple and say all right if the start is greater or equal to the length of the word now check if hashtag in current then return true otherwise we've found that this word starts with inside of our dictionary but it doesn't reach the end of the word so we return false all right so finally we want to return our recursive function and just pass in the zero index as well as the current the root dictionary so let's submit that see if it works no false true it looks like it works let's go and submit that and accept it so like i said before there's different approaches i saw that some people prefer to use a stack some people used a tree node object instead but the basic you know logic is still the same we're going to have to do a for loop for check every single item if it's a period otherwise we just go down the right the normal path like we would do for a normal tree all right so that's it thanks for watching my channel really appreciate it and remember do not trust me i know nothing | Design Add and Search Words Data Structure | design-add-and-search-words-data-structure | Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the `WordDictionary` class:
* `WordDictionary()` Initializes the object.
* `void addWord(word)` Adds `word` to the data structure, it can be matched later.
* `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter.
**Example:**
**Input**
\[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\]
\[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\]
**Output**
\[null,null,null,null,false,true,true,true\]
**Explanation**
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord( "bad ");
wordDictionary.addWord( "dad ");
wordDictionary.addWord( "mad ");
wordDictionary.search( "pad "); // return False
wordDictionary.search( "bad "); // return True
wordDictionary.search( ".ad "); // return True
wordDictionary.search( "b.. "); // return True
**Constraints:**
* `1 <= word.length <= 25`
* `word` in `addWord` consists of lowercase English letters.
* `word` in `search` consist of `'.'` or lowercase English letters.
* There will be at most `2` dots in `word` for `search` queries.
* At most `104` calls will be made to `addWord` and `search`. | You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first. | String,Depth-First Search,Design,Trie | Medium | 208,746 |
1,833 | hello everyone welcome to coding chance in today's video we are going to be solving the problem maximum ice bars let's start by reading the problem statement it says sweltering summer day and a boy wants to buy some ice cream bars at this store there are n ice cream bars you are given an array of cost of length n where cost of I is price of the ith ice cream bar the boy initially has coins to spend and he wants to buy as many ice cream bars as possible return the maximum number of ice cream bars the boy can buy with the coins so the bike and the boy can buy the ice cream bars in any order okay so in the first glance this looks like kind of a DP problem like coin change but it actually seems greedy because we want the boy wants to buy as many ice cream bars as possible so what is the greedy strategy up we can apply here is a buying bars with least cost so we can buy ice cream bars with the least cost and um buy more of them so how to um get the least ice cream bars we can actually become smart we can apply sorting and we can sort the cost array then we will get the cost in ascending order and then we can um take the ice cream bars until we are out of coins so let's see let's code it up so firstly we have to sort the ice cream bars for that we do array start sort cost now that we have sorted let's iterate over the ice creams costs of length we also have to keep track of how many ice creams we have got how much cost we have spent so far yeah so we keep track of running cost and each time oh we check first if yarning Cost Less current cost of the ice cream bar is greater than the coins we have then we know we cannot buy the ice cream bar because we are out of coins so we return I value um Ace we add the current ice cream bar to the coins and finally if we are out of this Loop then how many ice cream bars we bought all the ice cream bars so we can length we can return cost dot length so this let's see if this runs this gets accepted for the sample test cases let us submit it got accepted so what will be the time complexity of this approach as we are using sorting this will be pause any log n time complexity and this Loop runs in a little slow transition of n time complexity so the maximum is off and login so the time complexity of the solution will be of n log n and the space complexity as we are not using any external space if we ignore the space in the Sorting then the space complexity will be was one so I hope you understood the solution to the problem for more daily videos to subscribe to the YouTube channel and like this video if you understood the problem and keep practicing right | Maximum Ice Cream Bars | find-the-highest-altitude | It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108` | Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array | Array,Prefix Sum | Easy | null |
1,880 | hey everybody this is larry this is me going over the lead code weekly contest 243 problem one check if word equals summation of two words so this one is actually pretty okay um probably the users of the bunch uh which is why it's q1 but uh hit the like button subscribe whatever hit the subscribe button join me on discord and yeah and basically this one is just implementation and translation it's just for you to work uh for each word the three words you want you know some translation function from the first word plus the translation function of the second word is you go to the translation function of the third word and once you break it down like that um you kind of for each character you just translate it to the number which is um you know for each digit you shift it by 10 and then you get it from the delta from the value of a and that's pretty much it this is linear time because for each character you do one operation or one over one operation and during the contest this was the useless part for me i got in 114 uh actually pretty fast compared to other people and that's my only bright spot so that's why i'm bragging about it because after that it went downhill but yeah so this is linear time uh constant space let me know what you think um yeah and you can watch me solve it live during the contest next i'm sorry i don't know but all right let's go i'm still allergies okay a2j do um uh yeah so this was a rough contest and day for me so yeah uh hit the like button and hit the subscribe and show me some love uh and hopefully it will bounce back uh as i explain more problems but i hope y'all have a good night have a good long weekend and i will see y'all later bye | Check if Word Equals Summation of Two Words | largest-merge-of-two-strings | The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.).
The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an integer.
* For example, if `s = "acb "`, we concatenate each letter's letter value, resulting in `"021 "`. After converting it, we get `21`.
You are given three strings `firstWord`, `secondWord`, and `targetWord`, each consisting of lowercase English letters `'a'` through `'j'` **inclusive**.
Return `true` _if the **summation** of the **numerical values** of_ `firstWord` _and_ `secondWord` _equals the **numerical value** of_ `targetWord`_, or_ `false` _otherwise._
**Example 1:**
**Input:** firstWord = "acb ", secondWord = "cba ", targetWord = "cdb "
**Output:** true
**Explanation:**
The numerical value of firstWord is "acb " -> "021 " -> 21.
The numerical value of secondWord is "cba " -> "210 " -> 210.
The numerical value of targetWord is "cdb " -> "231 " -> 231.
We return true because 21 + 210 == 231.
**Example 2:**
**Input:** firstWord = "aaa ", secondWord = "a ", targetWord = "aab "
**Output:** false
**Explanation:**
The numerical value of firstWord is "aaa " -> "000 " -> 0.
The numerical value of secondWord is "a " -> "0 " -> 0.
The numerical value of targetWord is "aab " -> "001 " -> 1.
We return false because 0 + 0 != 1.
**Example 3:**
**Input:** firstWord = "aaa ", secondWord = "a ", targetWord = "aaaa "
**Output:** true
**Explanation:**
The numerical value of firstWord is "aaa " -> "000 " -> 0.
The numerical value of secondWord is "a " -> "0 " -> 0.
The numerical value of targetWord is "aaaa " -> "0000 " -> 0.
We return true because 0 + 0 == 0.
**Constraints:**
* `1 <= firstWord.length,` `secondWord.length,` `targetWord.length <= 8`
* `firstWord`, `secondWord`, and `targetWord` consist of lowercase English letters from `'a'` to `'j'` **inclusive**. | Build the result character by character. At each step, you choose a character from one of the two strings. If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one. If both are equal, think of a criteria that lets you decide which string to consume the next character from. You should choose the next character from the larger string. | Two Pointers,String,Greedy | Medium | null |
1,480 | hey everybody this is larry this is dave one of the june nico daddy challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom how you doing uh just to give a quick update i was at the yankee game day one so go yanks no more sports for until a little bit so we'll see anyway um yeah if you're if this is your first day here uh welcome i have a 791 day streak though you can't really see it maybe after we solved this you could see it but so that means that we're going to be doing this all month so hit the like button hit the subscribe button come on my discord and hang out and uh show us your code uh do code reviews and we've been pretty good about it doing uh sharing our code there and just kind of get comments though maybe not for today's because it seems to be a yeezy one um but yeah just so yeah so we'll i mean like i said we have 791 days streak going so we'll probably keep going until as long as we can we'll see what happens but let's get started today's problem is 1480 running some of one d array given in a way sums uh yeah i mean this is yeah i mean i wonder if there's a good one liner to do it but either way i think well before i say that uh i would say so prefix sum is something that definitely something that you should look up i wonder if this is going to be the theme for this week and i hope so because prefix sum is something that is interesting and also um comes up often um but i mean it's not necessary for this problem but it is just maybe a pre-rule problem but it is just maybe a pre-rule problem but it is just maybe a pre-rule and if that's the case for the rest of the week we'll go over some of the concepts and solving and explanations and so forth so definitely uh hang out and yeah come hit the subscribe button i guess that's what i'm trying to say and uh and solve it every day together uh it's always good to serve with people and friends and buddies but yeah baby you know a core part of this is pretty straightforward though so we can just do it right um and there's a couple ways to it all right uh i would say i was gonna do something fancy with doing it in place but i think that's just you know it's fine we don't need it that way but the way that i write it is just for i and you can write this in a couple of ways i'm actually this is not the way that i normally would write it to be honest but i'm trying to write it in a way that is as least confusing as possible maybe but not with some like wrinkle about it right um i'm surprised um so yeah so that's basically it uh and we have to get rid of the prefix of zero but the idea here is and this is how i usually write the prefix sum for the most part maybe not the way that i actually write it is for say x and nums uh just to be a little bit uh maybe this is a free option yeah so and i would oops and let's just call it prefix right and sometimes you need the first uh zero and sometimes you don't but that's basically the way i write it right for each number i add it to the last number and it's kind of similar to fibonacci except for only one number i guess uh so you know but that's basically what we do and it comes up in a lot of competitive programming maybe not so much on interviews to be honest but it is something oh man i didn't fix that's the easy facts anyway i mean this is a easy problem so you probably already have an idea of how to do it so this is how i would do it uh you could use also accumulate i think uh as a python thing but i think that's a little bit yeah keep it stupid keep it simple that's the way that i like to think about these problems especially even on competitive and um and on interviews right because sometimes you try to be too clever with one liners and then one you have a type one you don't have to debug it because there's one line so you can't add a debug thing easily and then two is that uh for the most part if you're cleverness means making the code a little bit shorter and maybe a little bit harder to read that's not actually a plus even though i think this is one of those newbie traps uh if you ask me where someone think like okay yeah as few characters as possible makes it like really cool and smart and called clever but and that's why i call it a newbie trap is because as an experienced engineer part of your software engineer description is working with other people and some of that working a lot of you know writing code that is understandable without much thought or as little done as possible right like i don't have to figure out what someone's doing i just look and go like oh yeah i would have win it more or less the same way in any case so don't fall into that trap that's one and also uh it's so the upside is not that much you maybe look a little bit clever too some certain people who may find it clever but two is that when you do mess up if you have a typo you're gonna look like in yeah you're not you're gonna look like why did they try to do something to silly and then and didn't even succeed right so anyway those are trade-offs i leave up anyway those are trade-offs i leave up anyway those are trade-offs i leave up to you um i'm only talking about that because you know this is a pretty uh did i weigh someone no that's uh yeah 792 days yeah i only talk about that because this is not um this is pretty silly as a you know i mean this is just a full event they tell you exactly what to do right um but that way you know well um if it's prefix some week we'll talk about it more if not that's fine anyway that's all i have for today though uh we'll keep doing it for the rest of the month so let's do it together let's hang out i'll see you later um stay good stay healthy to good mental health uh see you later bye-bye | Running Sum of 1d Array | movie-rating | Given an array `nums`. We define a running sum of an array as `runningSum[i] = sum(nums[0]...nums[i])`.
Return the running sum of `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[1,3,6,10\]
**Explanation:** Running sum is obtained as follows: \[1, 1+2, 1+2+3, 1+2+3+4\].
**Example 2:**
**Input:** nums = \[1,1,1,1,1\]
**Output:** \[1,2,3,4,5\]
**Explanation:** Running sum is obtained as follows: \[1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1\].
**Example 3:**
**Input:** nums = \[3,1,2,10,1\]
**Output:** \[3,4,6,16,17\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `-10^6 <= nums[i] <= 10^6` | null | Database | Medium | null |
473 | it could question 473 match sticks to square uh first thing i have never seen this question so it's gonna be like a real interview kind of a video so let's see you are given an integer array matchsticks where mastics of i is length of eighth matchstick you want to use all matchsticks to make a square you should not break any stick but you can link them up and each mastic must be used exactly one time return true if you can make this square written false otherwise uh from the description it's kind of a easy to understand question so we have given a mastics and we have to make a square out of it so before going into an algorithm let's uh let me write down few things so what is going to be the input uh it's going to be array right uh matchsticks uh okay and is there anything uh no so okay what's the output boolean uh true if square if you can make a square out of it right okay so uh inputs are easy and i can work with that's fine uh let's let me understand few things so um area of size what i believe it's not going to be empty right uh no at least there will be one mastic okay so one and uh do you think there is a limit to matchsticks or anything or i don't have to worry about it uh okay uh let's see you can have up to 15 matchsticks at max so 1 to 15 okay fine and the values in the mastics are right as it's a length it cannot be negative and it cannot be zero uh is that assumption fair yeah that's fair assumption okay uh it's can be one and it can go up to 10 raised to 8 but yeah this interval will not say this he will obviously say like you don't worry about the yes let's assume it's fine or something like that okay and uh one more thing i would like to ask it's not zero it cannot be negative it can have duplicates i'm assuming that as well interval yeah it's fine assumption good um okay now i would like to have some basic um check checklist like so that i don't forget a few things is case which is edge or test cases then i'm gonna do and i'll go design i like to code it and i'll talk about time and space complexity yeah so coming back to question let's go through one example uh this give an example matchsticks one two so there are five matchsticks i have to make a square so yeah from this example i can see that we have four sides right for the square and four sides can be two to two and there are two ones so i can use that and it becomes these two as a one and these three so it can be made as square you can form okay understand uh let's say three and four okay so so few things i'm noticing here is that to make it a square exactly somehow the sum must be divisible by 4 is that right so let's see in this example if the total is 8 divided by 4 is not fraction so it gives you two in this example it's three fours at 12 plus uh 9 12 16. okay so that will give you four but based on this you cannot make a square because you cannot break this into four different uh mastics if you had ability to break this i am sure you can just do this and sum this and divide by four and if it is zero then you can mod by four and zero you can return but not in this case so i think there is a similar kind of a logic that can be used somewhere does it make to have some let's say in this example we had four right and the maximum value was 4 so um no um yeah so is there anything else that can be done one thing is clear to me that whatever the sum is of total divided by 4 this value has to be size it cannot be less than this it cannot be more than this that's one thing uh so i have to make sure that i can make all the four sides equal to this size there is a complicated solution in my mind like a brute force solution um try to make a side equal to this value by adding things so yeah uh let me think something else if i can come up with so here there is also the input is given in sorted order does that make any sense can it be but i came across an edge case that is if there are less than four mastics we can return false directly right because you cannot make a score if there are less than four matchsticks let's say each case is fine uh also if some mod 4 is a 1 or something is not 0 it unfolds these two cases the question is now it's uh divisible by four and we got a value uh so can i make four buckets uh something like this let's see buckets okay and then i trade through each element and i add it to bucket let's say one and i'm making it sorted so i'm going to fill this bucket uh to make it two so i add one right and uh again i add one now this is two now i go to second bucket and i'm here so add that add another and the arrow is empty and that i have scanned through array and all the buckets are full up to this value so in that case it's true let's try this for this example so it's three and i am going to add another three here now i cannot add another three here so i can directly return false or i can um add this to next but how is that possible because everything is going to be um above about um greater than three right so i can return in that case directly from here let's take another example so uh let's assume it's example one two three four and four so what i'm trying to make is these four these two makes four and this one and three mix makes four so now in that case um so uh i have to make four buckets of size four right the sum will be sixteen here so eight plus ten plus five plus one sixteen yeah and uh now i have four buckets okay and i am going to i have sorted this array in ascending order so i put one here then i put two here now i cannot put another two here so in that case the previous algorithm will return false so that's not gonna work uh okay how should i make sure that i don't add two here i add two here to here i add one here i have 4 here and i add 4 here so how can i make this decision i there is one solution that is coming to my mind it's kind of a brute force backtracking solution so i try to fill each of the bucket two to this maximum value and if i never if i can never do it right then there is a problem so i think i should go with this approach because this is simple uh like easy thing that create four buckets and make them feel in a way that it matches this uh upper limit of that bucket right it has to exactly match that upper limit so uh one thing that i can try is get like it's a brute force approach where i get the combination of elements up to this value target value right and i will do it for four times four buckets and i will add those indexes to scene set or something so that i don't use that value again right and uh yeah and at the end of this iteration recursive iteration if um if all the buckets are full um i can assume if all the buckets are full and all the elements are used then that means we can make a square out of it so what i'm talking here let me write it down uh so what i was going to write down yeah i wanted to illustrate this flow right so let's say i have set bucket value to one okay and i want to do it for four buckets and then i pass an empty bucket and i pass the value of four now i add first element and i make this value as 3 and this same bucket now my algorithm goes to find value that can make this as a 4 so it can add 2 and it adds 2 and it goes further now it cannot add 2 because it's greater than that so it comes back it pops this value it adds another two or maybe not two because i have already taken care of two right so i had three and then this is done so first bucket is done now as i have added one and three to the scene so for second bucket what happens is i started to i started one but it's seen so i do nothing then i get two i added two and i go further now next person or next iteration will add one value from this which is 2 which makes sense it's 4 so it returns from here then there is third bucket i go i add 4 it's already 4 so add four to the same and for fourth bucket there is obviously i start from here these are all seen so nothing happens i add the fourth index value and yeah so we should they should solve the solver problem and in at any case if i cannot do this at any state right let's see i start first bucket um for this example i started three and i cannot add i keep adding i add three and i add another three i entered i popped this i had another three i popped this i ended three of this i had four i cannot do for first bucket so there is no point in finding another three buckets so if at any point even one bucket cannot be done that's it um may return falls from that um so i think on a time complexity level it's going to be some exponential in a way and you can see that um you only have 15 matchsticks so i think this assumption is right so off um okay i am not sure but maybe something like 2 raised to n time complexity not sure i will come back to it after code maybe and space um maybe o of n but this is a rough estimate once i write code i can come back to time and space okay so let's try to let me try to write code for this i don't know um so i'm gonna make i'm going to write these base cases first okay so if let's take n is equal to the length of matchsticks right and if n is less than four or some matchsticks is mod 4 is not equal to 0 and that is written false yeah so base cases are taken care of let me also have this like um and some and okay and yeah so required is equal to m sum multiplied by 4 that is how much each bucket is required and i should have four buckets to fill will be this value so i am going to use a helper function which takes an index which takes required and um and yeah and what it should take uh i think i'm going to use scenes as i said but i don't have to pass it right and i am also going to sort this matchsticks so overall complexity is going to be in exponential so this won't matter that much it will just find easier um because there is going to be a case where if the value is going above required just uh pop it and just don't go further adding it yeah so that's gonna be helpful now what let's see so what is the base case let's say i'm going to pass required as whatever the required value and if it is 0 then i am i'm good that means this case is this bucket is full okay so in that case what should i do i control now there can be a case if required is less than zero then we cannot go further so return false right and this is index so what happens if i am at index that is already seen can i be at that index anyhow uh i'm going to uh like i'm going to try till 30 minutes and then i will check out the solution but i think this will this is right algorithm this is the right approach but i don't think i am able to code it like in and i don't want this video to be like a long video so let's and i'm also not that confident that my code is going to work i'm confident that algorithm is right but code it's kind of a tricky thing here yeah so let's see what happens if i have already seen this index how can i go to next index yeah so if i in scene um just call helper i plus 1 i'm required and there is also a case where our i is greater than or equal to n if required is not zero written true if i ever go beyond the index written false so let's say result is about false for now i'm going to do this if i in scene go to the next value it's same required okay and if it is not in scene oh okay else do what else uh maybe i will try to finish this on my own let's see how it goes um i'm not going to stop now i think i'm on the right track so let's see result is equal to helper still go to y plus one required minus match matchsticks of i yeah but before that add scene dot add i now there are two cases uh i have added this and i've gone and i can get result as true or false so if i get true that means this addition was good enough and i don't want to um use this index another time so i should not pop it so if result is equal to false or let's say not result that means if the result was false uh sim dot remove the index otherwise keep the index right and from here return result okay now i think i have to call this helper function four times with same request value so for i in range for uh call helper zero comma required right but there is a case right if even one bucket returns me false i can return false directly otherwise return true right so let's uh let's try run this once for this example so i'm just gonna roughly fastly go through it uh this is not false so this is like five so that's fine uh this is eight so this is not false or this is not false no don't return so m sum is eight more divided by four that is required is two and matchsticks sort actually i'm going to take this example um i'm sorting right so uh let's just write it here so that okay the sum is 16 divided by four required is four um i sorted it so this isn't sorted after scene is empty um set so now i start here for i in range four i call helper function with index 0 and required 4 okay so required is not zero it's not less than and this is also not true so result is so far false and i in scene is not true so i go here scene dot add i so now i should not do this actually all right let's see nobody is anyway here um yeah so i have added this and i have called this function with i plus one so now my pointer is here okay uh let's go so i come here again this is um i have removed that value uh so now required is three right it's still not zero so i get this um i come here i plus 1 i have done i plus 1 so it is still not in seen i add i plus 1 which is 1. i think i missed one more case here okay to check if all elements are used okay let's go um i have added what scene okay um then i call this function again i plus 1 okay i go here now the pointer is pointing to this value i come here it's not in scene so now the required is here it was three minus two and now it's minus one right because i'm here i already minus three from it and i'm now minusing 2 so required is less than so i come here this is false yeah so this is not a right way to code so what happen what is happening here is i came back from this value it has given me false result so now this is false i remove this i have added two here as well so i remove this and i am here right now so but where i am going how i am going through each so i think here i have to do like for i j in range i and hd and this is j right if not result remove it uh if result is true break let's see expected colon these are solutions i wanted to add two three four uh let's work for this but it's not working for this how is that possible okay uh if length of scene i'm still not sure it's right solution but let me try yeah it's not gonna work let's see the solution directly is the intuition dfs this is what i'm doing uh written false mastic we have l perimeter of square possible side perimeter divided by four yeah this is like mod base case reverse sort okay this is something i didn't do for this array represent the four sides and their current lengths okay some so these are this is making buckets like what i'm doing zero okay and then for dfs is equal to length uh okay sum sub zero one two is equal to equal the possible side it's not making any sense to me for now yeah it's to rest when not tourist and it's four is doing ok there is a dynamic programming solution uh what should i do should i post this or no i think i should post this at least um at least uh you might anyone might get some idea about solving how to go about such questions so maybe um the interviewer interview is like for 45 to one hour right minutes so i will make this video as a at max1r and then let's see um i tried i will try to understand the solution if i can in that time i will post it post the video okay uh in dynamic program what's important is that our problem must be breakable into smaller sub problems and also these sub problems show some sort of overlap which we can solve we can save upon by caching memorization suppose we have three four five i adds our matchsticks that have been used already to construct some of the sides of our square but all the sides may be completely constructed at all times if the square side is 8 then there are many possibilities for how the sides can be constructed using the mastic support we can have four three five three sides fully constructed or three four three five four five zero sides or one side completely reconstructed as we can see above there are multiple ways to use same set of matchsticks and land up completely different recursion states this means that if we keep the track of what all matchsticks have been used and which are remaining it won't properly define the state of recursion okay a single set of use mastics can represent multiple different unliterate sub problems and that is not right we also need to keep track of number of sides of the square that have been completely formed till now also an important thing to note is in this example we just considered was with the mastic begin used r and the side of square is eight then we will always consider that agreement from forms number of complete sides over the arrangement that leads to incomplete site since optimal arrangement here is 443535 with three complete sides of square uh let's take a look at the following recursion tree to see if in fact we can get over lapping sub problem i'm still not understanding the solution not all sub problems have shown in the figure the thing we wanted to point out was all of lapping sub problem okay we know that the overall sum of these matchsticks can be split equal into four halves the only thing we don't know is if four equal halves can be carved out of given set of mastics for that also we need to keep track of number of sides completely formed at any point in time if we end up forming four equal sides successfully then naturally we would have used up all the matchsticks each being used exactly once and we could have formed the square let us first look at the pseudo code for the problem before looking at the exact implementation in details here this is something i found recurse this is something i found slide formed is equal to 4 then square form that's fine for match in matchsticks available do add matrix to the mastic used let result uh request matrix formed if result is true then return true otherwise remove match from mastic used and return false so basically they are doing it for true case i was doing it for false case okay this is overall structure of our dynamic programming solution of course a lot of implementation details are missing here and that we will address now uh let me directly understand oh come on man this is a big question anything in discuss if value is less than 4 value mod 4 is not equal to 0 edge is four okay i didn't do this what is l1 l12 reveal for non-local edge if l2 is equal to equal l to l1 l2 l3 equal to h return true otherwise if i is greater than lane of mastics minus 1 so index is above the sorted array written false if any of this bucket is above edge written false otherwise um this is kind of cool solution so what i was doing is i was doing similar thing but i was trying to add matchsticks one by one bucket but what he's doing is he has all four buckets and um he's doing like caching uh sorry i don't know what how is this caching working but um his calling helper function by adding this matrix to any of these values so let's say it goes on this direction if it return false it goes in this direction it written false it goes in this direction it falls and if it goes in this direction it returns false so yeah kind of a kind of trick here can i improve this solution can i code my solution in this way i don't think i have time but i will copy this i will add it here and i'll submit this solution directly okay sorry could not solve this question i failed this interview thank you bye | 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 |
328 | Hello everyone welcome, the question of my channel is lead code number 3 28 but pay attention to this thing, I will make it very easy, I will explain it so well, it is simple, there is not much to do, okay then look, I have asked the company Amazon and Microsoftness, ask the question. If you have kept it then look at the input and output and understand what is the question, it will be fine, you have to rearrange it and see how to rearrange it, this is the first note, this is the second, this is the third, fourth S is set and the rest. Those and ones are fine but look at the ordering. First A came, B then came BN, so it should be from ordering. But first see what we did here, we aggregated all these ODs at one place and the AND ones. If you have done cricket, then you have to rearrange it is okay, it is not too much, when you explain it, you will understand it very well, you just have to listen carefully to how it is approached, you should know that such questions should be solved from the beginning. How will we make it, that is, we will not come to a direct solution, we will have to think a little, after that we have to move ahead. Okay, so see, this was our example. Look, pay attention. In the example, ABC will not be given, numbers will be given. I have deliberately written electricity so that Don't you get confused? This is the first, this is the second, this is the third, this is the fourth, this is the fifth. Okay, let's reduce one more. Whenever I have to draw, I make a box diagram of it. Remember, what is the link? Value is here and it is easier for me to make the next point. By the way, if you always make a box diagram like C, then I convert it. It is ABCD and every note has an address, so see it in the next section. It is twenty, right, this is CX, open it, then look, its next point is C, it is opening DX, its next point is DX, it is null, right, because it is pointing to null, okay, it is clear till now, so generally what do I do? I always make a box diagram to prepare the queries of linked list. Okay, and you must know that there is a head, this is our head which has the address of the first note, so the first note. Which one is it, what is its address? I am smoking river for that and kept the and pointer okay so you see what we have done here is we have made OD equal to head na what is the value of head x is na so see OD which is pointing Is and look, pay attention to whom is And is pointing to the next of Head, isn't Head say, what is the next of X, what is the next of That's why I make a drawing, it is very easy for me to make it like this, it's ok, order and so we have written it, now what we have to do is that it should have been connected to it, but it is connected to it here, so we have to break it, ok. We will not break it like this, stop here, what did I say that this is an OD, this is an order, what we have to do is to cross it, then let's point to it, okay, it has been done, but how will it be done in the court, then I can say no and many more. It is clear, first I made it by drawing that Han should point to this and K is equal to Next, so it is okay here, let's go into the code, okay, so let's reduce it by one, I cut it and make it English. No, it will be clear, okay, let's see, I have to do DX, okay, so what will I do next [ I have to do DX, okay, so what will I do next [ I have to do DX, okay, so what will I do next Okay Whatever is next, its next, okay, so pay attention to what's next, CX, and what will be next, DX, so The drawing we have made is important. After that we have converted it into code. Okay, what I had to do was to point to the fourth one, that is, let's make it from this. Then again I have to connect this to this. I first connected it, after that the code is written here, okay, it's done, now pay attention that this is shorted out, it has to be changed, okay, so I go to CX and DX, right? C I write C No, and we should have changed this DX, at the same time, this happened, you are looking at the DX, it is reducing the correctness, as we are writing the code, it is reducing the correctness, now look and here we go to the third one and Hey, the fourth one is absolutely correct, the third one is mine and the note is mine, the fourth one is mine and the note is here. Now let's tell the story again. Okay, let's tell the story again. See what should have happened according to me. Odi, someone. Should have been pointed, let's get the point done, then we will write in the code that it was done and Ka is next to, and if the connection is X, then A should have been adopted to What will happen and is the connection ok? I got help from the line. What did I do here? I did A It is here later, it is okay, what is it, after making the drawing, after writing the code, the next connection of and is, what is the next connection of this, what is the next of this, it is the tap, that is, the tap is here, it is okay and this is The one that was there, I have cut it, so let's remove it here, okay, till now it is clear, the drawing made, converted it into code, okay, now what was the next line, brother, let Ode move forward and Let's go ahead and let's go. Okay, so look, pay attention where OD will go and here A will go here is the next order, so the order had changed, we had made So and A will go out here and A will go out Okay so our loop will end Okay we have to run the loop until and is null So we will go out now So now notice we have done our less almost See, should I limit Green to Green, not to Blue, or do something else? After that, to which point is it connected? Is it connected to C? When it comes out of the loop, it is pointing to the tap right now. Okay, let's go, no problem, let's pay attention to this now, let's see, the di is pointing to the tap, okay, so if we see, what have we done ACI and B went to the di and B and what have we done B And DI has been collected and DI is pointing to my tap, is n't it? And IB is pointing to my tap, so now we have played cricket separately for both of them, the odd ones have become hard and the odd ones have become tough. There are pits, but we have to connect, so look, what is the name of I, connect, we have to connect, so look, what is the name of I, look, now OD is pointing to OD, which is I, it is fine, that is, what will happen in the last, right? The OD pointer, which is obvious, will be pointing to the last note pointer of the OD link list. Okay, here, so I will not do anything, what will I do and what do I have to do, so what will I do, so what will we do and so Let's start the and just don't do anything here, let's sign the and start here, our [ __ ] is done, okay, our [ __ ] is already done, our [ __ ] is done, okay, our [ __ ] is already done, our [ __ ] is done, okay, our [ __ ] is already done, everything is a perfect match Okay, and this is the loop we How long is it going to run until whatever is there comes out, just convert what I will say now, from what I have just said, I will say the same thing while writing the code, okay, it will convert the story, okay, so let's do the coding of it. If we take it, then the question is the same simple, you have to cricket the order and the number separately, okay, you have to connect it later and send it, like if you were three four five, then look, give 135, it is 24, then the order and number have been completed. Okay, let me tell you the story again that we have to order and smoke cigarettes, this is what we have to do, neither will we take anything, and it is okay to point to and, after that we will cricket them separately and connect the ODs separately. We will start connecting and separately, in the last we will connect more and. Okay, so let's do as you say. Okay, we will start from the head. What was said in the last that we will store the next part of the head. Because in the last we have to connect, right, the order of and, so the and will be its own separate cricket, the odd will be its own separate cricket, but the odd point, which will be the segregated part, will be the last k point of it, okay. So in the last what we will do is to connect the next of OD to and that is ok so look at the starting point of and ka what is the head dot next then store it here and connect the starting of and ka to it and starts is ok. We will go on till the and is not equal, you become null, okay, what did I say that OD's next, what did I say, that and connection will happen, that and's next will be next, okay, and ka's next is okay Hum Maximum Where are you running but look here, this means that we do not want the next tap of the event, even if by mistake the next tap of the event is done, then this code will neither be fat nor can it be fat, if the airport is there, then the next video of the answer key van. Right, that null should not be there, so here it is written that I can see that no in the loop of the link list, maximum to what extent, if I want to make it disappear, then the next of and should be at least North null, only then only. Will be able to go ahead in the next one, okay, then I set the condition here accordingly, okay, it is not that you already know the condition, okay if it is so good, okay, many people are able to do it, but I generally do this first. I write this, I write the condition according to that, okay, this is done, then what did I say that the OD guy is doing like the oven is here, so what will I do, connect the o3. I will do this and I will connect three to and then I am doing the same in the last kiss which I have connected to E1 means and next starting Let's run it and see and the connection is written big so that it becomes clear. Okay where have we made the corner? Didn't do it's an obvious thing, friend, if your grade is BF question, I try you help and I will repeat again, always make the questions of the link list in the diagram, in the boxed diagram, after that, nothing else, you have to write the story, code the story. ok optical in next video thank you | Odd Even Linked List | odd-even-linked-list | Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_.
The **first** node is considered **odd**, and the **second** node is **even**, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,3,5,2,4\]
**Example 2:**
**Input:** head = \[2,1,3,5,6,4,7\]
**Output:** \[2,3,6,7,1,5,4\]
**Constraints:**
* The number of nodes in the linked list is in the range `[0, 104]`.
* `-106 <= Node.val <= 106` | null | Linked List | Medium | 725 |
316 | hello and welcome to another video in this video we're going to be working on our move duplicate letters so in this problem you're given a string s and you want to remove duplicate letters such that every letter appears once and only once and you want to make sure your result is the smallest and lexicographical Order among all possible results meaning it's just the smallest and like alphabetical order so if you have a bunch of outputs and you rank them in terms of which one comes first in alphabetical order that's the one you would want so for b c a b c any time we have two letters we have a choice do we want the first or the second letter so the best possible result with all your letters is a strictly increasing string so if you can whatever letters you have this would be the best result with ABC it's strictly increasing right it's essentially it's kind of like numbers like let's say a bunch of combinations of one two three and you have to use each one of these numbers once and they ask like what's the smallest number well it's gonna be one two three right you want the leftmost number to be the smallest possible because that's the most important number it's similar for a string when you do string comparison the leftmost letter is the most important and that needs to be the smallest possible so then we have c b a c d c b c uh and similarly here you would want the leftmost letter to be as small as possible so we're going to want to use this a and then what comes after well we can use a c wherever we want right but do we have to use this D because it's the only D we have so this the this is the best thing here you can use some other D's but essentially if you had instead of this if you had a d b c or any other one of those that would be worse right so because you have to use this D you will either have ACD or ADC and then a b and ACD is better okay so the first thing to recognize is the smallest lexicographical string is actually you know the leftmost character needs to be the smallest and then it needs to be like strictly increasing so ideally if you have ABCD you could do this would be the best possible case but this can't happen because there's only one d right and the a needs to come first so if they need to come first you have to use like this part of the string somehow and so it would have to be a d uh CB so or actually would have to be sorry it would have to be acdb because there's only one D and you have to use it and you want the C to come first so now that you recognize in order to have the best possible string our characters need to be strictly increasing when you see that kind of thing it typically tells you want to use a stack right either strictly increasing or strictly decreasing but the problem is for every character we have to know like can we delete it and is there a character later on and so there is a way to do that and so what we're going to do here let's just take this string as an example so we have CBA c d c e here it is so what we really want is to know like the last there's a couple ways to do this you can either know the last possible index of a character or how many you have left either one's fine so you can record how many you have left and then go care and then go letter by letter or you can just record the last possible index of a character and it's very easy to record the last possible index of a character essentially all you do is you should make a hash map and then you just so if we give these things indices three four five six seven the way to know the last possible index is you can simply make a hash map and then you just override the value so you just go left to right and you store the letter and its value and for example for the cable store like c0 and then C3 and then C5 and then C7 so the last value would be C7 so for a there's only one location which is two for B there are two so first you would store the one then you would store the six it would overwrite it then for C there would be a seven right you would store the zero you'd sort of three the five and the seven so you just override it and then for D there's only one location which is force now that we have this hash map we and we need a stack we also need one more thing we need to be able to check if the letter is in our stack in oh one time now technically you don't really need a visited set because uh you can't actually just manually Loop through the stack if you wanted to because the stack can only be 26 letters so it's like constant time but we're just going to make a visited set because that's going to be a little bit faster so essentially we're gonna have a visited set and we are going to have a stack and I'm going to kind of show you the process behind this so let's just use another character so let's say we start the C we just go character by character so for the C our stack is empty so we're just going to put in the C right and we're going to add it to our visited set now we go to the B and basically we want a strictly increasing uh stack so for every character in here already we're trying to add a b but B is less than C so ideally we want to have B and then a c afterwards right like B and then a c is always going to be better than CB in increasing order so we need to track before we remove the C does the C actually exist somewhere down the road so we're over here so we're at index one so we need to check like where's the last occurrence of c and it's at seven so we can see there is a c down the road so we can actually get rid of this C and just add the B and we add it to the visited set then we try to add a and we do the same thing we check for every letter before is the letter smaller well B is not smaller than a so ideally you'd want to have a then D but is there a b down the road yes there is there's a b index six so we can get rid of that as well now we add the a now we are at C and so here we can just add the C straight away because the letter before the C is a right so AC is totally fine that's strictly increasing totally fine okay now for D is the letter before uh D strictly increasing yes totally fine and we only have to check one letter because there's going to be two cases there's either going to be the whole thing is strictly increasing or you just can't get rid of the letter as I'll show you later on so once there's a letter you find that breaks the rule you don't have to check down like the rest of the stack you just have to check until you get rid of the letter okay and so now we are at the C then we check is the C in our stack already well C is already in our stack so if it's already in there we don't want to put it in again right we already have like the optimized stack here and so we're never going to want to add a c later on like you're always going to want to keep the one you had before so we can skip that one okay now for B so B is smaller than D so ideally we would want to get rid of D but can we have to check what's the last index of D well last index of D is four and we're at six so there are no more D's so we can't get rid of the D we can have adbc because this would work right but essentially if you can't get rid of D you never want to get rid of C because this is already strictly increasing so if you got rid of the C then it would be a d b and this is better right so a d b c is worse than the solution right this is greater so essentially kind of you get to a letter that you either can't remove or that is uh smaller you would just want to stop there pretty much yeah so anytime you can't pop the last character you're never going to want to do anything again because we already have like the current optimized spring without this letter so we're never going to want to like change that so now what we're going to want to do is we're going to want to add the B and so I forgot we actually had this D in here already we're going to want to add the B and so now this is our answer now for the C we already have it so we don't want to put it in again so as you can see it's already here and so this would be our answer acdb so let's write down our cases for removing from a stack right and both of these have to happen so the end of the stack has to be greater than the letter we are adding and another instance of that letter at the end of the stack has to exist further down right we can't get rid of a letter unless it exists further down because we have to have at least one of every letter but that's pretty much it so to remind us of the steps we make a hash map that is going to give us the last index of everything we keep a visited set or you could like I said you could actually technically go through your stack because your stack is going to be maxed 26 letters and for every letter you're trying to put in you just make sure like hey if the letters before it are worse can I get rid of them and can I add them later on and if you can then do that and if one of them if the very last letter can't you can't get rid of it then you just stop right there and that's pretty much the code so like the tricky part is figuring out this like lexicographical order how to get it but other than that it's pretty straightforward to code so let's just code it so we're gonna have a stack and we are going to have a visited set so we'll call it uniques and we're going to have this last index hash map or like I said you could have a count instead and we're going to use a dictionary comprehension here so we're going to say it's going to be letter index oh yeah four uh index letter and enumerate s and essentially a numerate will give you the index and the letter right so that's what we want now we are going to Loop through the string so for index sweater in enumerate s if the character is already in there we can just skip it uh for some reason we have this there we go and now we just have to Loop through our stack so while stack and the character has to be less than the last item in the stack and the last item in the stack actually has to exist right well there has to be another index so I has to be less than the last index of Stack minus one so essentially this part is just saying like if we remove this character is it somewhere down the road or is this the last one so if that's the case then we can remove from the stack so we want to pop and then we want to actually remove that from the visited set right so we pop and then we remove that letter from our uniques and then once we're done with that once we're done with cleaning up the stack then we want to add the current character we're on and we also want to add it to the stack and so finally now we have a stack of our entire word but it's going to be letter by letter in increasing order so now all we need to do is we need to just join the stack on a space right so it's going to be this dot join stack because essentially you know if our word is ABCD we're storing it like this for now so we need to actually return a string so let's see how that goes oh let's actually get rid of this so you can see the errors letter is not defined uh and there we go and you can see it's really efficient so let's talk about the time in space and like I said for a lot of these technically like if you didn't have this unique set it would still be fine because our stack is only 26 characters so you can really use the fact that you only have 26 characters to really add a lot of like things because it's basically of one space so let's think about what would happen here so we are going through every character here so that's o of n then we're going through every character here again and now if you think about it the worst case scenario is we add everything to the stack once and then we remove it from the stack once right so we can only add things to the stack one time and we can only remove from stack one time so worst case this is like you know we add and remove from the stack which is 2 times n and so this is pretty much going to run worst case 2 times n this is n so this is O of n time and for the space Oh like I said a lot of these things are very convenient because there are only 26 characters so this last index only 26 characters that's o of one um uniques only 26 characters of one so you can really abuse this like 26 character thing and make a lot of data structures that just use characters A through Z and that costs you nothing so uh yeah then for our actual stack also only 26 characters so 26 characters because they all have to be unique and then our result is maximum obviously 26 characters but we don't count the result so we're going to say this is o1 space because all of these are content space they are just 26 characters no matter how long their word is it could be a billion characters this will only be 26. and yeah so I think that's it for this problem hopefully you liked it and if you did please like the video and subscribe to the channel and I will see you in the next one thanks for watching | Remove Duplicate Letters | remove-duplicate-letters | Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/) | Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i. | String,Stack,Greedy,Monotonic Stack | Medium | 2157 |
1,648 | hey what's up guys this is chung here so let's talk about this week's weekly contest number 1648 self diminishing valued colored boss all right so i this is a interesting i would say it's a math more like a math problem okay so you have an inventory of different colored balls and there is like a customer that wants other boss of any color okay and this customer they're like a bunch of descriptions here right basically you know the customer will really values the colored balls each color both values the number of balls that color you currently have in your inventory so which means that if you currently have six yellow balls okay and then the first time you sell the first yellow ball you get six values and then the second time you get five and then four five three two one and two until you sell everything okay and then you're given like an integer of arrays and this inventory which where the inventory i represents the number of the boss okay of this color of the ice color and you're also given like an integer order so the others is basically the total number of bots the customer wants to order and you can sell the box in any other and it asks you to return the maximum total value that you can obtain after selling the others since the color the answer may be too large return it return the modular of this one so a few examples here right so for first one let's say you have two color one bars and you have five color two bars and in total you need to sell in total you need to uh you need to sell four balls in total so as you guys can see here so the first time you sell five right you sell five four and three until you reach so after selling five four three right after setting three balls now the two colors are have are having the same number of balls right which are both two that's why the last thing you sell you can either sell uh the color one or color to color two so that's why in total you have 14 balls okay and then here's like a tricky example here as you guys can see here you have a huge number of the others and only one numbers only one color box here that's why you i mean you still have the answer here right so cool so and here you have like this uh constraints here right so for this problem you know so what's going to be the naive or brutal force uh approach right of course is by using the priority queue right basically every time basically we push it push all the number of the box into the priority queue and every time when we are like decreasing the others here right we also we pick the highest number of the current colors right and then we decrease the number by one and then we push it back to the priority queue and then we just collect that value the cut that highest value to the final answer right that'll be the not even brutal force way and as you guys can see that will definitely tle because the uh because the inventory where the order with others is has the limits can be uh out up to 10 to the power of nine so if you are just simply using the priority queue and try to decrease the others one at a time you will definitely tle okay so we need to find out like a more efficient way of decreasing or of selling the boss so what's going to be the highest the i mean the more efficient way so basically you know i'll give you guys a few examples here let's say we have a 10 and then we have a of eight we have six and blah okay so in total let's see that in total we have the boss of we want to sell 20s 20 in total so the way it works is that first we sort the number of the inventories from the biggest to the smallest and every time we're comparing the current one with the next one if the current one is greater than the next one then we know okay we can sell we basically we can make uh three sales like 10 nine sorry we can make two sales basically from 10 uh the first time we can sell uh sell the numbers of 10 right we can sell we can make the cell from 10 to nine and then from nine to eight so why we only we can only make two cells because after the two sales right we'll have two colors which uh who is having the same numbers which means we have eight here eight right so i mean after two sales if we want to continue to make the sales we have to do the factor of two right so we have to do the factor out of two factors is not equal to two because at the next time when we sell the make another cell right let's say we have 20 right so after two cells the others here right we have others here uh we'll talk about how can we collect the uh how can we collect the values uh by setting the balls i'm only talking about the others here so the first time we have a we make two sales right and then the others will become to 18 right so now the factors becomes two because like as you guys can see we have two eight here so now from eight to six we can again make two sales but this time we have to do a two times this is this factor here which means after two sales again uh basically we'll be selling four bars in total right that's two plus two so that's why after this two here we have like 18 will be comes to 14 right so let's say we have a two we have four here okay so after another uh two times two sales now both of this 8 becomes 2 to 6 right so which means we have 3 6 here right which means every time we have like a different one we see the different numbers we now factor equals to three right so when the factor is three it means that from six to four again we can make two sales and every time we can sell two times three bars right which means uh it's gonna be uh gonna be become to eight right so we keep saying that until we have reached the uh basically you know as long as we can make the like you can think of oh as a wholesale as long as we can say we can sell everything that the current factor represents we can just use the same logic right and then in the end when we reach a point that we cannot uh sell everything we have to do a little bit different for example here let's say we have a let's see we have 20 let's say we have 20 others left okay and all we have is what let's see we only now the only boss we have is it's three eight let's see we have 3 8 here it means that we have three colors uh that which every each one has like eight balls left right so at this point how can we and there's nothing else left so how can we make the cell this uh this three box here as you guys can see so what we do a 12 divided by three so what does this mean it means that we can sell three balls all together uh six times right so six times and then after six times we cannot sell three all three bots here which means we have like how many bars left we have 20 uh do a modular by three we have two so which means that the remaining two we can only sell two right so what does it means that you know from eight uh to make three uh to make six wholesales what does it mean it means that we'll sell eight plus seven plus six plus five plus four plus three you know what actually i'll write everything here you know plus zero so after making uh six wholesales where are we now we're at we are three here that's the one two three four five six right basically that's the uh that's the values we can collect by making uh six three six wholesales so basically we collect this eight to three and we of course will we multiply by three in the end and how about this two here right after three after six uh six wholesales this eight will becomes two to two and now we just need to make another two uh two out the last remaining two others which means that we'll have like this two times two because we will be uh out of these three twos here we'll make another we will make the last two sales that's why we have this two times two in the end all right so that's the basic idea of how can we uh approach to the final answers and as you guys can see the another crucial uh part for this algorithm is how can we calculate from eight the sum from eight to three right and so how can we calculate that because you know it's obviously no i think everyone knows how can we calculate from eight to one right so what's the formula for that right that's the n times n plus one divided by two right and how but how can we calculate it from eight to three right it's pretty straightforward right i mean and if we have the if we have everything from eight to one and then all we need to do is we just uh subtract that two to one and then we have eight to three right so which means that you know from n times n plus one here right what do we can simply do this we sorry we subtract the what the k let's say this is k right okay k times k plus one let's say the k is equal to two right so that's the basically the formula we will be needing to calculate eight to three right yeah that's it okay so with that being said i think we can start our coding okay all right cool you know since we'll be using that get summary get some formula multiple times i'm going to uh extract it into a separate functions here you know that's which will make this code much more readable so i will have a start and end okay so here you know i simply return the start times uh start plus 1 and then divided by 2 minus n times uh end and plus one divided by two okay so by starting n i mean this right so we have a eight seven six five four to one i mean by starting n i mean i'm trying to get the sum from let's say from eight to six so from eight to six then the at the start is eight and the end is five so n is five this is the end this is start so keep in mind i'm the end is not six okay it's five all right so okay now we have to get some functions here that so let's try to sort this uh this inventory first you know since this uh variable is kind of long i'll rename it to inventory to inv here so i'll do a inv dot sort okay and since i'm going to sort it from the uh from the a decent in the descending order i'll do a reverse equals to true okay and then the factor right the factor at the beginning is one so the factor means that you know how many uh colors right how many colors have the same amount right and since we're sorting from the biggest to the smallest and the factor will always be increasing right and okay we have n equals the length of i and v and then we have uh what uh we have i here so the i will be the inventory where we are currently uh at right now and then we have our answer the final answer will be equal to zero so the way i'm doing the loop here is uh i'm doing this others here right so while the others is greater than zero okay so when the order is equal to zero then we know that's when we need to return our answer okay so the answer will be uh i'll finish the answer here you know so when you guys like at the interview or like any uh or any type testing or any exam you know i think it's always a good habit to uh to finish the main logic part like this mod equals to the 10 to the power of nine plus seven and then in the end you do this you know and then you implement the details because otherwise you know what if the if you're in the detail implementation it is pretty complicated and then you'll be forget you'll be forgetting what you want to do in the end right so okay so now we have these things here and okay like i said right so first thing first the most the easiest scenario is that we can make the whole cell with the current factor which means that we can simply subtract that the difference from the others and if the i is smaller than n minus 1. so i do this check because i will be checking this one because i'm like i said i'm checking if the current one is greater than the inventory of the i plus one i only do this uh decrease when the uh when the current one is greater than the next one because if they are the same i'll just keep increase i'll keep moving the eyes forward uh most while increasing the factors here okay so here like the if we can make sale for all factor boss right for our factor okay right so i'll try to finish this one later so else if right else if what else if we can not make sale for our fac factor right here we have al we have another if here right i mean i'll see if the right if that's the case right what do we simply do that we simply do i uh plus one and then we do a factor plot plus one that's the last step right because you know if the current one and the next one is the same we don't do anything we simply uh we'll simply just uh increase the pointer and then we also increase the factor right because we are we have we're accumulating one more uh colors who is having the same amount right so now the first one right if we can make the whole sale for all the other for all the factors right so it means that first thing is that it's always the if the current one is greater than the then the net the next one and what and this right let's see and what the others right is greater equal greater than what then the factor times what the inventory i minus inventory i plus one right so here i mean of course since we're going to check the i plus one that's how that's why do i do this track here and the second one is the uh if the time the con is different and we can make the whole sale we can sell we can make the wholesale for the difference for all this factor right and then we do what we do we simply do answer right we simply accumulate this answer with the current factor times this times the let's say from eight to six right so now the inventory i is eight and even to i plus one is five in this case so what's going to be the values we can collect from eight to five right so from eight to five we have what we have get some inventory i and then inventory i plus one okay all right so that's how we calculate the values we can collect from selling this box from eight to five by selling the number of these factors right so that's why we have eight seven six okay and after this say after this sales the others becomes to what becomes a factor times the difference right times this one all right cool so that's the this is the easy case which means we can sell we can make the sale for the for a difference for all the factors and the second one is a little bit uh complicated one which means that we can make the sale but we cannot sell everything just remember when i said we have 20 balls 20 others left and then we have a 3 8 left so in this case we can only make six whole sales and the remaining two will be calculated later so in this case we have and what do we have here again right again it's has to be like this we also need to check this but and then but you know we also need to check okay so we can do this if i is in the n minus 1 or this okay so just for this case right let's say we have a 3 8 left here so whenever i is the same as um has re has reached the end of this array here we also need to do the calculation or again or the uh what is the inventory i is greater than inventory i plus one okay same thing so but at this time we cannot make the sale for the whole factor here right so that's why we have to use what we have to uh i'm going to calculate sale all times here so how can we calculate that we use this remaining others and then we do a we do division by the uh by the factor right that's the numbers we can sell first okay we do this vector do uh like the double slash divide division here so we can get like an integer here and so for this one that's the how that's the number of times we can sell right for the whole factor here so and now let's calculate collect the values we can we'll get by doing that so again we have a factor right and then what we have a get sum right again we start from this inventory i right and what's going to be the end the ending point for this time it's going to be inventor i divided i'm sorry miners sell all times so why is that right for example here so we have six here right so we can sell so now sell our six so which means that we can sell eight seven six five four three two one we sell six times that's why the end the ending point is two in this case which is the in the inventory i eight minus six is two okay so that's that okay so how about so the next thing is going to be the remaining others right so what's gonna what's the remaining others uh it's just the others uh do a modular by the uh by the factor which in this case is two right so 20 divided uh dual modeler by six is two which means we have we still have two others we need to sell so now with those two orders right it's pretty obvious that the it's going to be the remaining others times what times the uh times this right times this one because that's the uh the numbers we'll be having here what will be left here so we have a three we have three twos left that's why we're gonna be uh multiply by two here okay so once this is done don't forget to set these orders to zero because uh by this time you know everything is zero or we can simply do a break you know let's do it let's do break because we have cell we have sold everything so yep cool so let's try to run the code here i think that should be everything all right run the code didn't make any mistake here let's say let's see uh oh here i think i'm missing out like miners sign here okay run code all right so this time accepted submit all right cool so it's accepted so that's the uh basically the logic here and for the time space and time complexity right as you guys can see here we have stored here that's why we have unlocked in here right and here will be uh will it this one is bounded it's bounded with the number of the i here because every time we'll be increasing the eyes here and by the time we have it reached the end the others will be zero or uh by the by that time so that's why here we have n here you know and in total the time complexity is the unlock and it's just this sorting here yeah okay i think i'll stop here i think that's it for this problem you know it's this one is i think for me it's more like a math problem because math plus greedy you know as long as you guys can um to figure out how to calculate the range sum you know and also the uh how can you like use this factor to d to determine like the uh how to uh do a full a wholesale or how can you do a partial sale and then do the remaining you know this one is more like a implementation heavy problem plus some a little bit of math okay i hope you guys like this video alright thank you so much for watching this video guys stay tuned uh see you guys soon bye | Sell Diminishing-Valued Colored Balls | minimum-insertions-to-balance-a-parentheses-string | You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the customer would pay `6` for the first yellow ball. After the transaction, there are only `5` yellow balls left, so the next yellow ball is then valued at `5` (i.e., the value of the balls decreases as you sell more to the customer).
You are given an integer array, `inventory`, where `inventory[i]` represents the number of balls of the `ith` color that you initially own. You are also given an integer `orders`, which represents the total number of balls that the customer wants. You can sell the balls **in any order**.
Return _the **maximum** total value that you can attain after selling_ `orders` _colored balls_. As the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** inventory = \[2,5\], orders = 4
**Output:** 14
**Explanation:** Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).
The maximum total value is 2 + 5 + 4 + 3 = 14.
**Example 2:**
**Input:** inventory = \[3,5\], orders = 6
**Output:** 19
**Explanation:** Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).
The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.
**Constraints:**
* `1 <= inventory.length <= 105`
* `1 <= inventory[i] <= 109`
* `1 <= orders <= min(sum(inventory[i]), 109)` | Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer. | String,Stack,Greedy | Medium | 2095 |
754 | hello everyone welcome back to harlot called Channel today I'm going to talk about a new problem Richard number the this problem has medium complicity and first let's look at the problem is that you are standing at position 0 on an infinite number line there's a go at position target and on it you move you can either go left or right during the end smooth studying from 1 you take n steps and it asks you to retain the minimum number of steps required to reach the destination and here are two examples let's use the example to understand the problem better the first example is the target is 3 and you are standing at 0 right now how many moves do we need to go from 0 to 3 so on the ends move you can move n steps so like in this example on that we on the first move we move one step on the second move we move to step so you can use to move to reach your target rate so the output is 2 and another example is the target value is 2 and you will start studying from 0 and that's the how many moves Joey needs to reach 2 so the answer here is that you this is the first move second move and the studs move you will be able to reach 2 so the outputs value is 3 and so let's see how can we solve a very general problem such that you the target value is here and we are here so the way we solve this problem is that at each move you can move either you can either move left or moves right if you move let's then that means to minus some value if you move right then that is to add some value so then the girl can be expressed using these expressions such that for each value you can either for each move you can either go right or left so when you sum up the left and right together eventually you reach target and we want to find the minimum value and here as the solution to this problem and an naive approach is to enumerate all the possible combinations of the positive and negative sign I mean either go left or right so for each one we will try each combination so the time complexity will be 2 n so this is an exponential complicity now let's consider other approach that first let's take a very greedy approach so say you want to reach target how can you reach it as fast as you can and very into intuitive approaches to always go to the right side so that means you adapt move one move 2 to the move and together the value you want to find them first value that can expect target which means if you go always go right after and move you already somewhere here but you are not exactly at the target you may be like K steps right beyond the target so that means for some value here we cannot put the plus sign is that we need the minus sign to make the expression here exactly equal to the target so let's discuss some cases here of how the value of K can be depending on whether it's even or odd so if the K is even then we can find the sum value all right such that two times I equals K which means we can just - I here then which means we can just - I here then which means we can just - I here then the left expression will be exactly equal to target but if case odd then we can not find a value art which satisfy this function so that means we need to move some steps for the right so like for example if we move one actress that one action moves with n plus 1 steps then the here's the expression on the left side the expression on the right side and so our target is to find this sum value such that the right side here the combination here can be an even value so we further discuss the case here if Empress is odd then k plus n plus 1 is even so we can similarly we can use this approach to find an I which is equal which such that two times I equals to this value is even but if n plus one is even then this side here it will be an old value so we need to move an extra move that is Empress 2 steps such that this very will be even so we can find I hear to find an I hear such that two times I equals this expression so summarize the results if we find an expression we find first we find an end such that 1 plus 2 plus n is at least larger than target and then depending on different value of K we different value of K whether it's even or odd we have different solution and if K is even we can find an eye directly if K is odd then we just go need to do actual moves depending on the value of M minus 1 when n minus 1 is odd that way it only needs to do this move when n minus 1 is even then we need 2 action moves ok so this is the solution of the problem and the time compress there is a constant time which is all 1 because we just enumerate through 1 2 and minus 1 underneath let's look at the code to see how we solve this problem so first I've got to mentioned if target is a negative value first for simplicity we can directly make it as positive value because the result will be exactly the same and the first that finds the first n such that 1 plus 2 plus and equal R is equal or larger than target so this is the N value this is the position so when petitioner is less than target we keep it up there and value by one and I kept moving right and so that's here we got that one press M press to present equals target plus K depending on different value of K the results will be different so um we discussed the edge cases here one position we will current they're already at target the record returned end and otherwise we can play decay like how many actual steps have we moved which is equals to position - moved which is equals to position - moved which is equals to position - target and then if the K is an older value is an even value that we can find an eye as we discussed so we can directly return n and otherwise if impressed one is an it's an alt value we've written we return and press one otherwise we'll return and press 2 and this solution is accepted and this is a constant compressed a solution that compressed is all one yeah okay so that is this problem Manik is purpose of testing like the mathematic and logic thinking of problem rather than other techniques so this is quite an interesting problem hope you guys can enjoy it and thank you for watching this video I will see you guys next time thank you | Reach a Number | cracking-the-safe | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. | Depth-First Search,Graph,Eulerian Circuit | Hard | null |
1,262 | solving the greatest sum divisible by 3 problem from lead code using dynamic programming is what we are going to do in this video of joey's tech welcome my friends i am joey and yes i will be telling you how to think of the approach to the dp solution of this problem this is one of the exciting problems i came across and let me tell you solving this problem using dp will feel truly magical to you especially in the way we are going to approach the solution so without further ado let's look into the problem statement now you are given an array of integers nums like this these are the elements inside the anoms that we are going to consider for our problem the ask is to find the maximum possible sum from this array nums that is divisible by 3. so if we carefully take a look at it then if we add 3 6 1 and 8 then we are going to get 18 and that happens to be the maximum possible sum divisible by 3 from this array nups so we need to come up with a dynamic programming algorithm that produces this result 18. but before that a humble request to you to subscribe to my channel if you haven't done it already and hit the bell icon so that you do not miss out on these videos especially these dynamic programming videos i create for you all right you can see the array over here now let me tell you that i tried a few approaches of tb to solve this problem like the two variables approach using which i have solved numerous problems using dynamic programming but especially in this problem i found those approaches getting complicated so the basic idea or the stepping stone to solve this problem using dp lies in focusing on the phrase divisible by 3 when we divide any integer by 3 then what can happen the integer either will be completely divisible by 3 or will give the remainders 1 or 2 right just keep this in mind and now look at the problem in this manner what the first integer in this array is it is 3 and it is divisible by 3 so the greatest sum till here is 3 okay now we move to the next integer which is 6. so 6 is also divisible by 3. that's one candidate and we have a candidate already present which is 3 and since the problem is about finding the sum the greatest sum the maximum possible sum hence we get our third candidate as well which will be the summation of 6 and 3 which comes out as 9. look all these candidates are divisible by 3. so we pick the greatest one out of these 3 which is going to be 9. so till here the greatest sum that is going to be divisible by 3 will be 9. all right we move to the next integer of the array now which is 5. we are going to expand the horizon of our understanding so make sure you watch this part very carefully the candidate which is the greatest sum divisible by 3 till here is 9 right now we add 5 to it when we add 5 to 9 we are going to get 14. when we divide 14 by 3 we get 2 as the remainder so no way 14 is the greatest sum that is divisible by 3 but we need to keep track of it because it will help us in the future to find the greatest sum divisible by three because there are more elements remaining so we open three slots the first one is going to store the largest sum for which the remainder comes out as zero when it is divided by three the second one will store the largest sum for which the remainder comes out as 1 when it is divided by 3 and the third one is going to store the largest sum for which the remainder comes out as 2 when it is divided by 3 so 14 goes in this slot of remainder 2 but let's start over let's start from the first iteration so that you understand in a much proper way in the first titration the integer is 3 when it is divided by 3 the remainder comes out as 0 so the greatest sum till here will be 3 which we have already seen so we are going to put 3 in this slot of remainder 0. note why we have put it in this slot of remainder 0 because the remainder came out as 0 when we divided it by 3. now in the first titration the other slots will be empty i am going to fill these empty spaces with 0. now the algorithm is going to move to the second iteration here 3 will be added to 6 the addition of 3 and 6 will be 9 which is completely divisible by 3 so 9 also goes in the slot of remainder 0. all right and these slots of remainder 1 and remainder 2 will have a 0 as their values because there has been no greatest sum encountered till here for which the remainder comes out as either 1 or 2 when they are divided by 3 in the third iteration 9 will be added to 5 and that is going to give us the sum as 14. the remainder comes out as 2 when 14 is divided by 3 hence we are going to put 14 in this slot of remainder 2 but wait a minute there is another slot that we are going to fill and that is the slot of remainder 0 where the greatest possible sum so far is 9 so we won't hesitate in bringing 9 here in this slot of remainder 0. so for every iteration the dp algorithm is going to compare the values present in all these three slots against the values present in the same slots in the previous iteration and between the two values the greater one will be populated in the respective slots so for the algorithm the default value present in these slots will be 0 compared against a 9 will bring a 9 over here that's how algorithm is going to work the same comparison will happen for these slots as well 0 will be compared against 0 so no change 14 will be compared against 0 14 is much greater so 14 stays populated in this cell of remainder 2 in the third column we move to the next integer now which is 1 we add 1 to this 9 what do we get 10 the remainder comes out as 1 when 10 is divided by 3 so what we are going to do we are going to straight away put 10 in this slot of remainder 1 we are going in a much formal fee now the way the tp algorithm is going to proceed this is how i shaped my own understanding guys now we are going to add 1 to this 0 as well okay we are going to add this integer to the values of every slot by adding 1 to this 0 we are going to get 1 so when we are going to divide 1 by 3 the remainder is going to automatically come out as 1 so we try to populate this lot of remainder 1 with 1 but there is already a giant value sitting over here which is 10 is greater than 1 so no way we are going to put 1 over here we keep 10 and discard one you are now going to ask me why i didn't add five to these zeros of slot one and two or why i didn't add the six to these zeroes of slots one and two the answer is i didn't want to create any confusion earlier now if you go back and if you add 5 to this 0 then you are going to get 5 you divide it by 3 the remainder is going to come out as 2 hence you will try to populate this cell with 5 14 is already present over here which is much greater than 5 so 5 gets discarded and 14 stays similarly if you add 6 to this 0 then you are going to get 6 only you divide it by 3 you get the remainder as 0 you try to populate 6 in this cell of slot 0 9 is already sitting over here 6 compared against 9 is much greater so 9 stays 6 gets discarded all right now coming back to this iteration only we add 1 to this 14 we are going to get 15 when 15 is divided by 3 the remainder comes out as 0 so we populate 15 in this cell all right now after the values are populated in each of these slots the algorithm is going to do one final thing for every iteration it's going to compare the values in each of these slots against the value in the same slot of the previous iteration and the greater value is going to get the priority so 15 will be compared against 9 since 15 is greater hence 15 stays 10 will be compared against 0 since 10 is greater hence 10 stays and 0 will be compared against 14 since 14 is much greater hence 0 gets replaced by 40. understand the basic idea guys we are capturing the greatest sums which give remainders 0 1 and 2 for every iteration we now have 8 as the next integer we add 8 to 15 we get 23 that goes to slot with remainder 2 all right now we add 8 to 10 that gives us 18 it is divisible by 3 completely divisible by 3 so 18 goes to the slot of remainder 0 now we are going to add 8 to 14 that is going to give us 22 we put it in the slot with a remainder 1 22 divided by 3 gives us the remainder 1 hence 22 goes in this slot of remainder 1. now these cells are populated the algorithm is going to compare this 18 against this 15 18 is greater so 18 stays it's going to compare this value of slot 1 with the previous value in the same slot 1 22 is greater than 10 so 22 stays and finally it is going to compare 23 against 14 23 is also greater than 14 so 23 stays remember why we compare the value calculated in a particular slot with the value in the same slot from the previous iteration because we are looking for the greatest sum for each of these slots if the algorithm hadn't done so we wouldn't have got 9 over here or 14 over here oh goodness me the matrix is full so this value the value in the final column in the slot of remainder 0 is the answer so 18 is the maximum possible sum from this array of integers that is completely divisible by three if you want to check out the java code for this dynamic programming problem then you can find it in my github repository you can find the link to it in the description box also check out my playlist of dynamic programming problems where i have explained the approach to getting to the solution of hundreds of problems that can be solved using dynamic programming with this we have come to the end of this video i hope you enjoyed learning to solve this problem of greatest sum divisible by 3 using dynamic programming if you have any doubts related to this problem please let me know in the comment section i'll try my best to solve them i look forward to helping you with programming and algorithms and only for this video goodbye and take very good care of yourself | Greatest Sum Divisible by Three | online-majority-element-in-subarray | Given an integer array `nums`, return _the **maximum possible sum** of elements of the array such that it is divisible by three_.
**Example 1:**
**Input:** nums = \[3,6,5,1,8\]
**Output:** 18
**Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
**Example 2:**
**Input:** nums = \[4\]
**Output:** 0
**Explanation:** Since 4 is not divisible by 3, do not pick any number.
**Example 3:**
**Input:** nums = \[1,2,3,4,4\]
**Output:** 12
**Explanation:** Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
**Constraints:**
* `1 <= nums.length <= 4 * 104`
* `1 <= nums[i] <= 104` | What's special about a majority element ? A majority element appears more than half the length of the array number of times. If we tried a random index of the array, what's the probability that this index has a majority element ? It's more than 50% if that array has a majority element. Try a random index for a proper number of times so that the probability of not finding the answer tends to zero. | Array,Binary Search,Design,Binary Indexed Tree,Segment Tree | Hard | null |
1,684 | welcome ladies and gentlemen for another exercise on leapcoat today it's about the gold passer interpretation so i guess it's coming from like a football scenario so basically from this exercise if you're given a command and you see g in that command you interpret it as g if you see the open and closing parenthesis with nothing inside interpret it as um oh and if you see the open and closing parameter with a l inside we interpret as just a l this is an example here g is g up and closes o and uh up on close to a l is here it extrapolates here like you can see go oh otherwise so we have to look through this command and break it down by uh letter or parentheses symbols so um we're gonna draw the while loop you will see why so going to have my looping variable i as usual zero and i'm going to have a variable that is going to have the answer at the end in the form of an array i'm going to construct um this as an array okay so let's start the loop so i is going to loop until the end of the command so while looping if we see um i to be equal to g then inside our answer i'm going to push the character g inside so as i'm looping over i'm going to if i detect g i'm going to put g inside my array so i'll be going ahead and constructing that way and i is going to increment to one because when i see g i interpret it then i go to the next character i'm going to meet this upon braces for this example too for example and then the second scenario is if we meet the character open braces now we have two scenarios when we meet open brace it can either be the open close with nothing inside or with al inside so we evaluate the second character so if the second character closer i plus one is um different from the closing parenthesis it means we add the el so inside answer are going to push here okay yes it means uh the closing uh it means the next character is actually the closing parentheses so we're going to push um oh at the end we have our answer interpreted oops we have to debate we have some errors oh we're not done um also let's run it again so that you can see so you can see fatal error call and we try last allocation for javascript heap out of memory a part of memory usually when you overload the memory like something running without stopping here because we haven't um control the variable that permits to get out of the while which is the eye at the second if so let's come back here if we meet um the closing if we made the opening parenthesis let's start from that and the next is not the closing it means we are at this particular scenario open air and close so if that's the case once we interpret the whole of the string which occupies four characters we have to just keep and go to the next the next possible letter for the goal so i is going to skip by four and for this one is going to skip by two because we have uh open and closing parenthesis which is two characters so when we're done interpreting we skip two i think that should be the reason since this wasn't controlled we have that hip error below so let's display again our answer we get something like this is the array i was constructing so now we just have to join everything together as a string and return so we're going to return inside the joint right good to go that's on me so this is it and i'll be glad to have in the comments any other procedures that can be used to optimize this but for now this is what i have for you and see you on another | Count the Number of Consistent Strings | find-latest-group-of-size-m | You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`.
Return _the number of **consistent** strings in the array_ `words`.
**Example 1:**
**Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\]
**Output:** 2
**Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'.
**Example 2:**
**Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\]
**Output:** 7
**Explanation:** All strings are consistent.
**Example 3:**
**Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\]
**Output:** 4
**Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent.
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= allowed.length <= 26`
* `1 <= words[i].length <= 10`
* The characters in `allowed` are **distinct**.
* `words[i]` and `allowed` contain only lowercase English letters. | Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map. | Array,Binary Search,Simulation | Medium | null |
1,266 | Scientist Hi Guys How Are You I Hope For Doing Good So This Is The New Yorker Face Which Has Been Created Athlete Code And This Is The White Bun I Like It Record You Very Colorful And Share Feedback Option Dowry Want To The Receiver Want To Go To attend the festival is the president where we are used to a guy but that's the question in the series so let's all group have a look I hope you are in every sphere of these just like comment and share and also tummy rest house farewell improve my teaching skills that you can learn a very well what I chair here let me first give the same question which we use to do you Ho, on the first day of my husband, Ram match, a big mock test has been done that I don't know what is the problem, how do you have changed, December gas, Vrinda's think, that the difficulty level status of the foreign country behaved, back to the question Some of the people are in the dark but I can't Are on sea and download dead skin I gave your show question which they have used to beach is bank intersection found so clearly behaved in the box is raw or betting suggestion it to festival solve remove time of these to will do minimum time distinguishing And point is this bill does a specific day every day time electricity bill question and win you to give more time on difficult strict military day for something important question of vegetable soup of but today we are so glad to have too many and points B Happy Calculator So Minimum Time Incident Withdrawal Point Okay Researcher Possible Direction Where They Can Do We Can Move Vertically Upward Vikram We Khali Urgently We Can Move Vikram That Recent And Vinegar Diagnosis For Ki Bihar To Visit Wala Point Se Motor Show Edison So It's Clear That we can e do not have heart this browser that from which modal sudhijano setting show sweeties dhawan weight 600 this study from off to kanpur distance from three list reward for this is to do not welcome to take medicine - Ramoji not welcome to take medicine - Ramoji not welcome to take medicine - Ramoji Rao and immediately the Disputed Area Hall Problem This Android F1 Price 122 Bank Video Pizza Very Easy Fashion Ishq Very Easy To Send But You Have Analyzed This Totke Best Hot And Digression The First Analyst Phance 1000 Like It Is - The First Analyst Phance 1000 Like It Is - The First Analyst Phance 1000 Like It Is - Repair Zero And His Team For It Give Information So what is the distance and what is the time quite to start from here and tourist here it is the difference between the spot and the college and pithadheeshwar coordinator and security convention from the strong list to the straight line a that and you Can Also Find This Eminem The Distance Between Is The Time You Can See A Time When E To Take Off Baroda Sugar Two Table Spoon Profile Skin Disease And Like This Is The Third Reich Only And Only ₹100 Distance And Thee - Off - 150 416 ₹100 Distance And Thee - Off - 150 416 ₹100 Distance And Thee - Off - 150 416 We can find a distance that apes loot of My Son Overload Straight Line Sona You Can Find It In The Distance Between A Man And Every Time Required To Distance Point Sona Destabilizes The It's Clear Net Previous - Great Britain Simply Find The Previous - Great Britain Simply Find The Previous - Great Britain Simply Find The Different But Effective Work Ban Hair Serum Officer To How Can Find A Distance Deal Time Required In Through 30 Minutes Hours So Executive Apply This Formula One Allowed Obscene Man To But They Need To Request The Minister But Top 3 Tomorrow Morning You Can See But Is You Who Is This Point To Make From This Point Is On That Auspicious 123 Means It Means The Weather It Is It A It Is The Governor And Ifik Udyan A And Distances Same 2009 Back And Subscribe Now Want The Time Which Needs Page if you liked The Video then subscribe Are You Can Take A Few Years 2007 Strong Good Earnings improved distance between us the real estate needle reminder given this phone lock teacher C but if you who is this point and after 10 minutes al hits of what it's 087 Madheshi subscribe 0 I myself so PM that this 390 ironing suit what you can From I One Value 0a Entry Work Start New Baby 2006 - I Will Give Thee Its Immediate Baby 2006 - I Will Give Thee Its Immediate Baby 2006 - I Will Give Thee Its Immediate Speed Come Acts Of This Too Difficult Speed Come Acts Of This Too Difficult Speed Come Acts Of This Too Difficult Verification President Acid Attack In The Weather You Are Taking Porn And Transport More Video subscribe Video give Vidash subscribe Video then subscribe to the Page if you liked The Video then subscribe to Ya Bhai Vishesh Hu Is This And This Is A Mess This Ki Inko Diwasiya Share It Will Take Two To Effects From Na Sohe Gal 335 2323 Shobhan This Confirm Dowry Suppressed Person Subscribe To Main Surat Total Score This is beginning is effective from hair soft point is speed come to English which aromatic medicines from three and its to switch total 786 internet that this to-do list you loot and oils in front that this to-do list you loot and oils in front that this to-do list you loot and oils in front of those came the points minus one and here On return after see you can see the results 204 net result is equal to result plus and water max of you drink imt points of i sugiyama to katni beawar to like welcome to 100 200 to zf the voice of ibn18 electronic machine and sudesh Dhawan Thing IS Copy The Same Thing 220 Vikram Band Qualities IS Quite A Who Is The Results Aapko Mu Jo Person Desh Loot Hui Ki Is Result Ki And Ki Is Results Icon Zero Payo Dhan Correctly Should Aim To Increase The IS Well So Let's Constitution Bench Straight Line Network Fine But That Test This Begum Acts Of Two The George Media Exposed In A Different In Accident In Give Me The Character Also Press Surya Hai Take Care Very Here Text Is That Tax Collection Difference And Active Okay Solid Have Been Success Fully Hatable And Tours Elections Will Meet In A Cn You Prepare Things Should Decide Where Will Also Give Description In The Eye Button So You Can Check Out From Rate Increase Next Video Bye-Bye Take Care And Subscribe Please Mez Kar Bye-Bye Take Care And Subscribe Please Mez Kar Bye-Bye Take Care And Subscribe Please Mez Kar Do | Minimum Time Visiting All Points | minimum-time-visiting-all-points | On a 2D plane, there are `n` points with integer coordinates `points[i] = [xi, yi]`. Return _the **minimum time** in seconds to visit all the points in the order given by_ `points`.
You can move according to these rules:
* In `1` second, you can either:
* move vertically by one unit,
* move horizontally by one unit, or
* move diagonally `sqrt(2)` units (in other words, move one unit vertically then one unit horizontally in `1` second).
* You have to visit the points in the same order as they appear in the array.
* You are allowed to pass through points that appear later in the order, but these do not count as visits.
**Example 1:**
**Input:** points = \[\[1,1\],\[3,4\],\[-1,0\]\]
**Output:** 7
**Explanation:** One optimal path is **\[1,1\]** -> \[2,2\] -> \[3,3\] -> **\[3,4\]** \-> \[2,3\] -> \[1,2\] -> \[0,1\] -> **\[-1,0\]**
Time from \[1,1\] to \[3,4\] = 3 seconds
Time from \[3,4\] to \[-1,0\] = 4 seconds
Total time = 7 seconds
**Example 2:**
**Input:** points = \[\[3,2\],\[-2,2\]\]
**Output:** 5
**Constraints:**
* `points.length == n`
* `1 <= n <= 100`
* `points[i].length == 2`
* `-1000 <= points[i][0], points[i][1] <= 1000` | null | null | Easy | null |
787 | good evening everyone today we are going to do the daily record challenge of 26 January 2023 that is 787 question number cheapest flight within K stop so the question is saying that there are ncts which are connected by some number of flights and we are given an array of flights and there we are given the starting index the ending index and the price to reach that index okay and we are also given three integer Source destination and K and we have to return the cheapest price from source to distance with at most K stops and if there is no route possible we will return -1 okay so this is what our return -1 okay so this is what our return -1 okay so this is what our question is saying we have to return the cheapest flight from source to destination with at most K steps so let's move on to the example and see how it is working so in the first example what we are given flights from 0 to 1 at the cost of 100 flight from one to two at the cost of 100 right from 2 to 0 at the cost of 100 and flight from one to three at the cost of 69 flight from two to three at the cost of 200. what is our source is this index zero index and from Source we have to reach destination that is 3 in this case and what is the value of K in this case it is 1 so that means we can have at most one step that means we can have at most one stop okay so what are the possible ways to reach here one is from 0 to 1 that is 100 then 1 to 2 that is another hundred plus hundred then two to three that is 200 so how much it is around 400 rupees 400 currency whatever you are thinking but if we move from 0 to 1 that is hundred plus one two three that is 600 so total is 700. so which is cheapest among these 400 but it will not be the answer why because we have to also consider the number of stops when we move from 0 1 2 then 3 then we are having one and two stops but when we move from 0 1 then 3 then we are only having one stop that is one so our answer would be 700 let's take another example in this question we are given that we have at most one stop and our source is zero destination is 2. this is our destination and this is our source go from source to destination we have two ways one is one two that is 500. and it is without any stop another is zero to two that is 100 plus 100 that is 200. so which one of them is cheaper this one is cheaper so we will go with this step yes or no but if you consider another example in this example you are given 0 stops that means you have to find a direct way to this from source to destination and that is only possible by 500 so in this case 500 would be answered not 200 why not 200 because we are having one stop and no stops are allowed in this case so this is you have to do so to do this question I will give you a hint you try it and then come back to the video the hint is you have to apply BFS breath versus because you have to consider every possible ways and you have to find the cheapest among them and for finding the cheapest you will make a distance array so please try this on your own and then come back to the video so I hope you tried the question on your own so now moving on let me tell you how to do this question so to do this question you will make a queue for a BFS and you will also make a distance array in which you will store the distances the minimum distances and when you are you have got all the minimum distances you will simply return the minimum distance of source which was there okay uh okay F4 so here what you will do you will start with the source index source is here 0 in the queue this is your queue and this is your distance array so inside the queue what you will push you will not only push the element also you will push the distance so the distance of Q from its source is 0 comma 0. and initially you will initialize the distance array with infinite values 4 only 0 1 2 3 this is nothing you will initialize them with infinite value and when what is the process of BFS you will pop it and you will update it what is minimum of infinite and 0 it is zero so here it will be 0 and after when you have popped it you will see what are the possible waste from zero it is this way yes or no that is 1 comma 100 so to reach 1 we are having 100 unit of time so we will update it here now after this we will compare which is smaller from 100 and infinite it is 100 so we will update our infinite 200 and then we will pop it and after popping it we have two choices first is 2 comma 100 another is 3 comma 600. so then we will again compare and again update it and then again pop and we will do this and whenever we are popping after that we will also need a variable steps why steps variable this will count our total number of steps and it should always be less than K according to our question so we do not exceed number of steps okay and when next time you will push the elements you will push the next method so when you upgrade it to 600 you will see this but next time when you are pushing the next element where that is again you are getting 3 for 200 so this time you will push this element as well and update it to 200 okay and you are pushing the new way here as well and at that time you will notice that the case size is exceeded so you will stop our BFS okay and we will not continue our BFS when we are exceeding our case size so let's change this in the code and we will understand it better so to brief you with the web or approach we had to make a queue in which we have to pass a pair of vertices and the cost and after we are done with making the cube we also need a distance array which will be storing our minimum distances in K steps that is all you have to do so let's move on to the coding part let me just zoom it for you so the coding part is very simple we will start with creating a vector of what Vector distance which will be initialized with into max value that is approximately infinite in the worst case okay and we also need to create our adjacency list with appear yes or no why appear because we need to store the vertices and the cost both we have to store so we will initialize our adjacency list like this that is pair of end comma end adjacency list so this is our address incidence and to convert this adjacency list and using these points we will make a graph how we do that we run a loop for vector and up to where flights is our array then what we will do we will initialize in Q is equal to Vector 0 that means starting point then end V is equal to vex 1. that is the destination now after that you will initialize int cost is equal to back 3 that is the cost to travel there and as it is a directed graph you will also need to push the relation adjoint U push back you will push the pair B comma cost you are showing the vertices and the cost that is what I told you in the examples and after that you simply have to apply the BFS for BFS you need to create a queue usually you create a q normal but in this case you need to create a pair of q y pair of Q because you are storing two values the vertices and cost and this in this question you will not create a visited array because there are multiple ways possible to visit a single array and you are comparing all of them to get the cheapest so you will not create a visited array in this case so now what you have to do you have created a cube pair vector and you will push the source node here and the distance from Source will be zero so you will make the distance of source to zero and then you will initialize our steps which will count the number of K steps possible that is number of stops now after that you simply write the BFS code what is it while Q is empty and what I told you we will also make sure that steps is less than equal to K we should not exceed our steps and then we will initialize n10 is equal to Q dot size while and negative and we will decrement and that is we are popping element from our queue how we will pop elements we will initialize the front element as the first and we will initialize our distance to the second that is the cost distance or cost whatever you want to say let's denote it as D it is our second in the queue and then we will pop our Q after popping the cube we will start iterating in another loop for we generally do for end and V2 at joint U but in this case we are having pair so we will iterate in pair end comma it so data type will be Parent Command and let's change it to P for better understanding and now when we are iterating to our it's all adjacent what we will do we will initialize our B to P DOT first what does it indicate the next iteration the next one and we also need to get the cost will be P dot second that's what you have to do and if the distance of V is greater than D Plus cost that is the distance is greater then we are updating it to cheaper distance that is what we told you so we will update it to cheaper distance B is equal to D Plus cost and when you are done with this you will push it in the queue to check its corresponding paths the New Path which it is providing we will push V comma distance B because it is updated and when you are done with this Loop and when you are starting again the BFS call we will increment our steps that way you can exit the final BFS when it exceeds the amount of K possible so this is all you have to do and when you are done with the DFS you will check back there in the distance array the source is still index if it is still into max that means we did not find any way to reach it so we will return -1 -1 -1 and if it is not in into max we will return our distance of destination DST it should also be destination not source I hope it is clear let's just run it and check whether it is working or not um expected okay we missed this now it should work uh it is distance P dot fast there should not be some columns brackets uh integer overflow we have written it zero one two zero base indexing no not one two three it should work now yeah it is working so this is all you have to do let's just submit it so yeah it is accepted so to briefly with the overall approach we simply had to apply the BFS we need to create a distance array to store the distances and while making the adjacency list we was passing the vertices along with the cost so we can compare the cost and get the minimum so the time complexity in this case will be o e into n and also we are running a loop for this so it will be what o e into n plus o n so that would be our time complexity ultimately it is O A into n and space complexity will also be the same so if you have any other doubt please let me know in the comment section please try to do this question on your own thank you so much for watching please like share and subscribe bye | Cheapest Flights Within K Stops | sliding-puzzle | There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`.
You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`.
**Example 1:**
**Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1
**Output:** 700
**Explanation:**
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops.
**Example 2:**
**Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1
**Output:** 200
**Explanation:**
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
**Example 3:**
**Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0
**Output:** 500
**Explanation:**
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
**Constraints:**
* `1 <= n <= 100`
* `0 <= flights.length <= (n * (n - 1) / 2)`
* `flights[i].length == 3`
* `0 <= fromi, toi < n`
* `fromi != toi`
* `1 <= pricei <= 104`
* There will not be any multiple flights between two cities.
* `0 <= src, dst, k < n`
* `src != dst` | Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move. | Array,Breadth-First Search,Matrix | Hard | null |
48 | foreign problem which is to rotate an image here a two-dimensional array or a matrix is a two-dimensional array or a matrix is a two-dimensional array or a matrix is referred as a image from the problem we can see that the size of the Matrix is given as n by n which means it is a square Matrix and our task is to rotate the square Matrix with an angle of 90 degrees in clockwise Direction if you assume this circle has a clock and the direction shown by the screen color is the clockwise Direction to understand it better let's see with an example let this blue color Matrix with the input Matrix and we are going to rotate this input Matrix with an angle of 90 degrees in clockwise direction that means we are going to rotate like this that means the position of 7 here will be finally settled down at here so the output Matrix will be something like this 7 and 4 1 8 5 2 9 6 3. till now I think we are clear with the problem and let's see how we can solo this we are going to solve this problem by performing two simple steps first step is to perform a transpose to the given Matrix transpose of a matrix is nothing but interchanging of its rows into columns or it columns into rows that means this is a given Matrix and we apply transpose to the given matrix by interchanging its column to the row that means the first column in the given Matrix will be the first row in the transpose Matrix that means one four and seven and the second column in the given Matrix will be the second row in the transpose Matrix that means 2 5 and 8. similarly the Third six and nine and now we are going to reverse this transposite Matrix in order to get the 90 degrees rotated Matrix the reverse of this transposite Matrix will be our required Matrix that means let's fill this transposing Matrix which is 1 4 7 2 5 8 3 6 9. right so this transposite Matrix should be reverse that means the last column will be transferred to First and the First Column will be transferred to last that means the result Matrix will be 7 four and one and it is eight five and two and it is 9 6 and 3. Now using this logic try to write some code on your own and then come back to check the solution this is the implementation of the logic we discussed here we are taking two sets of nested for loops right and in which one nested for Loop is going to use to find out the transpose of the given Matrix and the other nested for Loop is used to get the reverse of the given transposite Matrix to understand how the transpose of Matrix is happening let's check for the case of I is equal to 0. if I is equal to 0 then J is equal to 0 plus 1 that means J is equal to 1. and the temporary variable which stores the value of Matrix of 0 and 1 which is 2. the value inside the temp will be initially and then The Matrix I of J that means the Matrix 0 1 that means that position of 2 will be swapped with the position of j i that means 1 0. that means foreign of I and J will be equal to the number 4. and The Matrix of j i that means will be equal to the value of term that means it is 2. and hence the positions of 0 1 and 1 0 are swapped similarly all the elements all the other elements are also transposed and finally we get the transpose of the given matrix by the end of this for Loop now we are going to reverse the columns in The transposite Matrix when I is equal to 0 the First Column elements are swapped with the last column elements that means the XYZ values are swapped with the last column elements of this three by three Matrix and when I is equal to 1 the First Column the second column elements are swapped with the N minus front column elements and this process will be repeated till I is less than I is equal to Matrix dot length by 2. that's it and we'll after the end of this for Loop we'll get the reverse of the transposite Matrix which is our desired rotated image of the given Matrix let's see if this is correct | 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 |
917 | Hello whom I am Amrita welcome back to our channel technologies so this is lead code series in which will be solving lead code problems one by one if you also wish to solve it jump problems then you can join us and subscribe to our channel and also press D Bell Icon You Get The Notification So Nine Let's Move Ahead With Today's Problem Today C Will Be Solving Problem Number 917 Date Is Reverse Only Letter So Let's Get Started Let's First Understand D Problem Given An String S Reverse D String According To The Following Rules So Basically C Need You Reverse D String But C Need You Follow D Rules So What Are D Rules Rule Number Van Date Is All The Characters Date Are Not English Letters Remain In D Se Position And All D English Letter Should Be Reverse So Basically C Just Need You reverse the English letters and other respect characters date is not an English letter it should be remaining in D se position in D example you can see R string is now hyphenated CD so the and C is reverse de hyphen remains R D se position given B And A Correct Nine Let's Understand Ho C Are Going To Solve This Problem So Let's Safe C Have You Reverse Only Simple String Let's C Have All The English Letters Ho Do C Swap It What Is D Reverse Swing Date Would B C Be A Correct So D Last Letter Becomes a First and D First Letter Becomes D Last Letter Basically C Keeps Wepping D Characters First with D Last Second One with D Second Last and If There is a Third One Date Would Be with D Third Last Letter End Till C Reach D Middle Position correct but nine in this case let's say if c have a string like this now = c question mark the end hyphen now = c question mark the end hyphen now = c question mark the end hyphen tell characters which are the English letters correct so for date what are you going to do see will take tu pointers where would be start Pointer And Andar Van Wood B Pointer End And Let's Break It In D Steps So What Would Be D Step Number Van Science C Have You S Only D English Letters Will Be Checking Weather Both Are English Letters Okay So Let's Say If Start It Not An English letter OK if character comes from start position and just writing it start tu represents if character comes from start position it is not an English letter give what do see need do see don't need do anything see just have to move you next Character Right Give C Have You Just Increment D Start Index Too Move To D Next Character Similarly Next Will Be Checking If Character Ate D End Position Is Not A Letter Give Also C Have You Just Move To D Next Character Date Mains Dicrement The End Index And if both are letters from this let give that many characters what do you need you just swap d letters and after swapping what do you need do you move d next character from both d sides date mains increment d starting For example firstly you are checking if start is not a letter but start is a letter so this becomes false give check and this is not a letter yes date is true so move on to d next character so date mens nine this is start and Next And This Becomes Your End Index Correct So This Will Be Taste So Date Mens Di Is Your Ate First Position And Ate D Second Last Position Because Hiffin Remand D Se Science It Is Not An English Letter C Just Move To D Next Character Now You Want Tu de next character so date mains de will be swapped correct so when de will be swapped come your second position and be come this position this remains come de se position correct nine move on tu de middle van det mens you increment your start And Next Both Start And Are Not Letters So Date Mens It Remand D Say So This Would Be Your Reverse String Correct Reverse String So This Is Ho You Need To Solve This Problem Now Let's Try D Solution For It So This Is Un Class Date Is Reverse only letters nine let's try d method date would be public static it is going to be written d string so date mains it would be string reverse only letters and what would be the input would be your string so nine Firstly what do you need to do Si need tu take tu pointers van not b your start in next date would be zero start less den and what would be the first step they need to check wether your character at the start index it is not a letter den c have tu move tu d Next Character So Date Mains Increment Your Start In Dex Just Check Your Character And The End Index Date Is Not A Letter Then If You Have To Move To D Next Character So Date Mains Decrement Your End Index And If Both Are Letters Then What Do You Need To Do C need tu swap both d characters and move tu d next character from both d sides ho do c rapid let's take a temporary variable ch a start index and chs start index is equals tu ch at chs and equals tu temporary if you do n't know Ho to swap d's letters and other numbers c have a separate video on date I will mention d link in d description box you can check it out and then after stopping move to d next character from both d side date mains increment your start index and decrement Your end give index correct so come the end see can say write new string ch it tu de string because see need you write de reverse string let's go back tu me function end let's take de say in footage now hiffin cd let's write handyman app see need You solved this problem thank you for watching | Reverse Only Letters | boats-to-save-people | Given a string `s`, reverse the string according to the following rules:
* All the characters that are not English letters remain in the same position.
* All the English letters (lowercase or uppercase) should be reversed.
Return `s` _after reversing it_.
**Example 1:**
**Input:** s = "ab-cd"
**Output:** "dc-ba"
**Example 2:**
**Input:** s = "a-bC-dEf-ghIj"
**Output:** "j-Ih-gfE-dCba"
**Example 3:**
**Input:** s = "Test1ng-Leet=code-Q!"
**Output:** "Qedo1ct-eeLg=ntse-T!"
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of characters with ASCII values in the range `[33, 122]`.
* `s` does not contain `'\ "'` or `'\\'`. | null | Array,Two Pointers,Greedy,Sorting | Medium | null |
452 | hello everyone welcome to clashing coder so in this video we will see the question 452 that is minimum number of arrows to burst balloons so it is a medium level question and it is also sometimes asked in interviews also so let's see the problem statement there are some spherical balloons spread in two dimensional space or 2d space you can say where x and y coordinates are there so for each well whom provided input is the start and end coordinates of the horizontal diameter that's mean that means that you can see this line so this line is actually horizontal you can see so its diameter is given the diameter or the width of the balloon is given since its horizontal y coordinates does not matter so that means we will not take the y coordinates into consideration because all the balloons will lie into like y is equal to 0 for them so x will only change so hence the x coordinates of the start and the end of the diameter surface so the start is always smaller than the end so yes it will be true because the starting point will be always smaller than the end then only it will form the diameter otherwise it will be uh different so an arrow can be shot up exactly vertically from different points along the x-axis from different points along the x-axis from different points along the x-axis so it means that exactly vertically because we are not considering the y axis so we can uh assume that the arrow is also fired or like i triggered from the same vertical position that is y is equal to zero you can suppose that a balloon with x start and x and burst by an arrow short at x if x start is less than equal to x and that means that our x that we are shooting so we are not considering the y axis so we are only considering the x axis so if it in uh like uh if like that makes me new actually so in this you can see in this i will explain you so this is the diameter of a balloon that we are given and we have to burst it using the arrow so when we fire a arrow so this is the start x start sorry for the handwriting because i'm using the mouse so you can please uh you can copy that so you can see this other starting and end point so our arrow should only be uh arrow can only burst the balloon if it passes between these it should be lying between these okay the x should be lying between these it cannot lie uh here because if the arrow is fired from here so it will not burst the boom so that means these are the like constraints that x should always lie between x start and accent that means the diameter or the width of the balloon there is no limit to the number of arrows that can be shot an arrow once shot keeps traveling up infinitely so that means that if arrow like burst one balloon okay from here then it may also like not stop and it will also burst the next boom if it comes in its way so that is what it's trying to say so given an array uh points where the points i is equal to points start and end so that means we are given the element as pair of values start and end return the minimum number of arrows that must be short to the to burst all the balloons so actually if you see the problem statement it is kind of similar to merge intervals so actually if you haven't solved that problem in lead only it is a problem so i will provide you the link in the description or in the i button also so you should try to solve the question and i've posted a video in that also you should try to understand the solution from there if you are not able to solve so that will like save a lot of time and you will end up having a solution for this problem also this is almost similar to that problem so the concept that we are going to use here will be similar to that merge intervals so i hope you should see that okay so for these are the examples that are given so actually uh you can see these are the base cases if you want to like first of all see the base cases so if you are given one element only or one this input only so that means you have only one rune so you need one arrow only because you need at least one arrow to burst balloon zone so at least one so you can simply return one if element is one if there is no element only no balloons that means you rotate an arrow you can return zero so these are some constraint also you can see points length will lie between zero to ten to square four and points length that means the pair or you can say start or end where it is of length two every element and these are just some constraint for x so it will lie between minus 2 to power 31 to 2 power 31 minus 1 okay so these are some constraints so let's see the example so actually this is the example that we're given you can see this is the first example that we are given and here the output is two and let's see how that output is two actually as i told you let me draw this line as i told you we are not considering any vertical axis so we are only considering if the blues is here so it is actually like this the balloon is like this it is not having any vertical or vertical coordinates it is only having horizontal coordinates that are start and the end point so let's see how we can solve this so if you see this spoiler point so then uh for example you can see the minimum value here is 1 so the line is 1 and the maximum is 16 so this will be 16 if you see this balloon so it is of radius uh you can see six and uh diameter six and it is starting from 10 so exactly 16 is here so you can suppose n is here so 10 and it is going to okay sorry for the writing actually it is going till six so the 16 so that means the plume is off with this you can see this is the fifth of balloon so that means we need one arrow to burst it okay we need one arrow to burst it now if you see this two and eight so this is another balloon so it is two and eight so two will be somewhere here and it will be the system so it will be you can suppose here so now you can see these balloons are not overlapping so as it is written that arrow will travel infinitely after bursting the balloon also so if one balloon lies here and this one is here arrow passes through the race so it is merging or you can see overlapping this is overlapping with this so arrow will also burst this balloon but in this case you can see this balloon is not overlapping with this balloon so we require two arrows you can see if we was this there is no chance that this will uh this building also will burst so you have to require you will require two arrows you can see this will require uh the different arrow now if you see one and six so one way one is here six will be eight is around here so six will be around here so i'm just supposing so okay this will be the another one you can see so now this is the first balloon this one down one here okay and this is the second balloon now if you see arrow passes from this point so it will end up bursting the both the balloons so we require two arrows for now also this is for this balloon and this arrow will burst two balloons off you see this seven and twelve so seven will be around here eight is here so seven is here six is this okay seven and twelve two so twelve will be around here so now if you see seven or twelve so it can be busted by po uh by this room you can see this because here if you try to uh use this arrow okay so it will not burst this balloon so to burst this balloon it will we will have to pass a point between this okay this arrow would it will be like let me change this color so one arrow will be passing from here and one arrow you can see these are overlapping okay these balloons are overlapping so if you pass one arrow from here so you will require at low at me at least or you can say at max two arrows only to burst all the balloons so this is what our problem is trying to say so we have to output the minimum number of arrows required to burst all the balloons and we have to actually merge the intervals or you can say these are intervals uh i will recommend you to watch the video that i will show you in the uh the info button you can check it from there afterwards uh before watching this video actually so you can see we have to merge these intervals if you see we can let me erase this so we are given this okay so we are actually trying to merge these sequences if this is 10 and 16 okay 10 and 16 is there now is there any sequence which overlaps with 10 and 16 that means a number becoming between 10 and 16 or this line comes between some number you can see here so you can see 10 okay 10 and 16 is here and 7 and 12 is coming between this 10 and 6 so that means these this is one balloon okay this is one room and this is second balloon so you can see they're overlapping actually so an arrow can burst both of them if it passes between this seven and twelve so it will end up bursting 10 and 16 also so we have to require we need to output the minimum number of arrows required using this technique so let's see the algorithm so actually it is quite similar to the merge intervals only so you can see first we will initialize the count as one because at least we require one arrow if we will check the base conditions if there is only one of the balloon then we can simply turn one either if there is no balloons we can return zero otherwise if it is not the base condition end of the base conditions we will have to initialize the count as one because we at least require one arrow so we have to start with the one so let me write it so our count will be at least one okay so it will be one then we have to initialize a previous variable also let's see what we will do with that but actually if you see in this okay so for merging the intervals actually we cannot merge the intervals till we sort them so we have to sort the array also because we have to use the greedy approach in the merge intervals also we sorted the array so in this we have to sort the array to merge the intervals we cannot merge the intervals without sorting the array so it is actually a greedy approach so you can see in this how we can merge so we will merge using the ending value or you can say the end point of the end point or and coordinate of the balloon or diameter so you can see we will merge or we can we will sort the array using these elements so let's sort them so you can see here one two three four and four five and two three so you can see one two so two is smaller out of all so we will uh first the element will coming is one and two now again now see which is smallest out of this four five and three so this three is smaller so here it will come two and three okay now again you can see the two elements are only left so this will be smaller three and four so we'll write simply three and four so the left over element will be four and five so you can see we have sorted our array using a compare function you can say we will use a compare function and sort it according to the second value in this element or this pair so this is what we are doing sort the first we have to initialize these variables and variables that we will be using then we have to sort the array then only we will be able to merge them so now how we can merge them actually we will first of all we will need account as one so we have initialized account as well now we will start from the second element uh in the area or you can say first element this is the zeroth element so we will start from the second element this is where from where we will start and we will set our x or you can see this previous value of t okay i have written previous okay so we'll set the previous value as this value that is two so uh actually okay so i have not written it so previous value will be actually array of okay 0 and 1 okay this will be what we have to uh initialize this previously with so it will be initialized with actually x is two for this or previous is two so now we will start our loop from this point okay you can see i is starting from n i one until uh it is running till n so now if you see our previous value is this it is not x actually so sorry for that so actually it is our previous value so now if we are at this element and you will check this condition if array of i zero array of i is this and zero value is this 2 so it will end up having value 2 so you can see here it will be giving 2 and 2 is less than equal to previous value that we were having 2 so you can see it is actually equal so that means we will simply continue and don't like skip the steps so we will simply continue and skip these steps so that means that we have found a pair or pair of numbers which are balloons which are actually overlapping if you see this two and two so if we draw this in line in this actually if we draw this line so one is here okay two is here and three is here so this is our one balloon and sorry this is our one balloon actually starting off with two and this is our second balloon now if we pass error through this two then we will end up bursting the both columns so that means they are overlapping so we can simply skip this loop and our count variable will actually return the number of arrows that we require so our count will not increment it is still one because we can burst these two balloons by one you only one arrow only so that means we are skipping this step so now i will come here so i will come here now our previous is still two now we will check for this i is this okay i is two and for i of two we will check for the first element is 3 so now if you check 2 okay this actually value will be 3 first value will be 3 okay 3 is less than this previous value is 2 you can see 2 so 3 is less than equal to 2 so this condition is not true so that means we will have to skip this if condition and that means this element or this balloon these values are not overlapping so that means we require a more arrow or require another arrow because if you see okay so now if you see this three so okay uh let me draw again one right so excuse me one and two and three and four so one balloon is over this point one and two another point a balloon is over this point two and three and the last balloon sorry for the drawing it's actually this so this is the last blue so if you see actually uh let me check here so yes so if you see now this arrow that we will be requiring will be only so where would we so you can see we will skip this condition so actually we will have to increment our count okay this three is less than the previous so that is not true we will not uh end up into this condition and we will skip it so if we skip it so for count will become plus so the count was one so it will now become two now you can see a count has become two another previous value will update to the next value that we have so actually it will be uh i is at this okay i is at this and we will update is to four so it will be updated to four now you can see it is updated to 4. now if you see this 4 now we will increment the i to the next point so it will be here let me draw it carefully so yeah so i will be here so i is here let me erase this all so now you can understand so yeah so now when i is here our previous value is 4 and if you see this 4 is equal to this 4 okay if you in this condition you can see array of i 0 is 4 and our previous value is also 4 is less than equal to 4 this condition will be true actually so we will simply continue because this four and three these are overlapping actually three four and five these are overlapping but in this case i which i was telling you let me explain you further so if you see in this point if you see we are if we pass an arrow from this point yeah these are the merging balloons okay one two that we were having you can see one two and two three let me draw it here only one okay two and three so now you can see this balloon these two balloons can be bursted by only one arrow if you pass it from the two point okay two in uh coordinate but if you try to pass it from this also this is our next one so it will be three and four if you see we if we pass uh if we this is also merging actually this three and four but you cannot pass an arrow from this three and four if you try to pass the arrow from three and four that you won't be able to burst the balloon at one and two so that means you can at least at most merge two will not only over here so you will require one arrow extra for this if one arrow will be required to burst one and two or three balloons because two is overlapping and another arrow will be required to burst balloon at three and four but we will end up having saving more arrows because the next balloon which is at four and five it can be merged by this point so you can see we were having let me draw again actually so this example will be cleared to you and you will not require to solve any example but i will recommend to you to solve it once uh yourself this example with using this algorithm so actually you can see we have got a result for this we have got a result of countable 2 because we have merged this you can see this previous will be equal to or this element so it is equal to also you can see so it will be continuing so we will be getting our simply the count we can return the count so 22. you can see answer two but now if you see so this one and two so suppose one and two is this and again two and three so two and three is this so we can simply pass the arrow from two to point so it will burst two balloons so we require one arrow okay now if you see three and four is actually merging with the last balloon but if you see if we pass the arrow from this three and four then how we can burst this balloon which was first this one and two so we will require at least two arrows so that's why we are using two now instead of using the arrow here if you see this four and five so it will be here coming here so now we can pass the arrow from here so if we pass these two arrows from here so we can simply burst all the balloons so where our output will be two so i hope you got the algorithm how we have to do it so actually let me explain you the algorithm or give your summary again so we have to initialize count s go to one because at least we require one arrow and this previous will store this value actually so we will have to check if it is merging with uh this element the next one or not so then we have to sort the array according to the last value or the end uh coordinate of the balloon or diameter then we will run a loop from starting from the one till n and we will merge the intervals or we can simply uh we will increment our count only if the last value is not merging with the first value if this last value is actually one and the second first value of the this second element you can say is two so these are not merging you can see 10 is one is less than two so it will not merge one is here okay two is here it will not merge if this value is actually one so it will be at the same point if it is zero so you can see zero and one then again we are having zero and three so these are merging you can see we can simply uh get a common area from them so actually if you see the time complexity for doing this all will be only enough log n because we are sorting the array for sorting you can see we are using the embed function so it will be using merge sort so it will end up having the time complexity of n log n so it is uh like efficient also and the space concept complexity only will be one or the constant decrease of one because you can see we are only using some variables to show the values that is count and the previous value other than that we are not using any variable so this is only our simple algorithm and only we have to use the compare function also custom compare because we are having this pair so we have to sort it accordingly so let's see the code actually i will show you the code in the c plus and i will also share this code in the description i hope you like this video and do subscribe this channel also let's see the code now so actually if you see this is our uh main function so this is our compare function let's see the main function first so if you see in this function we are given the vector of vector end of points so we are given the points okay so we will check if the points or sides is zero that means we don't have any balloon so we can simply return zero if we have only one balloon then we will require one arrow so we can return one now this is where we sort our array okay we sort our array points or begin and point sort and this is our custom compare function let's see so uh this is a compare function you can see bool a true or not so it will run accordingly now you can see we are having the first element and the second element and we have to sort according to the first value or you can say second value but this is according to zeroth index so zero will be first value and one will be the second value so we are sorting according to a of one okay a of one will be this two and b of one will be this four if we are passing this two values so it will check who is less than four so yes it is true so it will add into the value accordingly if it is like four and two okay if we are having the first value is four and the second value as two so it will return false that means this is not true so it will accordingly sort and build okay so let's see so we are in uh initializing account variable as i told you count will be always one at la at start then we are taking this x or that i read out here as previous okay this will be using for our merging so then we are writing the simple loop it will start from one until it will run till n and if the point merges with x or the previous value and if two balloons are merging so that means we don't require any arrow for that so we do need not to increment any arrow so we will simply continue this so it will skip this loop and it will increment the i to 2 so now if you check if sometimes fl it will not merge so we will increment our count or the arrow number of arrows accordingly and we will also update when we count the upgrade our arrow so that means we are not able to merge so we will have to update our previous value or the x value also so then only we will be comparing if you keep comparing the two with this four it will not end up having the all the correct answers so it will it should be a it should be like change or updated to the full afterwards if we increment this count so let's see and submit this code so at last don't forget to this return this count so yeah so let's see so i hope you got this solution so guys do like this video and subscribe this channel for more such videos thank you for watching guys so you can see this got submitted thank you for watching | 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 |
565 | hello friends so today in this video we're gonna discuss a problem from lead code problem name array nesting so i will first tell you the problem statement it's still like it's tell that you are given an integer array nums where this nums array is actually a permutation of different numbers from ranging from zero to n minus one so they are encoding so from zero to l minus one there are numbers which are permutation from like zero to n minus one okay now what you actually have to do here is you have to find out the longest cycle in this what i mean by cycle is let's assume that you choose any index okay so uh let's assume that you choose uh as you can see in the example this exact index which is the youth index okay so you start from this youth index and then you go to the fifth index which is the number at this point so you go to the fifth and edge which is six now you go to the sixth index which is two okay now you go to the two index which is this zero and you again called zero index which is five so as you can see it is forming like a loop so you start from this earth index then you go to the fifth then six then so fifth sixth and then go to the second and then again to the zeroth index so we have to find out as you can see this is a cycle or loop of size four so i have to turn out four so you have to find out what is the maximum length cycle in this problem now what you can easily understand from two three examples which are given to you that the cycle are isolated from each other what i mean by this is let's assume that i have an array and it has different numbers okay i do not write down the numbers but i just tell you that maybe this is a cycle so i go from this index to this index then this index and then again to the this index stack so as you can see now it cannot happen that for this number i can again go to this index why because see from this number i can go to this index so if this is like this with index it should be two because from this index i should go to two but this cannot happen at this i from this also i can go to two because then it cannot be a competition permutation are unique numbers so it means that this path is not valid i cannot go to the same loop again so it can happen that from this point these two numbers are taken i can go to this point that this point and then back to this point this can be two loops so as you can see what i can easily do in this problem is maintain a visited vector which means that whatever numbers i have already visited because if that number is some sort some part of a loop what i mean by this is let's assume i start from this and i go in this manner and i completed one loop if i come to this point again while it trace like while it trading from left to right i'm going from left to right and checking for every starting point so i haven't taken out a loop from this point so i will go and find out a loop from this point and it ended at this point so it is fine now i take starting from point at this go from this to this and then come back to this point again so it is forming another loop now i come to this point so as you can see this is a part of a loop which i have already traveled because i have traveled this part so i do not have to do it again because if i do it again i will get the same loop again so i don't want to do that so it means that i can keep a visited vector whatever numbers i've already seen so that i cannot do it again because it is already a part of a loop which i've already seen so it means that i only have to travel over every number only once because i'm only touching it once while finding out a particular loop and when i find out a loop i actually store that what is the longest loop length and that's the answer i hope you get the point so i can show you the code part now so uh because i want to store whatever points are actually visited so i can make a global biscuit vector because the length is set to a five so just make it 10 to a five plus like 10 to the five plus five okay or ten plus five plus six anything greater than ten percent and this is the maximum length i can get this is the uh nested array function the starter function the length because i have to rotate from left to right so i iterate over from left right for every starting point as you can see and i only do my okay function or this iteration function only when i find out that the particular ith element is not visited if it is not visited i will call this okay function over the starting point which is i and what is the total length i have seen till now which is like zero and i have to also send the array because i have to check that what is the next point to jump on okay and in the end we just return on maximum how this okey function is calling is if this loop is completed i have to first always write down the base condition in recursive function so the base condition is i have encountered the same number again so it means that i have this is a starting point which is not registered so i will go from this to this when will this recursive function stop this recursive function will stop when i come to the same point again which is always visited so i have already visited out because i start from this point so at this point it should break so it will break when i hit a block which is already visited so as you can see if i've already visited out the visited of that point is equal to one that i have completed my total journey so my total length of this journey is stored in total so i will maximize my total maximum global maximum with this total value and return out of this recursive function else if i haven't come to a point or a block which i've already seen which means that this is a new block so i will first mark it out one that okay i have seen this block now so now from this block i've seen this i will call this recursive function again to the new jump ring position the new jumping position will be the current index i am on find out the value of that so if i'm on the fifth index okay from fifth index what is the number at the fifth index it is telling you three so go to the third index now so my new jumping position will be nums of i okay and you'll just tell the nums again and because i've taken one more number so that total will increment because now my chain has incremented by one position because i've taken the particular number and go to the next question and just that's the recursive question i hope you understand the logic and the code part for this problem if you have any doubts you can mention down i will see in the next one and then keep coding and bye | Array Nesting | array-nesting | You are given an integer array `nums` of length `n` where `nums` is a permutation of the numbers in the range `[0, n - 1]`.
You should build a set `s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }` subjected to the following rule:
* The first element in `s[k]` starts with the selection of the element `nums[k]` of `index = k`.
* The next element in `s[k]` should be `nums[nums[k]]`, and then `nums[nums[nums[k]]]`, and so on.
* We stop adding right before a duplicate element occurs in `s[k]`.
Return _the longest length of a set_ `s[k]`.
**Example 1:**
**Input:** nums = \[5,4,0,3,1,6,2\]
**Output:** 4
**Explanation:**
nums\[0\] = 5, nums\[1\] = 4, nums\[2\] = 0, nums\[3\] = 3, nums\[4\] = 1, nums\[5\] = 6, nums\[6\] = 2.
One of the longest sets s\[k\]:
s\[0\] = {nums\[0\], nums\[5\], nums\[6\], nums\[2\]} = {5, 6, 2, 0}
**Example 2:**
**Input:** nums = \[0,1,2\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] < nums.length`
* All the values of `nums` are **unique**. | null | Array,Depth-First Search | Medium | 339,341,364 |
969 | Everybody Gets All the Best Problem Bank Shopping for Giving Relief Victory Procession Half Are Performing in Wave Subscribe Like This Away from You for Example 814 Subscribe 1234 Turn on the Operation in To-Do List of the Content of This Problem To-Do List of the Content of This Problem To-Do List of the Content of This Problem Can Go to Do the Element Key tune of from one to the for example 3512 possible birthday all end after sending equinox 123 that porn so my for elements and 900 episode 354 is on the end right now for is on this index michigan index to visit to take this point to right so Every one to take this point to the first will move this point to the state of the video clip this point subscribe button to A Position Of And No Way Can Reduce Like Beer Can Remove 49 Will Reduce Come To This Point To That Electronic Display 1653 Subscribe Our Video Clip Of 2312 Subscribe To Floor Mills That 2131 For This Is It A Prank Clip Of 383 Subscribe 90 Connect Position directly subscribe 1234 that hence this can be given only solution situations like his adopted daughter element first position and the element subscribe also maximum to the like subscribe to subscribe and subscribe the amazing Internet Thursday From Noida Plus App that this offer is equal to target And will return diary don't want the tarzan - return diary don't want the tarzan - return diary don't want the tarzan - subscribe video like share and subscirbe from 0 to sleep will start from this will money aghi na af plus 2 f ki jan26 - - beerwah to elements and ki jan26 - - beerwah to elements and ki jan26 - - beerwah to elements and monitor person then subscribing element no Like Subscribe Class 9 Widely Loud Subscribe comment and subscribe the 102 209 First Will Find Index of the This Element Current Element By Calling Different Method By Passing A In The Mid Day Do Subscribe 125 Wishes Answer Is Not Clearly No Problem No Will Be Reduced Values in this will start at one end and Values in this will start at one end and Values in this will start at one end and research will be plus way from list daughter and will return all the subscribe button to subscribe like subscribe and subscribe must that and a maximum clear doing hair to star till lips chief min hair to start and end space Complexities of Surakshit Like and subscribe to receive notifications thank you for watching | Pancake Sorting | number-of-recent-calls | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | null | Design,Queue,Data Stream | Easy | null |
363 | Hello guys, once again welcome to all of you in the video of Tier-3 Daraz on your YouTube channel. The all of you in the video of Tier-3 Daraz on your YouTube channel. The all of you in the video of Tier-3 Daraz on your YouTube channel. The list has a very interesting question and the logic of the question is applicable in many ransom cars. The question for this is Find the Maximum Hypnotized Triangle No Rajasthan So basically it is a metric life, it is understood on the white board that it is a metric life and in that matrix what has been told to us that tell us the maximum which is garlic and request to Yes, meaning, now it can be of any color, it can be of this whole, of this, sometimes, it has become the Everest Canto of a thing, whose face has to be told in this type, how much is the maximum, which is garlic and request. If you have missed it, we will tell you okay, there is no problem, so now to do this, between two, yes, we can do this, we can generate a private address in a way, take milk in which we can now let us do what we can do. Our top most coordinator will start it loudly and it will change every time, like first this, then this, okay sister, we will still take the prostate type here, then here. B Hydration will be completed, we will change our top most cord from where we will strengthen the prostate roots here, we will make it on zero command1 and then do the same process that once we placed our bottom coordinate or then placed it here again or Placed here again then placed here again placed here Similarly Top Most Prominent Considering this cord as a toss all those placed in front of those whose request is handled the maximum has been picked up Time Process for this After that Same process and Top Most of the country This will make this the top most medical brother, giving respect to life here, then this day, this one is fine, similarly, we or this one has become the top most, after that we will make this one the top most, from here this one and this one, then this one will become Or this will be made, if this will be made then the top most prominent martyrs will keep on doing this and internally we are supporting it because we need 100 grams internally also, if we put the loop then the time complexity will increase a lot, so that's why I said this. Even if we make it and tell us about this region that Sri Lanka is all over, it is the evening of this region, then what should I do, from the entire time of this region till here - make it up entire time of this region till here - make it up entire time of this region till here - make it up to here - add it and add to here - add it and add to here - add it and add this Why should I do it because it became the subject twice, once when we all tweeted from here to here, this area also got included in it, then when we selected the word 'Kasam' which is from here to here, selected the word 'Kasam' which is from here to here, selected the word 'Kasam' which is from here to here, then this sexual thing was improved again. If it is done then the reason for having two boring roads is that we had to keep it once whereas if it is done twice then I will add it once so below this, what can we say and our coordinator for any coordinator access oil if this question is a distraction. Live without you want to listen to do, if we want this rectangle, then what will it go to the whole, understand who will be the training From here to here the whole will be created where is the anger if this is what if this but if this is this point - 110 that they one minus one - this entire Lanka - 110 that they one minus one - this entire Lanka - 110 that they one minus one - this entire Lanka time - what do we have for this time - what do we have for this time - what do we have for this What will be the stop for this that every day who we had if this is the explain point then who will be this upper one this point election - one ko ma action will be this upper one this point election - one ko ma action will be this upper one this point election - one ko ma action minus one coma in Y2's problem medicines not in Y2 and in plus because two You must have taken the engine twice. If you cut it once, then which region is this? Exam Form of Expansion - One region is this? Exam Form of Expansion - One region is this? Exam Form of Expansion - One End Why One Minus One Diner Lever Breezers One Minus Point Delivery So this is our question accordingly. Solvable and whatever I understand at this time, whichever is the maximum of the online question will become the immortal answer. Okay, so let's just record now. You have come to my training, tell everyone how it is generated. We are eager to generate it for us. A wedding. We will make it, we will accept the oven and will do the wedding like this is your boy, we will do the wedding like this, we will do all these 0's, we will cut it, which means to say - 1, cut it, which means to say - 1, cut it, which means to say - 1, but the doctors start our life from zero, the fun of Bansal is the result of the above. Will put pending so that our question will be easy in terms of intake, medicine scan, then we have to keep face conditions for the poor laborers, it is not there, hence we will do it, there is a in it, so now let's go straight to it. For the code side and for the court, we start in this, our professor makes it and then we do something or the other in it, otherwise there is another way, it is made through minor research, it is a little different in that we first Hare Pura's entire life got tips, the end of this entire region will be searched in it, which maximum means maximum number of mails per day and request is made, then that is also acceptable and this is acceptable, so much so that there will be no problem in it, okay, so let's do it. They are towards start coding and let's see what has to be done in it, so what did you do? First of all, we quickly made one of our indies RAM and Nikam took it out and kept it because it is Bose's definition, so take it out. It is correct and Na Agarwal later again we have to write on this soil, then the matrix that Arjun Adher DTH will make digi as if I made DP, then how will we make DP in mother prefecture, we will make PM plus one extra because of wedding so that all Index you can waste time in this otherwise it would have been a problem this became you I have it now we will fill our dp point ivory coast off islab request oh mi plus and vintage boston1 the day request 10:00 vintage boston1 the day request 10:00 vintage boston1 the day request 10:00 plus no do this Now we said that Bloody Mary has only one filling, how to fill it, like I am going to fill this channel, then what will happen to this light, how will I take out this year's evening? Light because according to the matrix, put this one in DP, I will be me, because of the wedding broke, who was that in the matrix, I - bank who was that in the matrix, I - bank who was that in the matrix, I - bank manager - one will be the office, because I am tiffin manager - one will be the office, because I am tiffin manager - one will be the office, because I am tiffin dec-2010 This and my one, our one If you want to dec-2010 This and my one, our one If you want to dec-2010 This and my one, our one If you want to add current element, then Matrix of I - 121 then Matrix of I - 121 then Matrix of I - 121 Ki Agyeya - Dad, do it okay. Plus I have now Ki Agyeya - Dad, do it okay. Plus I have now Ki Agyeya - Dad, do it okay. Plus I have now added, so now how have we added together, who were the reasons and have to add, along with this we have added this matter. Value has to be done for this region, have sexual intercourse till here and till here sometimes there is current value in plus and explicitly that even if you want the complete history till now then also you will do it, add porn till the whole time and here Till ever explicitly add it means I and J - Monica and Eyeliner means I and J - Monica and Eyeliner means I and J - Monica and Eyeliner and because you see that when I add this express entry twice then this will also be done twice so it will have to be subscribed once and then General Mathematics Kind of Singh is area wise, so you try inviting him on this, then I set his alarm, then I - me and I - set his alarm, then I - me and I - set his alarm, then I - me and I - then I comment - then I comment - then I comment - I comment, Jai minus one is also added and it happened twice. If you want to subscribe to the tips, then they are Constructed by BPO I - One Comedy - It is the first - One Comedy - It is the first - One Comedy - It is the first that we have kept it all tight, now our wife is completely gone again, let's like our one three below, let's support the missions Printed minimum value because Maximum wish is to do our we take out everyone's point i20 is judgment i that emma is i plus and these days ago 0 who is the land g plus that nine after doing this now tell us that yes now in our actual this we four do Actually, now we have grabbed the experts at zero, for the top most corner, the one who is going to be in our top most is going to be like this in the dead top post, so now we will add two more looks for the water motor and these This request I Yashwant we are plus one and this kaun taak costume tak a plus a remedy for bs well points page 2010 Stuart will get the gap Laxman ne se 20 loosening and 210 that Android plus now we will put ours then to do Method of deep temporary something, how will we take out the time, Sri Lanka, I have taken the last location of the entire location, because look at the celebration, because in actual also, you will see SinghVP that when the payment is cleared, that is why the coordinator has been kept at zero size and Deepika. Actually, we have one right now, it will be from its plus one, so this much value is there, how to update from that, I had asked to update the volume same one Amazon - in bp.ed icon also - in bp.ed icon also - in bp.ed icon also in A plus because that valley. If the chapter is done twice then I will have to add a rally of fun - - - Youth - 151 - What Action - 151 - Manju Youth - 151 - What Action - 151 - Manju Youth - 151 - What Action - 151 - Manju In the original this happens, if it is difficult then you are Laxman, then I will have fun and with the interests of Mathematics in these preambles, you will get to know how to make a statement, much respect, calculate area etc., read mail messages, calculate area etc., read mail messages, calculate area etc., read mail messages, you can do it like this and you can do it by sending zero too, if we have a lot of time, if we have the time. That loosening is done, so from Dhan VPN that yes, what can we do, at this time we can say our answer can also answer can be maximum of answer, we are in coma, we can say this and the last moment when all Work will be done also Apni Tange Sthali Congress MP and Anshu Maximum Ishwari Main Run Maximum In Jawa In This Matter But Maximum Mo Loot Ok So You Must Have Liked This Video Full This Video Guys Please Comment Channel Subscribe Our Channel And I Bhi Generation Of Service I also want to upload Qawwali, all that was left was the time of clothing and job, it is fine in her play list, ok baba guys. | Max Sum of Rectangle No Larger Than K | max-sum-of-rectangle-no-larger-than-k | Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`.
It is **guaranteed** that there will be a rectangle with a sum no larger than `k`.
**Example 1:**
**Input:** matrix = \[\[1,0,1\],\[0,-2,3\]\], k = 2
**Output:** 2
**Explanation:** Because the sum of the blue rectangle \[\[0, 1\], \[-2, 3\]\] is 2, and 2 is the max number no larger than k (k = 2).
**Example 2:**
**Input:** matrix = \[\[2,2,-1\]\], k = 3
**Output:** 3
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-100 <= matrix[i][j] <= 100`
* `-105 <= k <= 105`
**Follow up:** What if the number of rows is much larger than the number of columns? | null | Array,Binary Search,Dynamic Programming,Matrix,Ordered Set | Hard | null |
415 | hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 415 add strings let's read the question prompt given two non-negative integers num1 and given two non-negative integers num1 and given two non-negative integers num1 and num2 represented as strings return the sum of num1 and num2 as a string you must solve the problem without using any inbuilt library for handling large integers such as big integer you must also not convert the inputs to integers directly so for example if we were given the number 456 and 77 we would want to return 533 let's see how they did that and let me change my pen here to be more visible okay so we see that we have the number 456 and we want to add 77 to it well if you remember from i guess elementary school how to do division um not division uh addition what we need to do is basically add these numbers and take care of the carry so 7 plus 6 is going to be 13 so we have 3 carry the 1 5 plus 7 is 12 plus the one that we carried so three and then we carry a one again and then four plus one five thirty three which is um what we can see is our answer here so essentially what we've done here is we've lined up our values here and we've added them so we want to do the exact same thing for our strings basically we want to align them and then go from you know right to left and add the values at whatever index but you'll notice here that this string on top the 456 is actually longer than 77 so what happens when we get here where there's nothing well what we want to do is you know if we're traversing and we're at an index in our one of our strings that is not accessible because it would be out of bounds then we would just want to treat that index as a zero so if we just pretended that this was zero seven then we could do the additions as much as we wanted and this four five six could have any other things in front of it we would just treat those indexes as zero that way we can just add directly and we wouldn't have to worry about anything so that's the idea that we're going to use two pointers one to start here at the beginning sorry the end of our first string and one at the other uh end and we're just going to go from left to right extracting the value at the current index and remember that since we're going from right to left we're going to be decrementing our index each time so if the index for a particular string ever goes below zero that means that we've exhausted that string entirely therefore we instead of extracting whatever value is at the index for that uh particular string we're just going to extract the value zero and that way we can just continue doing the addition to parse through the longer string and then we're gonna have to maintain a carry variable here to you know keep track of these carries that we had each time and you know we'll just do the addition each time and then add that to some sort of like string builder and then join it all back together so we can return our you know result here as a string as it asks for so that might be a little bit confusing but let's go to the editor and once you see the code everything will be super clear this problem is quite simple and it does lay the foundation for some other problems on lead code so definitely want to know how to set up um this problem but like i said it's super simple so let's go to the editor and see the code we're back in the editor and let's write the code so like i mentioned in the explanation portion we're gonna want two pointers one pointing to the end of num1 and one pointing to the end of num2 so let's declare those variables so we're gonna say i equals the length of num1 minus one that's the last index and we're gonna say j equals the len of num2 minus 1. now what we want to do is remember that we need to keep track of the carry so we can add that each time when we do our addition so we're going to say carry equals 0 and we're going to say res which is where we're going to store our result here is going to be an empty list now what we need to do is we need to exhaust both num1 and num2 so we need to move our pointers until we've done all the possible additions that we have so we're going to say while i is greater than or equal to zero or j is greater than equal to zero and remember we're using or here because once if they're both the same length and it's really simple they'll both end at the same time because we're decrementing by one each time but if one is actually longer than the other it will take longer to reach its end and then while that one is processing the other one that has already been exhausted we're just going to instead of extracting the value at its index we're just going to extract the value 0 because obviously adding 0 to anything doesn't change the computation so with that explained let's now extract the values we have at the i and j index so we're going to say cur i is going to be the integer of num of sorry num1 of i and we're allowed to do this because remember we can't convert the entire thing to an integer but we can convert pieces of it to an integer and use that to do our calculation so remember we have to extract num1 of i if i is valid right if i was actually less than zero then you know we would be extracting the wrong thing python actually lets you do negative indexing you know lookups but you know we would get the wrong values so we just if it's greater than or equal to zero we want to extract the value otherwise we want to extract zero and we're gonna do the same thing for j we're gonna say equals to int num2 of j if j greater than or equal to 0 else we're just going to get the value 0. now what we want to do is the current sum of our position is going to be whatever the carry is from the previous sum plus the current i plus the current j now we need to append that value to our result but what happens if we have something like 13 obviously we only want to append the three and we want to carry the one for the next iteration how do we do that well what we want to append to our result is going to be cursom modulo 10. so remember that you know 10 mod 13 modulo 10 would return three because it's basically the remainder of what happens when you divide by 10. so that would give us this one's digit position item so that's how we extract that one but now we also need to keep track of the carry so the carry this time is going to be and do note here that we're converting back to string because at the end we're going to join all of these items together and return it as a string and you can't actually join in python if all the elements that you're joining together are not strings that's why we cast back to a string getting back to carry what we want to do is we're going to do curse some integer divided by 10. so if we had something like 13 integer divided by 10 this would divide this would be one so basically what is the result of integer dividing by 10 so we're going to get you know the 1 there so at this point what we need to do is we need to decrement i and we need to decrement j and then our while loop can continue and we're going to do that until we've parsed out the entirety of num1 or num2 whichever one is longer if they're the same then they'll end at the same time if not one will end before the other now what we need to do is before we can actually return our results we need to check if carry was still left over it could be the case for example if we had the number you know 999 plus 999 that you know when we're adding these last two nines you know we'll still have a carry left over but there's nothing to add here because we've already computed both of the values so we'll still have a carry that needs to be taken care of so we do need to make note of that and we're going to say if carry so basically if it's not 0 we're going to say res.append whatever we're going to say res.append whatever we're going to say res.append whatever the current carry value is so we're going to say string carry now at the end all we need to do is simply return our result but remember we were processing this number from right to left which means that as we were appending our value will actually be in the opposite order that we need it to so we need to reverse our result before joining and that's the last thing we need to do so we're going to say return string dot join reversed res so that will give us our answer so let's just submit this to make sure we haven't made any mistakes here hopefully okay cool didn't embarrass myself there all right so our solution works now what is going to be our runtime complexity well we know that we need to process the entirety of num1 and num2 so that's going to be big o of n plus m where n represents the length of num1 and m represents the length of num2 and what our solution here is going to be it's also going to be big o of n plus m because we need to account for basically the sum of these two which is going to be you know dependent on the length of n plus m uh what our actual result ends up being so that's going to be our run time complexity here and our space complexity that's how you solve add strings there is a problem where i think it's called add binary which is literally the exact same code except now our numbers are not going to be um base 10 they actually mean base two so you can literally just replace this with a two and this with the two when solving that question and you will be able to solve it's the exact same code you just need to remember that it's binary for that one whereas this one is uh base 10 so that's why we're you know modulo 10 and divided by 10. anyway uh that's the solution for this problem i hope you enjoyed this video if you did please leave a like comment and subscribe check out my other videos if you're preparing for on-site interviews you're preparing for on-site interviews you're preparing for on-site interviews and happy elite coding | Add Strings | add-strings | Given two non-negative integers, `num1` and `num2` represented as string, return _the sum of_ `num1` _and_ `num2` _as a string_.
You must solve the problem without using any built-in library for handling large integers (such as `BigInteger`). You must also not convert the inputs to integers directly.
**Example 1:**
**Input:** num1 = "11 ", num2 = "123 "
**Output:** "134 "
**Example 2:**
**Input:** num1 = "456 ", num2 = "77 "
**Output:** "533 "
**Example 3:**
**Input:** num1 = "0 ", num2 = "0 "
**Output:** "0 "
**Constraints:**
* `1 <= num1.length, num2.length <= 104`
* `num1` and `num2` consist of only digits.
* `num1` and `num2` don't have any leading zeros except for the zero itself. | null | Math,String,Simulation | Easy | 2,43,1031 |
62 | Hello Hi Everybody Welcome To My Channel Today Is The Second Last Date Of Units Wedding Chalen Is Dahej Ki Problem Is Unique 500 Vs Laptop Left Most Corner Of M Cross And Great Hair This Start Points And Notes Can Only Move On The Dawn And Right At Any Point Of Time Android Trying To Reach At This Point For This Is And You Have To Find Out How Many Possible Units The Robot Were The Subscribe To Our Channel Subscribe Now To Great Hair Soft Videos And Columns From This Conic 10 - 151 This Opinion From This Conic 10 - 151 This Opinion From This Conic 10 - 151 This Opinion Unlimited One Road Divider Ko Share And Hai 100 Basis Of All Way N Crime Ek Option Robot For Them Road Reach Subscribe And Donate 100 Road Possible Options Subscribe Can Very From Where From The Side And Subscribe Our Channel Like This Way Can Come From A Good One To Three To The Answer And Sorry For The Robot Subscribe According To Agro Robot From Here Someone Way All In The Air 1512 From A Great To Three Floor 500 600 3060 Had To 100 Will Not Right Side Download To Check Particular Coordinator Robot Can Only From MR that this is minus one coordinate and the I - one is called that this is minus one coordinate and the I - one is called that this is minus one coordinate and the I - one is called Maje Coordinator from being left side Sudhir and 10:00 So what we can do The side Sudhir and 10:00 So what we can do The side Sudhir and 10:00 So what we can do The number of tourists can form of I understand that can be written S D P F that I - One Ki Ko that I - One Ki Ko that I - One Ki Ko Majhe APlus Hindi PDF A Hai Aa J - 1m J - 1m J - 1m Slack Try to First Form Dainik Cursive Solution Handed Over Let Me Call The Everywhere The Total In Part UP From Record Chintu This Point Acidity Se - Oil - 110 The Chintu This Point Acidity Se - Oil - 110 The Chintu This Point Acidity Se - Oil - 110 The Soul From This Pat Let's Thee Vikram Come Like No One Can Come Only From Two Where From Here A Minus Two And Country One Life Amazon Voice Mail In Coma - 2 And From Which Coordinator Which Is Akin To Voice Mail In Coma - 2 And From Which Coordinator Which Is Akin To - Two And Other Same Inventions And - Two And Other Same Inventions And - Two And Other Same Inventions And Destroys - 151 - Two Columns So What We Can Destroys - 151 - Two Columns So What We Can Destroys - 151 - Two Columns So What We Can Benefit From It - 151 - One Will Go Benefit From It - 151 - One Will Go Benefit From It - 151 - One Will Go To The Way UP Of - 251 To The Way UP Of - 251 To The Way UP Of - 251 To End And This One More Minute To Sum Up India -Foreign Tweet UP Total Links From Pat -Foreign Tweet UP Total Links From Pat -Foreign Tweet UP Total Links From Pat - 151 - To Reduce Father Will Go Alone In A - 151 - To Reduce Father Will Go Alone In A - 151 - To Reduce Father Will Go Alone In A free to champion again more the robot to the point will return from the middle of 10000 subscribe up returns page after - one to three boys top the page after - one to three boys top the page after - one to three boys top the software will have or private method tent tube which will get into it's a shame for Mind 0 I will check only MS Word 120 and I am the request 0 Sample for turn on this vansh and other wise only family 20 and here and 10 that he will return 020 that hero otherwise will return social POP of feminines one plus side manas -1 Sudhir and Subscribe Like this is the Father Govind Str on - Pratima Str on - Pratima Str on - Pratima that and minus one and which one will visit UP after oo that UP is off - to butter - 2 acid less that UP is off - to butter - 2 acid less that UP is off - to butter - 2 acid less from which branch this tweet UP after - 2m from which branch this tweet UP after - 2m from which branch this tweet UP after - 2m - to - to - to This anniversary is a serious problem even from the right side, this is repeated hair, for example, all problems, thoughts, updates, Wilks result, officer problem, this, Zauq Singh, I am letting me use this in teenagers, a map of string for my hand, a juicer, a map, nickel to a new house, a map. 200 what will to will create from that bill se speech in the soil with string key request to plus $1 we using an india limited because they remind $1 we using an india limited because they remind $1 we using an india limited because they remind me to different this festival delete meter can give the same that maybe will create subscribe content's that Will Returns The Ki Hum Ki Is Saade Se And Indian Hair And Wealth Will Just Update Also The Place Value In The Letter This Is The Topper Us Implementation Of Problem Solve Picture In This Way Solution Citizen Compiling Running For the first test-tube Running For the first test-tube Running For the first test-tube baby very soon where written in correct taking too much time e this is all height for digital sign hai starring reddy who catenation plus hair safe and 102 ki rishi taking too much time encompassing also collect code in this verse in busy schedule Submit This The City Has Accepted And Same Time Complexity Of Dissolution Of This All Time Complexity Of Dissolution Is Form Of M Com And Space Complexities Us My Name As Given Subha Channel Se Implement This Problem Using The Water Mob Dance Programs Let's Video Course For Water Will Just One Too Today In Tv Today Are Dp Images Interface Size Plus Top Color Loud Plus For 10 Subscribe Tomorrow Morning 6Pe New Hair Resignation Strawberries Only One Way Robot Nuvve And Columns To What We Can Do 504 And J0 Case Will Awards Pema J is swelling other wise words page if his defeat after - one subscribe plus subscribe - one subscribe plus subscribe - one subscribe plus subscribe The Channel 220 layton dpi ko maf my name a minus one corner and minus one saudi system approach solid is earning that undertaking sometime e don't know weather retail list ko d Silvat Session Judge Singh Ya Wedding Correct Answer So Let's Acid Hua Hai The Site Is Accepted For The Time Complexity Of Dissolution Is Mess This Channel Subscribe Button Carefully See What They Are Doing This Relation Is This Is Equal To Of Them And Top 5200 2MB Subscribe And Switch on share mode that you turd what we can do hair drink spreading witch will update dros using the model to like involve will update roadways bus se continue like this they will update the verses will just rot this with subscribe who hair is film and Bittu Similar Mod Bittu An Indian Vijay Returns Again Dashami Mod With To Subscribe Hindi Mein Torch Light Is Compiling Yes The Judge And Now Any Sphere Cutting Correct 100MB Submit Dashrath Accept So Her Not Been Optimized Subscribe To 210 Problem Can Also Be Thinking Other Way Of Life but will remove hair from where to total - they number coordinator right side and total to total - they number coordinator right side and total to total - they number coordinator right side and total minus one side total vote's mood plus minus b hua hai - plus minus b hua hai - plus minus b hua hai - one plus and minus one hand they have to white dream defect is mathematics solution of ninth mathematics for implementation Thank you in comment section please like share and subscribe my channel | Unique Paths | unique-paths | There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100` | null | Math,Dynamic Programming,Combinatorics | Medium | 63,64,174,2192 |
1,710 | let's solve the problem 1710 maximum units on a truck so the question goes like this so you'll be given a truck size is nothing but a capacity of the trucks okay so let's take an example so say the in this example you are given a truck size of 10 okay so my capacity is to store 10 boxes okay and then there is an array that they provide with different types of boxes okay that doesn't matter but what matters is within this each type of box they are giving us two information one is the number of boxes of that type and the number of units per box how many units can be stored in one box right so that's what they are giving us so in this example particularly they are saying that of the first typ there are five boxes and each of those five boxes can store 10 units each okay in the second type of box there are two boxes in each of those box can store five units each third type of box are of are four there are four SE boxes and each stores seven units and then there is fourth which is three boxes and each of those stores 9 units each so I need to figure out with such an example how many units can you load into the truck given that you can load maximum 10 boxes or whatever the capacity that they provide how many units can be up loaded into the truck maximum units that can be loaded into truck so in this example what I'll do is to resolve this what I can do is the best way would be to take the boxes with the maximum units first right so I can maximize my units so the first one for each box I get 10 units it takes just one box away and adds 10 units right so definitely I'll take this one next I'll go with this right the second largest number of units per box then I'll go with this the third largest units per box and then finally if there's any then I'll go with the fourth one so I'll first reorder it this way then I'll start counting how many units can I go so I'll see can I add five boxes certainly I have capacity of 10 I can certainly add five boxes so how many units do I get 50 5 into 10 50 units then I can reduce the capacity now my left capacity has 5 boxes I'll go to the next one can I add three boxes yes I can so 3 into 9 how many units I'm getting 27 right I'll reduce the capacity by another three I'm left with two back box capacitor space can I add four boxes no four is greater than the my capacity so what I'll do is I'll just stick two of these boxes so I'll add 2 into 7 14 units I cannot take all four boxes but I can take two boxes so I'll multiply 2 into 7 I'll get 14 units so finally the sum of all this 50 + 27 + 40 is all this 50 + 27 + 40 is all this 50 + 27 + 40 is 91 so total units I can carry is 91 right this is what I need to code it okay so how will I do first of all count is equal to zero right and then while or I could do for I in range length of box type box types okay and then before this as we had discussed we will sort box types by the number of units per box and in descending order so how will I do that box types do sort my key will be Lambda is a function that I'm writing Lambda it takes in each box and sort it sorts it out on the first index element of it zeroth index tells me about the number of books the first index tells me about number of units per book so I want to sort it by that s pass or pass X at index one okay also I need to reverse is equ to true so that it does it in a descending order so I get the highest number of units at the top at first and or on the left of the array and lower numbers as we proceed to the right so now I can go with for I in range length of box types if box types at i z is less than or equal to Tru size then in that case what I'll do is I'll add it to my count so count plus equals to box types at 0 multiplied by box types of I have one so boxes multiplied by units so that manyan count will be increased in case my box types number of boxes in that at that index is less than the less than or equal to theze else if it is greater than or equal to Tru size what I'll do is I'll put the remaining uh space multiplied by so remaining spaces whatever the truck size is also I need to reduce my truck size here while I'm using those boxes I can reduce that much capacity from the truck size so now I can take the remaining truck size because truck size is smaller than count at count of boxes so I can take truck size into units or box why because only that many boxes out of all the boxes in of that index I can use up right so truck size into box type of box units per box that I added into the count and finally return the count so I can do it something like this count plus size this and I can return this at this point because after this my truck size is totally come full there is no capacity left so I can return whatever the answer is no need to continue the loop after it but if say the loop gets over before the truck size is filled which means that I have taken all the boxes Till There is space in the truck or I have taken all boxes and there is no space in the truck in both those cases the loop will run completely and it will never reach this point right so it will never returns off the loop is complete I'll return units of count okay let's look at this I put brackets here to just explicitly tell that multiply this first then add to the count let's run and see if that works that worked beautiful so that's how this can be solve let's look at for some of the solutions from other people and this is the best solution it's just doing exactly what we are doing let's look at one more solution all of them are following something very similar to what we have done so that's how you can solve the problem 1710 maximum units on a truck see in the next we | Maximum Units on a Truck | find-servers-that-handled-most-number-of-requests | You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106` | To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add. | Array,Greedy,Heap (Priority Queue),Ordered Set | Hard | null |
217 | hey everyone welcome back and let's write some more neat code today so today let's solve contains duplicate this is another problem from the blind 75 list of questions we've been working on so i like this problem because it's a good problem for beginners but there's also multiple solutions to it that i'd like to go over in this video so we're given an array of numbers we want to return true if there's any value in that list of numbers that appears at least twice but maybe it could appear three times or four times write just at least twice and we want to return false if there aren't any values that appear at least twice basically what that means is that every value in the array is distinct so let's take a look at an example we have one two three and then we have 1 again so of course this has duplicates right so we return true and the easiest way we would be able to detect that is by brute forcing this so given these numbers the first thing we do is look at the first number it's 1. how do we know if this is a duplicate or not well we'd have to compare it to every single number in the rest of the array so that would be a big o of n time operation just to check if the first number is a duplicate or not and then we'd have to do that for every number then we have to check is the second number a duplicate how do we know we have to compare it to every other number we do the same thing with the third one and the last one and so since we're doing it for every number in the array the overall time complexity is going to become n squared and by the way in this case n is just the size of the input array so the brute force solution is big o n squared time complexity but the good thing is we don't need any extra memory so the memory complexity is big of one it's definitely not a bad solution but the question is can we do better than that and yes we definitely can a second approach that will help us is sorting what happens if we took this array and we sorted it would look a little bit different it would look like this okay but how does sorting help us well let's think about it if we sort the input then any duplicates that do exist in the array and clearly we see that two duplicates exist at the beginning of the array they're going to be adjacent so when we're trying to detect any duplicates in here we only have to iterate through the array once and as we do that we're just going to be comparing two neighbors in the array checking if they're duplicates next we're going to shift our pointers to the next spot are these duplicates etc until we finish the entire array in this case we see that these two adjacent values are duplicates so we can return true and what's the time complexity of this well the one pass is just going to be big o of n but we know that sorting does take extra memory or not extra memory it does take uh extra time complexity and that time complexity is n log n so that's the bottleneck in this solution but again we don't need extra space if you don't count the space that's used by the sorting algorithm so in this case we do have a slightly better solution than brute force but actually if we use a little bit extra memory and it's really a trade-off if we sacrifice space a trade-off if we sacrifice space a trade-off if we sacrifice space complexity we can actually achieve better memory complexity and let me show you how so suppose we don't sort our input we're given the default input but we use extra memory we use a hash set but what exactly is a hash set gonna do for us it's gonna allow us to insert elements into the hash set in big o of one time but it's also gonna allow us to check we can ask our hashmap does a certain value exist we want to know does this 1 exist in the hashmap well if we start at the beginning of the array so far nothing is in our hashmap so a 1 does not exist in our hashmap that means this 1 is not a duplicate you can see that this is an improvement over the brute force previously to determine if this was a duplicate we had to check every other value in the array this time we don't but after we have checked if this is a duplicate we do have to add it to our hash set because later on if we encounter a one like over here then we determine that this is a duplicate because we know that there's already a one in our hash set so next we're gonna check two is not a duplicate added here is three a duplicate nope add it here one is this a duplicate yep there's a one over here so we return true this does contain duplicates and by the way since each operation was just big o of one we had to do that for every value in the input array and we only had to scan through the list of inputs once the time complexity is going to be big o of n but the space complexity we did have to sacrifice a little bit we have to create a hash set and the memory that hash set will use could be up to the size of the input array which is n so we do end up using extra memory but that's not too bad this is about as efficient as we can get in terms of time complexity so let's get into the code now okay so now let's get into the code so the first thing i'm going to do is create that hash set in python you can do that just like this it's just called a set and then the simple thing is just going through every value in the input array nums and before we end up adding it to our hash set because remember we want to add every one of these values to our hash set just like this but before we even do that we want to know is n a duplicate does this value already exist in our hash set and if it does we know that our array contains duplicates so we don't even have to continue through the rest of the array we can immediately return true because we found a duplicate but if it doesn't contain a duplicate we're going to add that value then iterate through the rest of the array of nums and then the loop will exit and then we can return false to indicate that we did not find any duplicates in the array now let's run the code to make sure that it works and on the left you can see that yes it does work and it is about as efficient as we can get so i really 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 and hopefully i'll see you pretty soon thanks for watching | Contains Duplicate | contains-duplicate | Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** true
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Example 3:**
**Input:** nums = \[1,1,1,3,3,4,3,2,4,2\]
**Output:** true
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109` | null | Array,Hash Table,Sorting | Easy | 219,220 |
1,095 | me Brea me let me the lungs inside you and the black and eyes make my way into your mind just to know what you knew rest every time we start locking as all oh I lost control oh is Paradise with a nasty B wi the dead of the night let the darkness take control let the darkness take control Darkness take control May the darkness take control take me in small breathe in and let me go sink to your heart to find you open up your eyes till you're blinded by the lights so you can see what you do rest every time we start Ling as oh lost control oh is Paradise with our nasty by in the dead of the night tear drops on the FL the Fain is over field the darkness control take that you should know I've been going so low one my love baby ear yeah doesn't on my own see if you can follow got me feeling Al lie one go control is real all I feel real I do what I want o I do what I want ooh I do what I want hear me now I do what I want are you ready now cuz it won't be easy only get what you work for got to go all out whenever you see me don't be wasting my time watch me go control is this real I feel bre my signs tell's be real I do what I want hey I do what I want I do what I want hear me know watch me go control real all I feel I do what I want I do what I want I do what I want I me now I do what I want like me small breathe me in and let me go feeling the lungs inside you and the black and eyes make my way into your mind just to know what you knew rest every time we start locking eyes oh I lost control is dice with a nasty but win the dead of the night let the darkness take control let the darkness take control Darkness take control May the darkness take control like me in small breathe me in and let me go sink to your heart to find you open up your eyes till you're blinded by the lies so you can see what you do Restless every time we start Ling as oh lost control oh is Paradise with our nasty by now in the dead of the night te drops on the | Find in Mountain Array | two-city-scheduling | _(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`
Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`.
**You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface:
* `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed).
* `MountainArray.length()` returns the length of the array.
Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification.
**Example 1:**
**Input:** array = \[1,2,3,4,5,3,1\], target = 3
**Output:** 2
**Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.
**Example 2:**
**Input:** array = \[0,1,2,4,2,1\], target = 3
**Output:** -1
**Explanation:** 3 does not exist in `the array,` so we return -1.
**Constraints:**
* `3 <= mountain_arr.length() <= 104`
* `0 <= target <= 109`
* `0 <= mountain_arr.get(index) <= 109` | null | Array,Greedy,Sorting | Medium | null |
929 | it was a guy's nick wife here at attacking coding stuff on twitch in youtube and do all the solutions to all the hacker ink and lead code problems so just check my playlist it's on my channel I have them for both this one's called unique email addresses it's really easy every email consists of a local name and a domain name separated by an @ symbol for example an Alice at by an @ symbol for example an Alice at by an @ symbol for example an Alice at Lee code comm Alice is the local name Lee cocom is the domain name besides lowercase letters the emails can contain period or plus symbols addition symbols if you had periods between some of the characters in the local name part of an email address mail will be sent there to the same address without dots in the local name so we see periods we just ignore them for example Alice dot C will just be a lousy forward to the same email address if you see a plus in the local name everything after the plur first plus sign will be ignored this allows emails to be filtered for example m dot y plus name will be my email com so just ignore anything after the plus and before they add symbol so how do we do this it's pretty easy we're just gonna loop through this well first of all we're gonna have a hash set because we want the count we're gonna be outputting we're gonna be in we're gonna have the input of a bunch of different emails and we're gonna have to you know obviously do what we fix these addition and split it into local name and domain name fix the addition and periods but we want the unique email addresses out of the list that we're given so we're gonna have a hash set because we can just loop through all these emails this array of emails fix will create a fixed version of each email and then we'll put them into a hash set and return the count at the end because a hash set only keeps unique things unique values so that's the method here we're gonna have a hash set of strings called unique emails we're gonna do a loop we're gonna use the kind of object loop here so for string email and emails so we have access to the current email as we loop then we're gonna go first we're gonna get the index so we're gonna get I'm gonna call it split position we're gonna get the index of the at symbol in the current email and then this is how we split we're gonna use the substring method so we're gonna do local name is equal to e mail dot substring from 0 to split position so now we have the local name in the domain name is going to be set to email dot substring just a split position because by default this will just give us the rest of from split position to the end of the emails length that's pretty much it and then all we have to do is if local name doc now we split the email up into before the @ symbol and after the @ before the @ symbol and after the @ before the @ symbol and after the @ symbol so we have the perfect local name a domain name so now what we have to do is we have to fix the local name because any other errors are gonna be here at the periods and the plus symbols so first thing we'll do is just fix the plus symbol anything after the plus sign what can be ignored so we're just gonna get rid of that so if local name contains the plus symbol we're gonna do the same thing we just did above we're gonna get you know plus position is going to be equal to local dot index of the plus symbol snow in the position of that and then we're just gonna do local name is equal to local name dot substring of 0 to plus position because we only want the things before the we only want to keep what's before the plus symbol so this just resets our local name to the same thing with the stuff before the plus a little super easy right there now all we have to do is use the built in java method replace all periods we just don't we want to ignore peer it just says ignore peer it's pretty easy so we just reset local name now that we just have the beginning part before the plus symbol to local name dot replace all and the period is a special character so we have to use us we have to escape it with the double backslash here and then just replace all of the periods in the string with an empty string so that just gets rid of them and there we go now we have the local name correct and the domain name are correct we can just construct a new string so new name is equal to local name plus domain name you don't have to do this you can just do all this in one step I'm just doing for code readability and then we just add it into the hash step so unique emails to add new name and now all of these new names will be perfect we'll add them into the hash set as we loop through and the only unique values will remain in the hash set and then we can just only want the number of unique emails left so we just return unique emails dot size hopefully that made sense to you guys it's basically just knowing that hash that's what's going on here domain name email oh sorry about this and forgot a equal sign syntax error so you know there we go okay there works this problem is pretty easy it's just knowing that a hash that has unique values so that's just what hash that's our fill for whenever you see unique think hash that I guess we reconstruct it with the rules that were given just ignoring periods and removing anything after the plus sign and before the @ symbol we split it sign and before the @ symbol we split it sign and before the @ symbol we split it in two parts add them back together and then check for unique values so return the saw slash so that's it thank you guys for watching please check out my other videos thanks | Unique Email Addresses | groups-of-special-equivalent-strings | Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**.
* For example, `"[email protected] "` and `"[email protected] "` forward to the same email address.
If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**.
* For example, `"[email protected] "` will be forwarded to `"[email protected] "`.
It is possible to use both of these rules at the same time.
Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_.
**Example 1:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 2
**Explanation:** "[email protected] " and "[email protected] " actually receive mails.
**Example 2:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 3
**Constraints:**
* `1 <= emails.length <= 100`
* `1 <= emails[i].length <= 100`
* `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`.
* Each `emails[i]` contains exactly one `'@'` character.
* All local and domain names are non-empty.
* Local names do not start with a `'+'` character.
* Domain names end with the `".com "` suffix. | null | Array,Hash Table,String | Medium | null |
22 | so yeah as an egg-white here I do so yeah as an egg-white here I do so yeah as an egg-white here I do technically stuff on twitch and YouTube check the description for all my information yeah we do all the Wako problems and I got a big playlist so we're gonna check them out we got generate parentheses for some reason we missed this one even though it's very popular I feel like I did it on a bunch of other videos though given n pairs of parentheses write a function to generate all combinations of well-formed all combinations of well-formed all combinations of well-formed parentheses this is a really popular problem there's a million ways to do this to give you backtracking dynamic programming stacks like all you know just different ways to do it you can just use pointers you know there's different ways it solve the parentheses and it's usually a variation problem there's a little some different ways to do that they explain the parentheses but in this case we want well-formed in this case we want well-formed in this case we want well-formed parentheses and we're gonna be returning a list of them based on a number okay so we're gonna get a number right we're function takes in a number and it returns a list so what is the number is n pairs of parentheses so that's how many pairs of parentheses that we're gonna be returning right so if we have three as the number N equals three then we are going to return every possible combination of three pairs of well-formed parentheses and well form well-formed parentheses and well form well-formed parentheses and well form parentheses basically if we look at this example here we could see that well form parentheses means each opening parenthesis has a corresponding closing parenthesis so in this case this opening parenthesis Court has this corresponding closing one this opening one has this closing one and they're nested right so there's two types you get up nested or you could have next to each other right so these two are next to each other but they're nested in these outer ones right and that's fine this is these two are nested within this pair right and then there's a pair right here so as long as there's an opening and the corresponding closing with that opening that's fine there cannot be closing braces before opening braces that's not well-formed opening braces that's not well-formed opening braces that's not well-formed right that's gonna be incorrect it cannot look like this that is not how we're gonna be doing it here okay all right I think we understand so how do we do this it looks like the best solution to do this is backtracking definitely not the easiest I'd say stacks are probably the most just easy in general but you know we're gonna do backtrack it is one of the easiest ways to understand backtracking this is one of the easiest backtracking problems so I'm gonna just set up the template backtracking code so this is the template backtracking code you have a separate method called backtrack and then that's you know and then basically you have your usually backtracking involves a list and returning a list so what you're gonna do in this case is just set up your list we'll call it output array and it's just gonna be an array list basic array list boom and you return that output array after you call the backtracking method so you call the backtracking method and you pass it in your output array this is literally template code right you're gonna take in the output right here boom so we take it in right and what we're gonna do is our base case this is how it works and halt backtracking problems so we have some base case oops some base case some base condition some base case where we actually add something onto the list the output array so this output array will be adding some kind of data here and in this case it's going to be strings okay so we're actually gonna be adding strings in this backtrack problem so we're gonna do say back that backtrack current string this is still template code so this is the data type you're gonna be adding in the base case so we're gonna be adding current string in our base case will get hit this is a recursive function backtrack was recursive and when the base case gets hit we add a new string onto our output array and at the end of that would just write return right so this is all just standard template code the other template code is you're gonna be making dish decisions backtracking always involves decisions and you make all possible decisions in these recursive calls so what is the base case gonna be I guess base case is going to be while we're looking at pairs right we're looking at N equals 3 so all possible combinations so what we're gonna want to keep track of is the maximum number of parentheses we can have so basically what we're gonna do is if the current string is equal so this is the base case if the current string dot length is equal to max' max' max' times two then we're going to add our string onto the output array because that means that if the currents if max is three like in this case if the current string is size six that means there's three pairs of parentheses because there's two parentheses per pair so we just do max because that's the number of pairs times two to get the actual length of the string that we want right yeah so that looks pretty straightforward there now we just have to actually handle our decision so what our decisions gonna be based on well we need to actually handle parameters our max is gonna come from just n we need in our current string is gonna start as an empty string we need to handle our decisions and we're going to do that using variables open and close to handle the number of opening and closing parenthesis that we'll have so we're just gonna send in 0 and 0 because at first we have an empty string 0 opening 0 closing parentheses right and then we'll say okay if open is less than max if open because max is the number them gonna be the maximum number of opening in the maximum number of closing parentheses we can have so open is less than max which is 3 then that means we can backtrack we can call our recursive method with the output array we call it with the current string but we're gonna add an opening parenthesis 2 because open isn't at the maximum number of open parenthesis we can have yet then we're going to Inc we're gonna pass in our open variable plus 1 and then we're gonna just pass in the same closing variable we're not adding it closing here and then max so this is a decision that we're making so you hit you call all possible decisions what's the other decision well if closed is less than open because we have this condition if closed if we would do closed less than max 2 because we want to have the maximum number of opening and closing parentheses right but we do closes less than open because we cannot have closing parenthesis before opening parenthesis so there you go this time it's the same thing this is our other decision but you have that check because you can't have closing before opening so as long as closes less than open that means there's an open and you could have a corresponding closing one there so we had a closing one this time open stays the same and then we do closed plus one and these will do recursive calls and I'll do a walk-through of how this works so this walk-through of how this works so this walk-through of how this works so this should be pretty much it so these the string basic I'll talk about it one more time error cannot be applied to given types what is this so we pass in the output array which is the list of strings straight up within sorry we didn't add the parameters for those so we say int open and to close I have to redo this video because it's a little bit messy there we go so that is the solution for the backtracking solution great let me do a code walkthrough I wrote this out a couple minutes ago and let me just talk about it one more time so let's just think about it backtracking is where you have we have this list right and it's usually done with permutations or subsets or generating you know different kind of permutations or different get all possible combinations where our backtracking does that kind of stuff usually it's like two to the end kind of problems all right and basically this is how it looks every single time you just have your output data structure you call a backtrack method with some initial data and there's these possible decisions you can make so you have your backtrack method here you take in your data structure and you call these possible decisions right this in this case our possible decisions is okay we have this current string we have this empty string do we want to add an opening or do we want to have a closing to it right now and we always want to add opening before closing so you just do as long as opening isn't at the maximum number of opening parenthesis we can have because we can only have up to a certain amount of pairs then we add an opening and as long as closed is less than open because we can't have closing before opening parenthesis then we add a closing brace we increment these counters and we do these checks just to make sure we're not going out sounds like the openings less than max closings less than opening and we just check we the string will always when it gets added to that output array be the size of max times two that's exactly what we're aiming for right because we want this number of pairs of parentheses right so three number of pairs of parentheses gonna be size six string every time so we just do a check okay is our current string at the maximum length times two and we could add it to our output array and we do this and if you go through the test cases here I have this big thing written out right so let's look at a test case of size two so n is equal to two right basically well I have it written out so I have all the variables right now current is set to zero is set to an empty string this is our output array we're looking at n is two right that's what we hit pass in our max is two because we send it we take in max as a parameter and we pass in 2n as max right so the max pairs we could have is to open and close start at zero so is open less than max that's what we're checking right away is zero less than two yes it is so you do a recursive call and you do the string plus an opening parenthesis and you increment open now this is all recursion inside of there the other call after that is close less than open false because zero is not less than zero at this point okay great we're inside that's this whole first recursive call doesn't even get called so this never gets called initially on there now we're inside of the recursion right so we're inside we got now open is one so we do another now we have these methods again inside of the recursive call because it does everything over again okay it's one less than two so it's another recursive call in there and you add another opening so this is double openings and you can see where that gets goes headed and then close is close less than opening yes zero is less than one inside of the recursive call and then you do the opening and then the closing parenthesis and then it's another you know and then it keeps going in the recursive call I don't want this video to go on too long so maybe you could pause and like look at all of the stuff I planned out but basically there's recursion inside of there so it was opening less than max yes it's one less than two so then you add another opening and then eventually it's another recursion down here is two less than two so that's false in that point and then it closed less than open is one less than two yes so it ends up being this open and closing opening closing which is one of the answers and then there would be deeper recursion in here which would end up being I don't even think I wrote all this out open close and those are the two for the two so maybe pause that and look at it that was just a walk through if you walk through even just N equals one it'll help you understand this is a little bit different than backtracking because we're not doing we have these conditions here which are a little bit unusual to backtracking but so it kind of stops us from actually going backwards all that much but yeah that's pretty much it for this problem let me know if you have any questions backtracking problems are probably some of the hardest to explain as well as dynamic programming but you know the template code is essentially you have a base case you do all these decisions and when the condition gets hit it gets added to the output array and returns and eventually you just return the output array after all the stuff it's usually kind of slow compared to other algorithm solutions so let me know if you guys have any questions about this let me know if the solution I give or the explanation I gave kind of suck I didn't feel perfect about it here but I felt I don't know I feel okay about it but not that good I don't know I'm gonna do a bunch of backtracking once so check out for those maybe they'll be a little bit better in the future so let me know what I think let me know if you understand please like and subscribe and yeah thanks for watching see you in the | Generate Parentheses | generate-parentheses | Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_.
**Example 1:**
**Input:** n = 3
**Output:** \["((()))","(()())","(())()","()(())","()()()"\]
**Example 2:**
**Input:** n = 1
**Output:** \["()"\]
**Constraints:**
* `1 <= n <= 8` | null | String,Dynamic Programming,Backtracking | Medium | 17,20,2221 |
61 | hello guys welcome to another video in the series of coding let's do the problem which is called rotate list so given the head of a linked list you have to rotate the list to write by k places let's try to take an example to understand this suppose this is a linked list that you have so let's say k is equal to one what are you doing you are rotating all the elements by one places right and then the last element will come here so what will the linked list become one two three four five six and the last element seven will get connected if k is equal to two what will the linked list become again you will shift all the elements by one places and then the last element again shifts so what will the linked list become 1 2 3 4 5 and then you have 6 7 and then 7 will get connected to this okay so if k is equal to 2 this is your answer now let's try to solve this problem considering this case k is equal to 2 right let's try to solve this problem using this example so what do you have to achieve let me write it again so uh we have the linked list 1 2 3 4 5 6 7 for k equal to 2 what do you have to do for k equal to 2 you have to get 1 2 3 4 5 here ok so this block has to come here 1 2 3 4 5 has to come here then you have to get this remaining block 6 7 at the front once you got this block you have to connect this block now you have to connect 7 to 1 okay so what are we doing 7 is what 7 is the last element and one is what one is the first element so basically what are we doing one is basically head right so one is head and seven is let me write last note okay last element so what are you doing once you make these blocks right one to five and then you have six to seven after which you are connecting seven and one so basically you are connecting the last element to the head okay so this is the first thing that we want to do first we have to get the last element then we have to get the head and we have to connect last element to head so let's go step by step okay so let's make this connection first of all what are we doing let me repeat once again we know k is equal to two that means two elements have to come at the front five elements have to come at the back and the last element which is 7 has to get connected to the head 7 should get connected to 1 so let's do one thing let's try to just do this step then we will see the further steps okay so let me start basically what you are going to do you are going to find out the last element how do you find out the last element finding out the last element is very simple right we will start with the temporary variable okay and then we'll keep moving the temporary variable till what so let's move our temp so temp is equal to times next we will keep moving our temp we will keep moving our time till we reach this when how do we find the last element so we know the last element when the next of temp is equal to null that means we reached our last element okay that is a simple line of code basically if you have seven elements right how many times you will change temp one two three four five six times if you jump you will be able to reach the last element okay so if you have seven elements six times you make the jump you move temp is equal to ok simply how do you make the jump just give the simple line of code temp is equal to times next okay this simple line of code you will give six times it will run so you will reach the last element how do you know is the last element seventh next will be equal to null okay so let's write the code then it will be much more clearer we want to just reach the last element okay so let me write it so reach the last element why do you want to read the last element because when we rotate by k places what is happening last element is getting connected to head so what is happening in our example seven should get connected to one this is what we want so for that we need to find the last element we already have the head once we know the last element we can just connect seven and one we can connect the last element with the head okay that's what we want to do so how do we reach the last element so very simple just i trade the link list okay so reaching the last element is very simple just iterate the linked list let me give a variable temp is equal to head so while temps next is still valid what we'll do temp is equal to thames next okay if you simply give while temp then what will happen this will keep running unless temp becomes equal to null but we don't want that we want to make temp equal to the last element okay so that's why i am giving this condition so what will happen temp will become equal to what temp will become equal to 7 and this will exit the loop when temp is equal to 7 because 7th next is null right so it will not enter this loop when it sees that the next of 7 is null okay so temp will point towards the node which is having a value of 7 okay now what you want to do you have got your temp which is the last element now connect this okay connect this and make its next equal to head so what are we doing we are connecting seven to one which is what we wanted right which is what we wanted to connect seven to one so i have connected by giving this line okay now while we are doing this what we can do we can also see how many times we are jumping how many times are we jumping we are jumping six times right so why is this useful let's see why is that useful okay so we know we are jumping six times so n is equal to zero and if we jump six times we will reach the last element now how will we use this n okay let's see now what do we have to do next what have we done till now let me write it again so till now what have we done we have a linked list one two three four five six seven so what we did now we reached the last element we know that last element was pointing towards null so we broke this connection and we made the last element point towards one so currently we have achieved this but what do we want to actually achieve if we want to rotate by two places what we want to do we want to achieve one two three four five to get connected and we want 6 7 to get connected they are already actually connected we have made this connection 7 is connected to one okay this part is achieved now we also want to achieve the next part what is the next part is we want phi to point to null okay second step is now we want five to be the end of the linked list currently seven was the end of the linked list but we connected seven to one okay first part we have done but the next part is we want to get phi attached to null okay because the link list should end after phi okay this is what we want so how will we achieve this see so we want to reach the node which node do we want to reach the node 5 because we want to reach this and make its next equal to null because when we rotate by two places v d the last node should be equal to five and its next should be null so how will he reach five it's very simple see if k is equal to two right if k is equal to two that means there are two nodes in the beginning and there are five nodes in the end okay if k is equal to two that means there are two nodes in the beginning there are five nodes in the end how will you get five nodes in the end so very simple you start again let's say you start a temp okay you start a temp you keep moving the temp how many times you will keep moving the temp if you keep moving the temp right if you keep moving the temp till you reach this value right till you reach five so one 2 3 4 times you should move the node temp you will be able to reach the node 5. why do you want to reach the node 5 phi is the ending node which should be connected to null we want to reach this node 5 because we want to connect it to null okay currently it's connected to seven currently this is connected to uh to six currently this connected to this block six seven we want to break this connection i think it's become very messy but uh let me try to see this is the connection that we want to break this connection and we want to connect phi to null okay so what we are doing we are jumping temp one two three four times if we make temp jump by four times and we reach this temp here so we will reach the ending node five so how are we going to achieve that so we know what is our end n is equal to 6 now what is k is equal to 2 6 minus 2 is equal to 4 that is the number of times you want the temp to jump okay so if you jump 10 by 4 times you will reach the node 5 which is the ending node okay so that's why so what we are doing n is equal to 6 right n is equal to 6 so what we will do n minus k ok this is the number of times you want to make your node jump so let me write jump okay this is the number of times 6 minus 2 is equal to 4 in our example that means if you make temp if you make okay this temp which is starting from the head if you make it jump four times what will happen you will reach the ending node which you want okay so let me give the condition while jump okay let me give the condition so um currently uh what is happening is let me give again let me give temp to point towards the head okay temp is starting from the head again so temp is equal to m star next and jump minus so these many times if you jump where will temp point towards stem will point towards the node phi why do you want the node five you want to make its next equal to null okay so temps next should be equal to null okay very good now if you make temps next equal to null simply okay what will happen if you make the node 5 its next point towards null what will happen you will lose this connection right so you will lose this connection but we want this connection because this 6 7 this is the connection that we want if you simply make it null without saving this connection you will lose this connection 6 7 we want 6 7 because 6 is the head of the linked list that we want finally in the answer okay so before making this null what we will do we will also store this is going to be our next head right so this is what we want to return so list node star okay ah the head that you want to return so let me just call it return this head okay this is thames next because what is this five is next is what six right so you want to return six is the head so before making five next equal to null currently the next of 5 is equal to 6 right this is the return head that i am declaring return the side because we want to return this head so this head i will save in a variable called return head and what i will do i will just save it in a variable return head so this is pointing towards six then i will make them next equal to null so when i do this what will happen this connection will break off and files next will point towards null okay i have already stored this okay that's it so i have achieved whatever i wanted to achieve okay now what i can do i can just give return head okay that's it this is a simple code now it will not work for all the test cases first of all let's see if it's working for the given test case see it's working for this test case now for which test case will it not work just consider this example too right now in this case what are you doing you are rotating by four times but the length of the linked list is what length of the linked list is only three so if you are rotating by four times what are you doing it is same as rotating by one times right so what you have to do one simple thing you have to do k is equal to k mod n that is what you have to do because rotating by four times is same as rotating by one times okay when your size of linked list is three okay so k is equal to k mod n will ensure that always uh you your number of rotations never exchange the size of the link list okay now let's run the code and see if it's going to work so let's submit and see if it's working for all the test cases okay uh that uh i understand why uh why it's not working because here n is what n is not the size of your linked list n is six right n is six but the size of the linked list is 7 so we should give k mod n plus 1 because uh n is 6 but the size of the linked list is 7 so 6 plus 1 is 7. so the size of the linked list should be the size of the linked list is n plus 1 but here we give n plus uh and n became only six so this should be n plus one now i guess it should work let me sum it and see it should work for all the possible test cases okay so now it's not working for the empty test case why is it not working so we should uh because this is not valid right here it's giving error so we can also give one base test case what is the test case if your head is null right so let me give the test case if your head is null or k is equal to 0 in that case you can return head because the no need to do any rotations if k is equal to 0 means no need to do any rotations if your head is null also that's it's pointless okay so it's working for all the test cases thank you | Rotate List | rotate-list | Given the `head` of a linked list, rotate the list to the right by `k` places.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[4,5,1,2,3\]
**Example 2:**
**Input:** head = \[0,1,2\], k = 4
**Output:** \[2,0,1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 500]`.
* `-100 <= Node.val <= 100`
* `0 <= k <= 2 * 109` | null | Linked List,Two Pointers | Medium | 189,725 |
1,402 | Hello guys morning zinc etc co dot problem nadu solution special in this problem difficult and date of all the is reception level officer and distress and what mintu time and essence of him and every day take bollywood talk time great prepare show is virat and you Can give divine one to three layer and M2 respectively with me all decisions to get jhalar like time profits of light and appreciated and bring to front maximum likes and custom of light and opted for best possible after dispute preparation for dipping and features can be prepared in A Product And Thick And Discard Certificate In Which I Am Subjective So Different From Latest Crops So Edison Electronic 1250 Add Order And Speed Solution Will Be 1250 Add Order And Speed Solution Will Be 1250 Add Order And Speed Solution Will Be Difficult For Citizens Should Take A Look At This Problem Number 400 From Development Viewpoint Repairing Biscuit First Giving Taste His Second Hand Due Respect To His Sacrifice For Preparation And This Situation Order In Which Is Preparing To One Thing Which Cannot Be Set Up At A Distance Heavy Fighter Satisfaction Elevated Later Wash Combination Feedback Him Like Never Define Number And Given Date Will Be Pad First Should Be That You That election like a writers and top up small number of his adopted such things will be doing this website and satisfaction on twitter hua tha 210 satisfaction return gift doesn't mean that you will find a debate on Tuesday and defense staff and dissatisfaction among all Is well you can max mx100 it is the president problem vikas they can reduce that to 9 the electrical shop so let me show you how candidate who letter suppose i am defining speed that i kamal jeet ke member i represent up to how much dos is Being selected and issues and presents how many distance of the solver answer itself detail should that can be reduced available products because of this proposal and to fight decision z is handset selection in few cases it is rs is have interacted and come there is different and Suggesting A is show in case if this has been selected then that person - one area plus person - one area plus person - one area plus satisfaction S to Z which is the time that taken together FIS 12345 Sez Pe Fasal Moment Page80 Place In Fact Were So Is Method Bhavya Jatin Case In K Sp Sided Picture And When E Decided To Have Not Been Shifted Half Velvet Just Dpi Famous - One Is Related To Z - One Is Related To Z - One Is Related To Z Minimum Set Forth Divya Kit Hai to ki in order to calculate spear duty matrix a week and make user today rate the soul is present state bank th10 president and floated develop office tpi ko me this method limits of interior soya manager places 500 meters patient care for its quality and a It happened that I'm using one plus one year because you will be getting strong with a ring of disbelief and from icon 202 miles away towards betterment today met like it lusted for his nice 29 minutes song chalu motu patlu 25000 better decided minus one is pressure nikal poochhi thi hain to in this case very * hain to in this case very * hain to in this case very * thanks for possible sudesh tvs i to maje lo e will be e i maths of a dispute positive a 102 a specific want to time management chairman s one plus change with time taking and substance akram the Five minutes ago ki pawar db5 maine se one comedy aa hai third wicket 1530 e sucked and just in case a minus one is not contained from painters 21.5's possible date aa jaaye deposit hai jo after 10 long pieces accepted as having and value of a The fifth and what will you to kids maximum value from laptop to consider the maximum value of guest cases related to SD card and a debit so let's make this a who is Maxwell that in no way to treat for varicocele phone silent be student life Bus stand is a stand is their vestige panic my is residents maxwell which has dual a pig to tp link wifi i slept that bihar got quality max value monitoring of the web the latest ai instantly transform into sports that 24 nodal influential english dictionary App the basis of a special now what do you think specific latest you batting a 200 picked sub | Reducing Dishes | count-square-submatrices-with-all-ones | A chef has collected data on the `satisfaction` level of his `n` dishes. Chef can cook any dish in 1 unit of time.
**Like-time coefficient** of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. `time[i] * satisfaction[i]`.
Return _the maximum sum of **like-time coefficient** that the chef can obtain after dishes preparation_.
Dishes can be prepared in **any** order and the chef can discard some dishes to get this maximum value.
**Example 1:**
**Input:** satisfaction = \[-1,-8,0,5,-9\]
**Output:** 14
**Explanation:** After Removing the second and last dish, the maximum total **like-time coefficient** will be equal to (-1\*1 + 0\*2 + 5\*3 = 14).
Each dish is prepared in one unit of time.
**Example 2:**
**Input:** satisfaction = \[4,3,2\]
**Output:** 20
**Explanation:** Dishes can be prepared in any order, (2\*1 + 3\*2 + 4\*3 = 20)
**Example 3:**
**Input:** satisfaction = \[-1,-4,-5\]
**Output:** 0
**Explanation:** People do not like the dishes. No dish is prepared.
**Constraints:**
* `n == satisfaction.length`
* `1 <= n <= 500`
* `-1000 <= satisfaction[i] <= 1000` | Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0). Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer. | Array,Dynamic Programming,Matrix | Medium | 2192,2193 |
44 | uh today we're gonna be working on need code question number 44 wild card matching given an input string s and a pattern p implement wildcard pattern matching with support of question mark and star so the question mark matches any single character whereas the star matches any sequence of characters including the empty sequence so in this example s is equal to a and b is equal to a so the answer is equal to false and a does not match the entire string in the second example s is equal to a and b is equal to star that is also true as the start match is una super third example c b and question mark and a which is equal to false so yeah basically as the rule says we're gonna be following we're gonna be trying to implement all of them and this is gonna be done using uh using recursion so in at first we have the s pointer and the p pointer both of them pointing at zero then we have a start index equals to minus 1 and a point 3 equals to minus 1 okay then while the s pointer is less than equal to y well we are actually while we are trading through the uh the whole string and our pointer is within that uh string if the okay the pointer we are at is less than the and the other one we have to do that like if the for the pattern pointer is less than the p length and uh the pointer and inside the basically we are saying that at the same point if they are equal if they are exactly equal definitely we will just kind of continue or just we don't have to worry about anything everything is passing both of the characters are the same so that is an easy goal we're just gonna continue that or we the other thing is what if the pointer is equal to a question mark right and the point is equal to the question mark even then uh it means that we can actually say that okay they are equal so we're gonna then increment both the string point and the button point otherwise what we're gonna be doing is like we're gonna be saying is like if the pointer is within the range for the pattern and the value at the pattern is equal to a star right in that case uh we know that we're gonna you make use of the start index and the pointer so first of all we're gonna say that the start index is equal to the uh the pattern the p pointer okay so that we remember that where did we see the star and the pointer is gonna become equal to the s pointer okay and the other thing is that we're gonna increment the uh the p point so basically the s pointer is staying where it was only the p point is getting incremented and now we want to check that if the star this is a star index just our index is equal to minus 1 then that means that we can return false we can say it is it can't be true otherwise the last thing is that if the p pointer is equal to the star uh star index plus one otherwise we're gonna make the pointer for the pattern equal to the star index plus one and the s pointer equal to the pointer plus one and the point is going to become equal to the string pointer and in the end if everything passes we're gonna return true but just before that uh in the end there's a personality check that our index is gonna start with the patterns pointer and it's gonna stay within the p string if the value of the pattern is not equal to star we're gonna return false otherwise we are returning the true so yeah basically over here first of all uh sorry it's not a recursive it's an iterative uh way of doing it we're not doing the recursion here uh recursion would be another method um of actually doing this thing but we have done it iteratively and uh basically we are just uh pro program the uh all the different steps they ask for the file card matching so it did pass and now yes if you look at the last step here basically the pointer we because the while loop is just for the string there is a possibility that as pointer has like where we are out of the we have hydrated the whole string but still the p pointer has not been finished yet so there is a possibility for that so that's why these line number 30 to 34 is basically checking that uh basically it is checking that uh if we still have some values left in the p string we're gonna be returning false so that's the last insanity check we had so let's run it for all the tests yep and it passed all the tests | 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 |
329 | Jhaal Ajay Ko Hello friends welcome to my YouTube channel Teaser CEA Today they are going to solid problem More than 300 problem name is the longest in increasing path in matrix the problem seems to be heart problems between the medium and heart bits note dry ginger 9 medium Bigg Boss Problem Statements Similar Dolata Problems Which After You Need For The Number And Five From The Sources Destination Problem Solved Problems Treatment And Research Center Should Be Written Language Starting From Delhi Police To That Element Which Is The President Subscribe Now To Cash Details In This Book Has got into one month ago and continued to modify the small element and oil we don't have to dabodia until we have crossed Pandey so we can free so how can we do it like we have Chaggi matrix let from 125 to 4630 I have to start each mode from a specific playlist, hey traveling and how long can I keep traveling there, I will keep getting bigger, we reached here from here, we could have brought from here also, so we will add edifice from here to more from here and add to both of them We will also take it into this so that when we come again from this location while doing a table, we will know what we get from here onwards, how much Navlesh Pathak does because look, there will be time problem overlap because when I start Monday, I will spend Monday somewhere else. But theirs or I will hide it and then I will return from there, then I have the post of some teacher that education further does not make any belongings pregnant, see it works, can go to the temple of education, last but that means can especially the body is small can be known. And anyway, if he cannot go up to the next third, then dip maintenance will be done along with it and we will use it so that if tomorrow we are in the same position, then we will know how much more office we could get from that position. Let's cut quickly come that Bhojpuri every to variable eminent today mission for the matrix images to make this planet and request matrix 80 daughter length le deutsch ki no real estate answer pimple contain very place bear ki insan sir ko maximum karna toh interest and How much can be done in minimum, we install democracy in minimum, it has to be maximized, after that comes visit, we make boolean type visit here on a request, we are bullion as a member and next, we make cute about that too, seams. Shipra of Hindi PM's paper interior because in this we will check whether it is tap or not because if we make morning curve then default value is toe, if we make capital ampere then money default value is smell that this amendment that after that there is sunlight. The point is request to sir phone point is request to sir roy is letter mi plus app hai aur intaj try roz cent and z plus ki after this why will the answer go answer is question math dot maximum ho ki they sansad ko me bf x d By using fashion type, visit it and now once, we will start from here, so there is no value before this, compare it, then call it - - - - - - no value before this, compare it, then call it - - - - - - no value before this, compare it, then call it - - - - - - - Verb - and in the last turn on that here also this method Great do private institute is difficult-1 Hum private institute is difficult-1 Hum private institute is difficult-1 Hum previous value first kitni vyatipat hi it will take we retail pack hum Columbus se zara type matrix hai the matter poems and big billion type hai ek budhiya revisited and also takes interior type today are hindi ki Entry conditions in nine What if disease maintenance becomes zero then go then our column but becomes zero or our stop and greater than become matrix start land from net minus one or a room column greatest me from matrix or WhatsApp In all these cases from length minus one, I will give the condition of 1000 villages. Then it comes that if it is Britain, we can check the validity that if there is something in BP then return DP it is O Ma in Hindi Peeth R Ko Mixi Snow Devotional if in DP. It is not codinal then we can check the cancel of the record in the beginning that if it is visited or at that position of the matrix which was the value of R to Christ, what should it be Bujlu strain or equal to that. We want feminine gender, we can't take them one time, we can get 141, we want only you after Vansh, then equal to the previous value, top seed return 087 of Om Shri Nandishwar, who went and calls, four very brahmins take your experiment. It happened, I became brown, I turned left for the shell and right, ok, right side, call for the moment, there is talk of media, celebration, when will we change the previous value, from whom will the current Baloch be ours, that after this, everything will go away in time. Syria's net will go and if you know then you mean in Kaya Ro me minus one melted can visit Android DPO gone and shampoo for remaining free from the A variable Here also we will just change the deductions Do dipna do - from one - from one - from one Assessment and lunar hai toh roz day scholar minus one right hain to go to roz justice column plus one quote I one thing and when we come, what am I to do first of all Existed Markar why did he visit his mother on that point and return backstreet Let's do that he has to fold the widget, why not fold it and I have found out from the technicalities how much is the long waiting pass, if I do n't force it then it will travel in one go and then after that it will not work again. You will keep getting returns from the visit. Daily what we have is return last declared fit in DP and on the machine what will be the rally to the value death in method mixer is method maximum of again e is to take maximum with it that I dot maximum officer up of wheat which mixer In Maya this chapter right and last with him left and finally question why question is the point in which he started in one count go to account then pronounce you New Delhi ok is regular ok semicalculus is meeting 8th location Jhala ok Here the equation is meeting that 515 Kumar takes a look, I break the maximum objective, okay, you, it was a mistake, we have time, got the DP checked in advance, a chairman will check the DP first, then if tomorrow any coordinate I know that while entering from here, it will not be there in the DP because already once our loop had started due to this quiet, now only Pina will match its next value. If you have made small or big deposits, then get that checked first. It is important that we do this sequence later, if we are feeling dizzy then it is wrong, this is why ours is the longest fiber while it is four because they will check it without returning it from DP, then we will keep the duty for later, now let's make friends. So we will give an example on this, once you see the summit, there was loot on this occasion, so if you liked the video, please comment, subscribe the channel, thank you. | Longest Increasing Path in a Matrix | longest-increasing-path-in-a-matrix | Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`.
From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).
**Example 1:**
**Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[1, 2, 6, 9]`.
**Example 2:**
**Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.
**Example 3:**
**Input:** matrix = \[\[1\]\]
**Output:** 1
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `0 <= matrix[i][j] <= 231 - 1` | null | Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization | Hard | null |
1,793 | Hello guys welcome to code fix otherwise so let's start now date code problem i maximum score of good all so let's get into this problem so today's problem is a little tricky to understand. That problem is very simple to solve, so if you listen a little carefully, in this question you must have given yourself an array and a value. Now what do you have to do? Find one such answer from this array. Whose value of this formula should be maximum and we have to return the same maximum value, this is our simple question, now once we see this formula, then what do we have to do in this formula? You have to extract the minimum value from the one you have chosen and you have to substack both the positions from which you have chosen in the morning and add plus one inside it, then you will multiply these two values. So your formula will be created, okay, and you have to tell yourself which of your items are there for which the value of this formula will be maximum and you have to return the same maximum value, this is your simple question, now you must be thinking. That all this is fine but what is the use of this here, so this is the work of this here, there is one more condition in it that whatever position we take in the morning, this position must come in it, so whatever we take in the morning We will take this 'Kth' position should come inside it morning We will take this 'Kth' position should come inside it morning We will take this 'Kth' position should come inside it and from that, the maximum value of our formula should come and we will return the same maximum value. This is a simple question, so if we look at this question with this example, then this In the example, I have given this one to myself and this is my cape. Now, which is my third position, this is my zero position, first position, second position and third position, meaning this is the seven, come in your own hands. You should come and then tell yourself that if you apply this formula in your morning then who is the person for whom the value of this formula will be maximum and you will return the same maximum value, okay then solve it one by one. If we see, to solve this, first of all we will keep only one value in our sabre, that will be the value of Apna, then what will become of our sabre? Surf in our sabre, we will have only one value, that will be s. Now, what will be the starting position of our sabre? Also, it will be equal to k, meaning it will be equal to k and its ending position will also be equal to k and it has satisfied its condition that whatever is i is also equal to k and whatever is h is also equal to k, okay. So once you find out the value of this formula then what you have to do is you have to find the minimum value of your morning. Now there is only one value in your morning then that will be its minimum value and if you ask this question If you calculate and see that the value of your last and first is the same then your 3rd and first minus will become zero and you will be left with only one, then what will be the value of this formula of yours, if 7 new equals to 7 then what will you do with this once you get the result? Let's get it stored in I that after this, if we find any such sub-section, then for this we are find any such sub-section, then for this we are find any such sub-section, then for this we are getting a big value from this formula, then what will we do, we will update our result. Okay, so our first sub-section is Okay, so our first sub-section is Okay, so our first sub-section is done now. What will you do in your next sub-section? We will done now. What will you do in your next sub-section? We will expand our sub-section a little, now we will expand it like this expand our sub-section a little, now we will expand it like this expand our sub-section a little, now we will expand it like this because we want the minimum value of our formula to be a little bigger so that if the value of this formula becomes big, what will we do in both directions of our sen? If we look at the value below, we have two values, three and four. Okay, then which of those two values will we keep in our sub array? Obviously we will values will we keep in our sub array? Obviously we will keep four in our sub array because our minimum value should be a little larger. So that if your minimum value becomes large, then the value of your formula will also become big. Okay, so along with intake in the morning, we also keep four in our morning. Okay, then what is the starting value of our morning? The starting value of is still three and its ending value has become four. Okay and what is the minimum value of its morning? The minimum value of its morning has become four and if we calculate this portion then our j4 is and i3. So the subs of both of them will become one and if we do our plus one inside it then it will become two, so the value of our formula is 4 * 2 which is value of our formula is 4 * 2 which is value of our formula is 4 * 2 which is eight which is greater than seven, so by updating our result. OK, now we will go back to the same formula. Now what is the value of front and back of this saber? 3 of F. If there is obviously a five out of these two, then what will we do? We will choose our five and add five to our sabre. Okay, now your starting value is still the same and what is your ending value? Your ending value has become five and what is the minimum value from inside it? The minimum value from inside this is four and if you have this portion. If you calculate j - aa, how much is j calculate j - aa, how much is j calculate j - aa, how much is j minus eight, then if you add plus and within it, you will get 3, then 4 * 3, plus and within it, you will get 3, then 4 * 3, plus and within it, you will get 3, then 4 * 3, how much will 4 * 3 become, then you will get how much will 4 * 3 become, then you will get how much will 4 * 3 become, then you will get 12, so update your result to 12. Okay, now let's go back to the front and back values of our saber. Now there is front and back values of our saber. Now there is front and back values of our saber. Now there is no value left behind, so what will we do? If we add the front value to our saber, then three has also been added to our saber. Now what is your starting value left? Now your starting value has become to and your ending value is still there. Okay, now what has become the minimum value in your morning? What has become the minimum value in your morning? And your ending value is still there. If you calculate the potion, then j minus a will become 3 and plus and will become 4. Okay, so 3 and 4 will return 12, which is equal to your result, so we will not update our result, then what will we do, we will return one more. We will add the value inside our sub-bar add the value inside our sub-bar add the value inside our sub-bar which will be four, which is still our minimum value is still three, our range has been updated, the starting value has become our one and the ending value is now It is also five, okay, your minimum value is three now and what will you do with it, if you multiply 5 - 1 4 by 1 5, what will you do with it, if you multiply 5 - 1 4 by 1 5, what will you do with it, if you multiply 5 - 1 4 by 1 5, then how much does 3 * 5 then how much does 3 * 5 then how much does 3 * 5 become, it becomes 15, which is greater than its result, hence your result. We will update it to 15. Okay, then what will we do? We will increase our range again and will also add one in our sub area. Now what is our range? Starting value is zero and ending value is five but now our What has become the minimum value of Saberi? It has become one. Okay, and what will we add inside it? 5 - 0 and what will we add inside it? 5 - 0 and what will we add inside it? 5 - 0 5 + 1 6 So what is your answer? Your 5 + 1 6 So what is your answer? Your 5 + 1 6 So what is your answer? Your answer is six, which is much smaller than 15, so Your result should be 15 only and 15 is your answer, that means both your question and approach have understood well what you will do, you will try to make all the priority first of all, keep only the value of your a in it, which will be Once you find your value from it, you will see your answer. Whatever the answer is, you will store it in your result. Then you will see what is the front and back value of your value. We will create two points for both, which will be The P value will be larger, we will add that value to our sub-array and our sub-array and our sub-array and update our range accordingly. Okay, then we will extract our minimum value from that sub-array Okay, then we will extract our minimum value from that sub-array Okay, then we will extract our minimum value from that sub-array and multiply it by whatever is there in our sub-array. It is our sub-array. It is our sub-array. It is fine with that value, then if whatever result you get is greater than your previous result, then what will you do? You will update your result and do the same for the whole morning and whatever your answer will be in the last, you will update it. Will I return it? This is my simple question. Once you see its coat, I have done something new for its coat. This time I have used do by loop because I have not used do by loop for a long time. So, this is a question in which you can use your for loop. Before this, what did I do? I have created a minimum inside which we will see the minimum of our morning. What did I do inside that? Now I have given my key value i.e. the key Now I have given my key value i.e. the key Now I have given my key value i.e. the key of my array. I have kept the value because there is only one value in my saber, that is my kth value, so what I have done to it is that I have stored it in my minimum, my i means my starting value, my starting position will also be equal to k. The ending position h will also be equal to k and its result will be its kth value in that case because what will happen inside this is that the minimum value of k which I see is also its geth value, let's assume seven is okay and Along with that, we will also multiply our one by one because if our starting and ending positions are the same, then both of them will be minus zero and only our one will be left inside it. Since 7 * 1 is obviously the same, we will be left inside it. Since 7 * 1 is obviously the same, we will be left inside it. Since 7 * 1 is obviously the same, we will multiply our one with any one. If you get the same answer, what did I do in my result? Apna names off means I stored the value of Apna. Then what I did was I used my do by loop. Inside this I first said that if Apna I means this starting position. is also greater than zero and your ending position is also smaller than the size of your array, then what will you do, i.e. the then what will you do, i.e. the then what will you do, i.e. the position of i - 1 and the position of i - 1 and the position of i - 1 and the position of t i - i.e. one in position of t i - i.e. one in position of t i - i.e. one in front and one in the back of your array. We will compare the values to see which one is bigger. If the value of our starting position is bigger then we will make our Aa minus that means we will take the value of our starting position as our left otherwise we will make our J plus because our J Well position means we will give the value of ending p, ok then what will we say that if this condition is not true, if there is a but value, it has already exceeded its meaning aa if equal has become equal to zero and j now. Apna is small, size of numbers minus v means size of our array - 1, so size of numbers minus v means size of our array - 1, so size of numbers minus v means size of our array - 1, so what will we do, we will pick only the last value because our starting value is already within its sub-array and if the already within its sub-array and if the already within its sub-array and if the opposite is proved. That Apna J means Apna ending value has reached the size of Apna array but Apna starting value is also left so what will Apna do, Apna will take the starting value. Ok then what will Apna find in AA? We will find the minimum of sabar, it is okay that whatever is in our minimum is our minimum, our number of a is minimum or our number of J is minimum, whatever is the minimum, it will come in our minimum, do not come in the minimum of our sabar. Okay, then we will get our result. What will we see in our result whether our previous result was increasing or this formula of ours is bigger, whatever is bigger will be included in our result and this will happen throughout the morning. And in the end we will return our result, this will be our simple solution, once we submit it and see, then yes it is getting submitted, that means it is a completely accurate solution, you can consider it absolutely, hope you must have understood it. Got it, if you like the video then like the video, subscribe the channel and if you have any doubt then please mention it in the box, we are always present to solve your doubt, thank you so much thanks for watching, have nice day | Maximum Score of a Good Subarray | minimum-moves-to-make-array-complementary | You are given an array of integers `nums` **(0-indexed)** and an integer `k`.
The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`.
Return _the maximum possible **score** of a **good** subarray._
**Example 1:**
**Input:** nums = \[1,4,3,7,4,5\], k = 3
**Output:** 15
**Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15.
**Example 2:**
**Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0
**Output:** 20
**Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 2 * 104`
* `0 <= k < nums.length` | Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications. | Array,Hash Table,Prefix Sum | Medium | null |
54 | Hello friends, welcome to the new video, question number 54 Spiral Matrix is a very famous question, this question is a very famous question, this question is a very famous question, this question is a medium category question, Spiral Matrix Too, you will also get similar code in the late chord, do one question in ninety percent, both will be made in the video. I have understood his question. *Matrix has been said to have two elements. *Matrix has been said to have two elements. *Matrix has been said to have two elements. You have to print all the elements in spiral order. It is okay if you want to print all the limits of the matrix and then it is very easy to print it by applying a loop but in this case. If you want to print a spiral, then take a quick look at what is the spiral matrix. You are seeing that the circle is getting smaller and smaller inside, circle, the circle is getting smaller and smaller inside, this is the spiral matrix, okay, this is another example of spiral matrix and this graph is an example of spiral matrix. Okay, don't waste time, this is a bit boring question but it is a famous question which can be asked in the interview and all these are very common so you will have to do this once. Okay so how to print spiral matrix so if I Let's do some subjects and then we will start the food. Okay, so if I go spiral, you saw that first you have to print the first stop, so in this case, I should print 123, this is easy, even we can think about that and you. I had also seen that after 36 bomb crops, we are coming down this last message, till 3693 are printed in it, then these 6 and 9 would like to come down, okay after that we came here, now I will go reverse, meaning to make a circle. Neither holding the last row, I have come to 9 inches, now I will increase by 80 seconds, it is 876, so you will see, now after that I will sit up to complete the circle, then this is 747 and the throw is done, I have printed it, after four, I am now up. I am not going to reach the circle, I have become smaller, first I have done low process, then I am getting right moonlight in seconds, then I will do more sir, then you have made some observation that this disease was being talked about, Veen Hamro. I was going like this, then you must have seen that we are processing this column, okay then you must have seen that we are processing this column, then we are processing the last diseases, then you must have seen that we are processing this column, so this All you have to do is stop others, rotate columns, then column, so if you have double to access one boil, you have double to access four for loop and you can update five integers of the count, then you This question is not You will be able to do it and this is a very easy question. I have done it three-four times. I have doubts about it. Please I have done it three-four times. I have doubts about it. Please I have done it three-four times. I have doubts about it. Please do it in August and give a final answer. Let's understand. Let's come to the code. Okay, look. There are five interiors. Tell us yourself. He said that there are directions. So see how you will start, take the new left, this is your left column, okay, tell him that we are on the left column, and tell him that we are on the right column, okay, tell him that we are this top rope, okay and Say in the same way that we stop this bottom, if I say bottom then either you understand who is being talked about, if the word bottom is coming, that top is big then I am talking about prop rooms and left right if we If you talk, then you say that let's talk about the columns, this is the left column, this is the right column in the middle order, so what to do, first we have to print the toppers, okay, then we have to print the l column, the right column, then we have to print the bottom rows, then We are printing the left column, moving around like this and saw the direction, this is our one direction, so if I take this as DJ 120, then you saw that I am coming down, if we call the directions two less, diesel two one. Our third direction is okay, we are going from right to left in the third operation, we are pressing the button, we are going to the long platform to light the light, so the direction is the second, after that you saw that the direction is the third, I accept it as the voters. It is going up to the toppers and it is taking up our left column completely. Okay, so now after being free, we will be roaming again, there will be three of the directions, Ghee will be made every day, this action will go, the structure will be thick. Have you understood the code of the court? Okay, we will not make the video too long. We will do this in the court. First of all, we said that we have * and matrix, so we have to said that we have * and matrix, so we have to said that we have * and matrix, so we have to find out how many rows are there in it. So let's do the basic setup. First, okay, the number and how much is the good column. How many columns would you know how to remove, look at the columns of E0, there will be so many columns in each, so there are three columns of zeros. Okay, these two are finished, do good work, return type our list, don't print it. One way to save spiral water is in the list. Make it okay, I would like to name this loot as a list, what is the use, if you see something else, okay, I have made the list, okay, this is done, now what to do after that, handle the shares of one base, in the beginning all these things. You will do better that if the length of your matrix is basically A, then stop it. length of your matrix is basically A, then stop it. length of your matrix is basically A, then stop it. If yours is 0, then return your MP list A. There is no need to do any processing. Okay, now I would like to tell you how our process will be. A little bit. Let's see how we will understand the concept of this. Now see, if I say that I processed the toppers, then I printed these three, then next time when we were coming in the circle, I was not rotating on the toppers again, then where did my toppers go? My top disease was gone, we had increased one that this process was done, the proper one had come here, in the same way, if this right one was my process, then my right one was come here and in some time you will see that the left one will be processed. Left and right will come in the same way every day, one part will go and at one time the left row will go ahead of it, okay so something like this will keep happening, then we have to stop the processing, okay when our left goes ahead of our right or Then if our top goes ahead of our bottom then this is a condition, you have to walk holding it, you have to remember that as long as your left is less than or equal to the right on physical Twitter, your top which is less than or equal to your bottom is fine. If you have to do this, then make a Tushar declaration to make the interior. What will be the left? The left problem will start from the left over. Okay, the left column will start from 0. Okay and we will leave the top. Where will the right worm come from, what is its length, which is our right. Column is, it will go till our column, but this is one less in zero base indexing. You know, the index on the right side of the column will be minus one, in the same way, the top will be from Pro0, the promise to is the last bottom row, how many will be mine as many as ours. As many as we have, that will be the button, this is done, row minus one, okay, that's it, we have done that, now let's take a direction, we have to do it ourselves, this direction is ours, I took the direction from zero, in the beginning, Jio is One will go to two, then it will go to free, then it will go to zero. The video will seem a bit boring and it is a matrix question but once you have to understand the contact, after doing this, first the matrix is two same code. Okay, now let's matrix is two same code. Okay, now let's matrix is two same code. Okay, now let's start the court, so let's see what to do now. Na, start on the direction wave or, then the direction of the people, then you do direction one, two, okay, if you want to keep doing it in this way, then do direction, you press two, okay, this is making the structure thick and thin till now. So keep it ready and then start coding. Okay, this is the basic installation. Basic shut up. Now this is the direction and for us, your work is done till then. Zero 123 and okay and we will print this traction. Finally, you will make your Print the list, the answer has come, let's start the directions, process it, then stop the direction, do one process, do darshan, do the process on you, free the direction, press free, turn the direction back to zero, okay. Well, this is also done, if you want to process it, initially you have to print 123, then you have to print the toppers, but if you change the mood from left to right, then our left or right will work, this thing has to be kept in mind, you will code it once or twice, it will be remembered. And people, where will the direction go, it is at zero, first our intermediate will go from left to right and from left to right, okay I am plus and after that, what to do, right? You have to extract the value of this matrix and add its value in the list. So look, the matter of top row is different, we had printed the toppers but it is a changing tractor, it will keep changing one of our columns and we have put a loop in the column, so it is okay, so basically I have come here to add it to the list, let's do this. To add all the items in the list, we are sorting out each position but let's add the last one. After doing this Ajay, little did I know that this process was done, we had reduced the toppers to the bottom, so you are under your control every day. Had done mature had been increased so do that here two increase the toppers increase plus two okay next time now what to do is to update direction one and how is it going that it is direction one so what is there in it from the top Bottom allegation below but you are processing and right column just remember from where it is coming from. First write that if you are coming from top then okay then you are coming from bottom okay then border is coming from you. And what to do after that, copy it, there is no use of writing forward and if bottom is coming from not stop then the bottom is coming from our top and it is changing daily but if the right column is being printed then in the right column Write the right column. Changes are happening with us every day. Here I have done it. Now what will happen in this right column? After it has been processed, do it by reducing it. This is simple. You just have to remember what to reduce and what to increase. Then you go next. Do nothing much, the same question will come, you will be asked to write the same code there too, so now you have to process the bottom row, but this time we are moving from the right column to the left column, a little reverse is happening. Right close loop actions are taken, we process them, let's run the reverse loop, so I was saying, where am I going, from the right column, I am going to the left towards Alam. My - - Eye give this. People - Let's go by the way My - - Eye give this. People - Let's go by the way My - - Eye give this. People - Let's go by the way remember it's ok and ok pick this up and what we were doing in this so bottom row we were printing and our it's left we were muting so bottom row write first bottom row we were printing ok And this is ours, I wrote it in 3, sorry, let's ignore that Kotha Karma direction to 35, we will do a stuff, neither were we taking the right sum, so now we have printed the voters, okay, bottom, we have printed it. But this is our direction going from right to left, so it will automatically take the same height, select the height and return, the matter is simple, good bottom process is done, bring the bottom row up here, bring it along with the top, then it means the length of the bottom row. That was one thing was done B minus two now let's pick up the last one, what's in the last one, this is the one on the left, is n't it, these are coming up from the bottom, coming towards the top and this left column electronic left column Lift it completely, coming from bottom to top and lift the left column completely, then go from bottom to top 12 in reverse, this term is coming from top - - 6 is coming from top - - 6 is coming from top - - 6 is ok, top is coming from the button, remove this. Two more, we were picking this left column, this is Alam Vijay Kolar, this is 18, Alam, write it like this, okay and put it here, okay, it is simple, now in the left column process, move the left ones forward. So expand the left column, the work is done, the structure has been written, it will keep rotating, according to me, it is done, I would like to delete all this and after scanning once, I would like to see that something is being scanned, a mistake is being made, we have also done the return. We have given that, let's check these many chords separately, here we did not find any semi-problem, all these here we did not find any semi-problem, all these here we did not find any semi-problem, all these mistakes, you go, write how much and fat, let's see once more and this 20 so that you will have to write first, Rocky, check and come back. Just set it if you are in matriculation then get the MP list printed there, no need to do any work and submit it and see that successful submit is getting accepted and you can see in the video. Subscribe to my channel is 966. You can subscribe to cover all the videos and see you in the next video. Thank you very much for this. | 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 |
893 | Hello hello welcome to taste preparation requested post question is the patient has pieces in which we have the texture that kidney will go and the listing will be as much as it will be that whatever elements it will have all of it, we have a quarter inch of it that happened in special events in which we Out of that, let us complete that we had some porn and this is the next year, there is someone else in it, like we have to do, like in the middle of this, she has become special, then for that, Russia, like if on this, we have to pay the gardener and tax. So if there is 100 and on this we will be at a time because from that and this again so here we have that only means if we can make changes in it that we can depress it with a positive value, then here if If we see that there is a clash, then Meghvar helps us on the points, then if we now have time on WhatsApp, now how can we increase the equivalent group, we have to give these two in the encounter, now let us assume that the This year's spin ball is given, so if we see here it is ABCD, CCTV is C, request is being made like if we change the voltage among these three and get a simple group, then this is ours here. If I robbed you then did I spinjiju special request, his account was Dr. So this can be a special tanning here that sometimes it happens that if we are watching this then at that time we think that let's say that a A group has been formed, now a group of this and that two has been formed and in the same way this group has been formed, then it will happen at that time that whatever group we have, they will take a bigger group and if we want to get it done from it, then we demanded to decide at that time. If you look here at this and this, it means that some changes would have set an alarm in the group, then at that time ours which till now was only ₹ 2 and this was only this, then was only ₹ 2 and this was only this, then was only ₹ 2 and this was only this, then how much money is there in our things. That has to be given at that time and it must have been given in whatever will happen, so for that I have given an example like this, whatever work has to be done for it, like if we look at dry ginger, then Bhushan is something like this. It will be that we are monkey size lion left, after that boss, we have taken ABCD, so we will change ABCD with the next Justin, then first of all we will do what is here and what is from the seat and then check that it is matching. So now we will do this here and join it with all this here, then at the same time Sambandh Ravana will keep checking this entire team and then keep seeing that if this value is being found then we will add it to the group. Now if We are Edition Pyun in this group, so it should be our pimples to such and such groups, but now what we will do here is that if this is what it is, then if we add more of it and whatever we do, it will become very big and subscribe a lot. That if that question has not been asked in Hindi then I have put pistachios for this question, first of all you go there and practice this question, you try to do some project as per your own, what will happen from that you can get 21 MPs and MLAs daily as per your choice. Let's solve the problem of how to invest, if you will be able to do that on Android, then in this mind that as we know this group, we have to name it, what we have to do is to remind which value it is and we can do whatever it is. We want to take what we have and take with it 138 This is a machine, after breaking it, we can see how it is becoming a Chinese group or not, whether it is the President or not, then this problem can be solved easily. If you will be able to call then what will they set that suppose we take that from the servicing that is ABCD is CDAB which is which one is doing this on behind the back appointments, then we will open it and take the balance which is even. So whatever is here and whatever value is there on the even, the building and the goddess that is here, the seal and that from the media and Billu and this matter, if we make it a fool that we have done this and now we, then she will go and our If all of them are the same, then in that condition, whatever will happen in the group, now we have someone here that if there is any rally and in that, we saw that if this video is coming, then we will not add Pumik at that time. That we will get this one, now if we use such Gram Quiz Patience Accepts Gram, then it will give us whatever unique rally we will forget, whose purpose will have to be fulfilled and whatever we do and we will use it for like and subscribe and on top of that we If you are doing it then you can now make improvements in it like I just said, can we use America for whatever we want to do or can we use it or what can we do If you take any particular Singh and send it to Vrindavan after setting it up then you can make any payment, I, your messenger and your people, if anyone can add. For example, if you use it in this manner at this time, it will save your shopping time, then what will happen according to that, it is time for coating again and our ability will also reduce, so what can we do? You can't do anything else or you can add anything like so here you can edit the video as per your requirement. If there is any problem inside then we are going to go ahead and watch it right now, start it, still make a moment. If you can, then complete it as per your wish and do it in the assembly. So, this is the answer to our question and in this we will make a meter and inside it we will be given information string, so that we can match and select the group from it. If we want to make that from then for that we can say set this so what we will do is take the gas flame and for that and what we just saw for that time Amit Singh will take more and now inside this we will have more posts laugh whatever and Agent is there, he has all the tricks and other things in the industry and he has all the control, if we add it then it will be like we saw that and whatever else he had done in the industry, these people were getting it, so here we are. Are using but to do this we have created our first and use that we have softened the whole hair and vote and here you will be our dry rally and this will be as unique as those who subscribe to our channel. But if we meet then here many times this happens where many defined s were already there at this time and if we have to do it at that time also then at that time the jhamajham will be slightly changed and now it is complete but in this it has been used and It may not be enough and it will remain ours and it is what it is but what I have implemented is in a slightly different way. Let's say that what we saw in the Pizza a Solution was that we worked in front of the team and its method. The reason here, if we have taken diabetes, then what will happen if we do not do whatever was being done, for example, the person who was getting it done was solving it and the one who was doing it for us and not by adding it, then we have to subscribe to something. The one which was received but is only available, cannot be fulfilled while kissing. The cigarette which has to be smoked. At that time, we will use the seat belt, join interior, it is real and make it for us. Instead of regarding that which has been arranged, the song is that. Whatever things we get and whatever unique things we had back here, as if we who are our country, we will make it from the canteen and for them, now we all the people who were there in that too. Were doing but in that reason must have started by subscribing here in that, now as we add the batter to the SIM which is there, anyway that chapter's increment will be completed from these specific busy life and tent. What will we do, we will cut it and now due to being an industry, with shampoo and if we add here, then this will be eliminated, what will happen with this that we will come to do whatever and there is no need to do it, then this was Mahima. Sudarshan, if you have any doubt for this question of ours, if you liked the video, then like, share with your friends and subscribe to the channel till then with this video. | Groups of Special-Equivalent Strings | all-nodes-distance-k-in-binary-tree | You are given an array of strings of the same length `words`.
In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`.
Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`.
* For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`.
A **group of special-equivalent strings** from `words` is a non-empty subset of words such that:
* Every pair of strings in the group are special equivalent, and
* The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group).
Return _the number of **groups of special-equivalent strings** from_ `words`.
**Example 1:**
**Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\]
**Output:** 3
**Explanation:**
One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.
The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\].
Note that in particular, "zzxy " is not special equivalent to "zzyx ".
**Example 2:**
**Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\]
**Output:** 3
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 20`
* `words[i]` consist of lowercase English letters.
* All the strings are of the same length. | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | null |
60 | Hello hello everybody welcome to my channel today is the day 28th june recording challenge MB problem is per motivation cement members to and contains all the total length factory units per month in this listing and having all the per motivation in order to get the following sequence for any One to three lights 12313 2121 to 0217 In between hai front saath par motion song play n is between boys classes in k will be between 2 and cars for example 12323 Lo sorry for them on subscriptions 13152 Video turn on the * minister lift quiet Different Do * minister lift quiet Different Do * minister lift quiet Different Do n't Mind Will Get This Shows How Will Solve This Problem Let Me Explain New Fruit Force Approach Sudhir What We Have To Create All The Missions Example Foundation For Any One To Three Layer This And How Will Get Some Will Get This Hai Haldi Promotion Bhi start from one place to another and 120 elected to bat first in the school was elected to the 0230 will give one to three is 10th left with two three fatty acid selected soul will not be selected in the industry subscriber tree to avoid you to the Like Share And Subscribe Similarly Subscribe Like This Shrill 231 Shades One More Three To One Which Missing From This Initiative Which Lasts For This Way Also Get All The Formation One Switch The City Of The Initial String Started Between Subscribe The Channel And Subscribe The Amazing The Answer List Play List Ki Dot Net Aaj Cake Minus One K - Services Morning Later Aaj Cake Minus One K - Services Morning Later Aaj Cake Minus One K - Services Morning Later Till 19 Minutes Let Me Convenor He The Code Of This Which Is Written Earlier Vikas To Make Short Video I Am Not Fighting Record For This Add Fruit Solutions For Writing This Code You Should know how to write because others have problems and not with use this way saw her first created during British numbers from one to one day the result will hold to the number one right this is my channel subscribe And subscribe The Amazing to the result of After the For All Next From Zero to the Standard Size Water Sources of Power Sparing Saudi School Will Be Called in the Village Difficult Character Subscribe and Removed from the subscribe and Share Thank you members Will Work for India But If You See the Time Complexity Lets Submit Difficult 10th Time 200 Setting Too Much Time Definitely Will Be Time After Being Unfurled The System Limited Vikas Wise Kushwaha Recording David Designs for the Time Complexity of Dissolution Wave Fin Factorial Sources of Unfair to Real 210 One How They Can Optimize Solution 100 Such No Like 512 Generate Se Example Against And One Two Three One To Generate December 2016 Subscribe Possible For Motivation Subscribe Possible And Subscribe In The Total Population Will Guide You - 1929 Subscribe 312 Subscribe To You - 1929 Subscribe 312 Subscribe To You - 1929 Subscribe 312 Subscribe To Like Baby Can Get No S Person So What We Can Do We Will Computer's Wherever We Draw Select From We Shape's Hair 9 4 So Effin's End Which Episode 21f First Place And Can Get Maximum Possible For Motivation Subah Means The Best Option For The Place Will Not Be Able To What We Can Do This And From Hair that and in this will look photo again the two separate from here.the K F103 subscribe separate from here.the K F103 subscribe separate from here.the K F103 subscribe The Channel and subscribe the Channel Please subscribe this Hair 216 How Can Calculate Soft Bhi Anjaan Reddy Factorial of All the Number 24 2010 Will Not Used Cars subscribe and subscribe this Video plz simply divide the number with that number and - the current index I show the that number and - the current index I show the that number and - the current index I show the number of middle number one seems rather than 4000 start with 1212 reply two the software I will start with avv will get rid from k divide factorial of which 3 - Way Subscribe Button More Channels Subscribe 238 Subscribe Similarly One Remove From The Ko Remove B N X The two Swadesh Civil Drink After Removing This World Channel Subscribe Now To Receive New Updates Reviews Subscribe 04 - Special Guest Subscribe 04 - Special Guest Subscribe 04 - Special Guest Lutti Apne Pati Voice To This Previous D Ki ho fifth edition shop no this one will v5 actually so this point you calculations for five se zbar weir graphical 251 from which comes for this calculation in terms of hair and cases with festival will always have a part of three - Vikram for tube well 2031 That Similarly They Will Continue Till And Will Give Them One Dose Motivation For Meditation In This Is Very That Easy Problem But Getting This Idea This Little Tricky Vansh You Have Some Idea Only When You Look So Let's Start Between Optimal Solution Implementation Remedy Share This Code Show What We Do First Will Create Factorial Are Thing New In Top Ten Plus Vwe Elimination Of Vwe Calculate The Real Me2 Vwe Plus I Slept And Fact Of Life Is Equal To Front Top I - One Star I Sudhir Vasudev Singh Tweet Stream This A stream interesting and arrange from one to and plus one vikas will be one race in the sense one to two to do subscribe list subscribe channel thank you will need to which will result in in to-do list in to-do list in to-do list That Builder Jai Hind Sir Chashmish Ayur Vigyan Distic 9 Bhi Reduce's Scholar And Will Not Follow For Marriage Youth 2n Plus 910 Video Subscribe Divide Factorial Of - Number In History From Start To And From List Will Not Remove - What Is The From List Will Not Remove - What Is The From List Will Not Remove - What Is The In The Story Of A 's member will be updated with that one should be given service just a string of this 's member will be updated with that one should be given service just a string of this train will have spring is you string of speed2 spring member simple implementation and tried to compile amarkot 123 compiled and expected answer so let's get the idea and solution so it accepts so What is the time complexity of dissolution Sudesh Bhosle and where running the factorial in Dishaon Software's dinner minister but her desires will also be running but if you remember that up and enlisted in law and is contest while removing from the take this particular touch it Open Which Will Take Off Time And Also Running On Open 10th Time Complexity Of Functioning Of Which We Square Safe And E Couthing Space Complexity Wishes For Pyun Otherwise Subscribe Please Subscribe My Channel For My Upcoming Videos Thank You For Watching | Permutation Sequence | permutation-sequence | The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:
1. `"123 "`
2. `"132 "`
3. `"213 "`
4. `"231 "`
5. `"312 "`
6. `"321 "`
Given `n` and `k`, return the `kth` permutation sequence.
**Example 1:**
**Input:** n = 3, k = 3
**Output:** "213"
**Example 2:**
**Input:** n = 4, k = 9
**Output:** "2314"
**Example 3:**
**Input:** n = 3, k = 1
**Output:** "123"
**Constraints:**
* `1 <= n <= 9`
* `1 <= k <= n!` | null | Math,Recursion | Hard | 31,46 |
1,071 | hi everyone so today we're going to solve lead code daily challenge problem number 1071 greatest common division of strength so uh it's a very simple problem uh it is marked as easy as well so what we have to do is we have to find out the gcd of two strength and they have given a definition of gcd in strings as well uh which basically means the largest string which can produce both string 1 and string two uh if concatenated repeatedly okay so basically we'll have to find out the same we have to find out the minimum or the yeah I think the minimum string which can form the both these uh which can form both these uh strains after repeated concatenation so it's going to be a really simple one to solve um it doesn't need any you know any as such explanation uh to solve this question so let's move right to good solution and what we're going to do is post things first I'll check if my string one and string two are same if yes then I can return any of these okay next condition is I want to check if there is any uh gcd possible or not so to do that I am I'm checking if I add a string 1 and string two and do this thing in the other order if both these strings the strings are same then we can say okay uh P can have a GCB if not I made this error if not then we will return empty string as our gcd because then we cannot have a gcd for example if string 1 was lead and string two was code in this case our gcd will be an empty string right plugins so next comes the condition where I want to just find out the maximum length we can have for our uh for a gcd or these two string so I'll be using the default uh method provided by python to do that so next length is equals to PCD of length of string one and length of spring 2 so using uh this approach we will get the index uh in any of this like you can either use string one or string two for the return purpose and this back slant will basically represent the index uh index till which are gcdas for example a b so we'll get one as the max length or uh let's say ABC and so on so now what we have to do is we have to just return the values from string one till our next length let's submit the test let's check out the test cases um the test cases got here let's submit for further evaluation and yeah the solution that accepted and we performed decent like we outperformed 79.41 of the submitted Solutions uh last 79.41 of the submitted Solutions uh last 79.41 of the submitted Solutions uh last time I submitted the same it was around 95.70 percent 95.70 percent 95.70 percent so yeah thanks again guys for watching on the video and stay tuned for the upcoming ones don't forget to subscribe to this channel thank you | Greatest Common Divisor of Strings | binary-prefix-divisible-by-5 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. | Array | Easy | null |
341 | and hello so today we are going to do this problem called flatten nested list iterator so what we have with this problem is a nested list of integers and each element is either an integer or a list okay um and the user list also can be listed so you can have something like this and then another list inside it and maybe an element here and then some another list and the goal is to implement a nested iterator that has next and hazmat next function this one returns the next integer in the error so let's say we have maybe uh one uh two here uh first we'll return one and then we'll return two and then we'll know whatever is next has next just returns if there is um uh still elements left or not if we are at the end of the hour list or not and the code that will call our function is um result here and while there is a next so call has next we get the next element and then we add it to the list one thing to note here is that before every call to next we do call has next that risk guaranteed by the problem that will help us later in the implementation um yeah so let's take a look at one of the examples they have here um so we have uh this list um for the first one nested list is the first element of the nested list so one and then after that this one and then this one so you can see it respecting um this is also another interesting example so first this element and then the one in the nested list and then one in the depth three here which is six um so that's the problem um now let's see how we can solve it um so the simplest solution is to just um rub the list the nested let's flatten it in the constructor and then have an index that marks the um the position where we are at for next and each time just get that position and increment it that's the simplest solution although it's not ideal because then we are not implementing a real iterator um so definitely not the recommended one but it's a good place to start okay so let's just see that one and then go from there to the to a real iterator solution um so for that solution we can have um in our init function okay we are going to create an array of that represents the list completely flattened okay so to flatten the list we'll go through the element of the list and for each of them flatten it and then just add the elements in values okay so how do we flatten it um if the element is an integer then we don't need to do anything we just add it to the list but if it's a list then we get all the elements in it and recursively call helper so that if it's an integer we just return it but if it's another list then we iterate again so very simple and then we have the uh a pointer that starts at zero um and for next we get the element increment the pointer and return it and for hazmat we just check if we reach at the end of the completely flattened list um so this one is very simple um however it's not ideal because we already constructed the list we want to implement a real iterator so let's see how to do that next um one thing to note though is instead of an index here you could use um a stack of the elements and then reverse them and then you can pop each time or you could use a queue and then each time pop from the queue instead of maintaining um an index so that's also a possibility um okay so let's see the next solution um okay so let's see how we can do a solution with an iterative with an iterator here so the idea of this is what we want basically from this solution is first return one then return two they return three then four then five so regardless of the nesting we want to return the elements the first element right so what we can do is just have a stack that contains the element and each time what we want is the environment that we want is at the top of the stack um that's the elements we want that's the next element so this is the invariant we are looking for so to do this what we can do is basically add to a stack this list to reverse it so that one is at the top right and so if we do that what that will mean is this here is the first in the list this list here right this is the first element um then after that we'll have four then after that two three then one so what this allows us to do is in next we can just the next function call we can just do this is our stack you can just do stack pop and return that okay and just return this okay but for our mix function so we would remove one and we'll return it and that's what we expect but for our has next function remember in the problem statement it says before every next we call has next so what this would mean is in has next we need to unwrap this right we need to transform this to be two what's the first element that we should have to be 2 3 4 and then this will stay the same until we get to it so we need to unwrap each nested list in has next so that it's in this order right the order where when we pop we get the first element so that's what our has next function will need to do so how can we do that basically uh so we need to just pop we need to just check the top of the stack and if it's a notation we don't need to do anything like here in the case of four but if it's a list we need to do the same thing we did at the start which is um add to the stack basically pop the list itself and add it to the stack in reverse order so that the first element is at the top in python we can do it like this okay so what our has next function will do is just keeps iterating until it finds an integer because what we want is top of the stack next element and an integer this is what we want and so has next we'll prepare for next to do that and so what we will do here is while we have a stack what do we want to do um so we want to get the top element right and if the tab is integer then we can just return it we can just return that we have an element right so we can return true but if the top is not an integer right like in this case it's a list what we want is to pop this and instead enter two and three in our stack right so we can just take the list to reverse it and then add it to the stack and so to do that we have the top that we want to um to add and so we can just take the stack pop the elements out of it and then add it again but reverse it at the top which is two three in a reversed order so that would be just uh taking the top in reverse it order which is top minus one um you get the idea so minus one here okay uh one thing here we don't we shouldn't do append we should do extend because we are adding a list in python okay um so this is the idea but if we end the stack and we didn't find any integer although we kept uh popping let's say for example in a case where we have a stack like this where there is an empty list and an empty list right this can happen with something like this then we won't find them into here then the step would become empty after traversing these two and so we need to return false at the end okay um so this is the simplest idea here at the start we'll need to call tab get list together the elements right now you may ask what about the case for five and six here right so what will happen is that what we'll add to the stack for this is five first and then the list six um and then the list six and so in the next iteration we will get the elements of the list and then we will add them as just six okay so this will work each time right um yeah so that's the main idea is to each time we unwrap the list that we are at and we add it in reverse order to the stack so that the first element is at the top so that we can pop it in the next function and the invariant we are respecting is that the top of the stack is always a single integer um and it's the next element okay so let's cut this up and make sure it passes test cases um okay so let's put this solution up so the first thing we need to do is to have our initialize our stack and we need to initialize it as we said to the reverse of this nested list so that the first element is at the top uh the second thing we want to do is make our next function just return the top element because we make sure that top element is um the is the integer um and it's the next integer and this is possible because um in the problem statement we are guaranteed that has next is called before next um and now in our function here we want to iterate while there is a stack right one there is a stack we want to um okay so while there is a stack we want to get the top um we want to get the top uh element and then after that we want to check if it's an integer so if it's an integer we want to return true of course because then we found an element um otherwise the top is a list so we want to pop it and then enter the element in a reverse order and so to enter them we extend the stack with the list in the top right so this will instead of having two 3 in the top we'll add 3 and then 2 after it in the top of the stack and then if we weren't able to find any integer in the stack then we return false so let's run this okay more examples um okay so it looks like there is something out of order this is because we did not reverse here we need to reverse so that two for example for this list we want two to be at the top so if we just extend with two three then three will be at the top we want to do the reverse to add three and then two so that two is at the top so that's why we need um to reverse the list okay and this should pass solar submit and this process passes test cases um now with this solution next is of one because we are only doing one pop um and has next is open because we do as many elements in this stack as the there are so with the number of elements in the nested list um okay so this is the one way to solve it another different way to solve it but still in an iterator way is um to maintain track of the now reverse by just maintaining where we are the position where we are in the while iterating in a stack so let's see what that will look like um okay so in this solution the idea is to maintain um is to maintain in this cat um the position so let's say our stack here um so what we want to do is maintain the list in the position so let's say let's actually make our stack bigger here to understand our solution so in the stack each element will be will have nested the nested list and then the index where that we are traversing so what this would mean is first i would be here and we will put the entire list and the value zero right because i is zero here in the next um iteration i would be here so this is what the list in this stack right so the current list we are looking at that's what would be at the top of the stack so what i mean by that is that um let's copy this here because the first thing we will do is add the list in the stack the entire list right with the position where we are at which is zero okay and so what happened so that's what we start with from the initialization now what do we do for next what should we do in the next iteration so what we need to do is get the top of the stack right so that we can get the position and then return that element right if it's an integer we print that element what we need to do is advance the index right we are here first as zero we need to advance the index to one so that the next iteration we go to the next element so to do this what we need to do is get the top of the stack so to do that we just get our nested list in the position and that would be the top of our stack which is in python just minus one which is the element at position n minus one and then we want so we want to return what's the value is the nested list at position i right so first it will be position zero will get one and then we will get we need to get the integer because next we'll need to always return an integer so what this would mean is our has necks need to maintain that the top at the top the element is always an integer and so here once we return that element so this is i actually we need to increment this here so what we do is we take the stack the top of the stack so we say stack at last position that's the top what we want is to modify this which is at position one we want to increment it okay so this is what um what next does now we need our hands next to always maintain that the element at position i is an integer so how can we implement our has next to do that okay let's explore that so has next um so what our has next function can do is check the top of the stack again but since we may for example have something like this to enlisted less we need to keep going until we find an integer because we need has next to maintain that the top of the stack at position i is always an integer right so what we do here is we do wireless stack um we get the top of the stack right position minus one that's the top of the stack and so we will get uh an element we don't know if that element is a list or an integer yet but what we want each is to check so let's say we are at we have two three right and i is at we incremented i in next and it's equal to two right that means this list is done right and we need to go to the next list so let's say we have maybe three four here five we need to go to this next list so that's why here we check if i is equal to the length of the element then we want to go to the next list in what was previously in the stack right so what this would mean is basically we need to pop this out of the stack so let's say we um we added 2 3 to the stack right and then our i is now here so it's bigger than the length of 2 3 that means we need to pop this 2 here and of course add 4 okay um or at the entire list but have i at this position right and so what we need to do here is if this is equal to the length we need to pop the top of the stack because that means that the element is done we finished it reversing that element here okay now otherwise what should we do so otherwise we have two cases either the top is just an integer four for example and we can just return it or the top is a list and then we need to expand that list right and so to do that here um so we check if the element at position i right let's say i for example is here at position 2 we need to check if this is an integer if it is we know that we have an x element we can just return true and next one just get that we'll just get that element and return it right otherwise it's a list right so we'll need to do is make the top of the stack be that list so otherwise it's a list let's say for example for this 5 6 that means we need to open this list and put i at 5 so that next year returns it and so what we need to do here is append to our stack the new list right which is element at position i we get the list and stop at position zero but before doing that right because we say here we are at this position i and maybe there was an element here once we appended this list we needed the r for the entire list to be incremented as well right and so what this would mean is here we need our stack before adding the element we need to the top of our stack to be implemented for the next time when we pop this list once it's done you want to go to the next element in the rest of the list if that makes sense okay so this is the main idea maintain the list we are looking at in the index and then for next get that element at that index and then for has next each time we check if at the end of that sub list go to the next list or the next element in the top level list um essentially so yeah this is pretty much it now let's screw it up and make sure it passes our test cases um okay so let's write this solution here so first we need um to have um our stack right so we need to define our stack here which let's say it's equal it starts out with just as we said the nested list at position zero and for next we need to just proper the list from the stack so we need to get the top of the stack incremented so this would be soft dot stack and what we need to return is the element right where we are pointing at the top because the top is what the element that we need to return next and we need to get the integer okay with hands next we guarantee that this will give us an integer so we don't need to check now for has next what we need to do is well we have a stack and if we exit and we didn't find an integer then we can return false here we need to check the top of the stack check what's there either the list we are looking at ended and so that means it's equal to the length then we pop that list and the next thing we traverse would be whatever is at the top of the stack after this right and then here otherwise we will check if the element we are looking at is an integer then we are done you know there is an element so would it be true otherwise we know it's a list and so we need to do is definitely append that list which is basically um just elementary list but we need to specify what is the position which is zero here the start position but we shouldn't also forget to increment the previous step right because um but once this one is done we want to go to the next one if we don't increment we will get to the same list and traverse it again right and so that's pretty much it so let's run this um okay it looks like there is a small issue here um so we pop we check if it's an integer which isn't true yeah this is element at position i that's what we determined is a list because that's not an integer so it's a list okay let's check if it passes test cases and it does um in terms of time complexity here um here we are only doing all one operations so this one is of one here we do at most the number of elements in the stack so it's open um yeah so that's pretty much it for this problem thanks for watching please subscribe and see you on the next one bye | Flatten Nested List Iterator | flatten-nested-list-iterator | You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the `NestedIterator` class:
* `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`.
* `int next()` Returns the next integer in the nested list.
* `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = \[\]
while iterator.hasNext()
append iterator.next() to the end of res
return res
If `res` matches the expected flattened list, then your code will be judged as correct.
**Example 1:**
**Input:** nestedList = \[\[1,1\],2,\[1,1\]\]
**Output:** \[1,1,2,1,1\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\].
**Example 2:**
**Input:** nestedList = \[1,\[4,\[6\]\]\]
**Output:** \[1,4,6\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\].
**Constraints:**
* `1 <= nestedList.length <= 500`
* The values of the integers in the nested list is in the range `[-106, 106]`. | null | Stack,Tree,Depth-First Search,Design,Queue,Iterator | Medium | 251,281,385,565 |
1,442 | Hua Tha Hello Viewers Welcome Back to My Channel Hope You Are Doing Red Brahmin Subscribe My Channel This Please Do Subscribe My Favorite Several Places for Various Categories Such Problems Iss Defiant Programming subscribe this Video Please subscribe and subscribe the inform 2all Subscribe Give Winners Were Selected in j&k are defined in the fire key j&k are defined in the fire key j&k are defined in the fire key 111 sexual phase - one b is equal to 111 sexual phase - one b is equal to 111 sexual phase - one b is equal to airtel 156 alarm key not the symbol of return subscribe this boy dividing darkness * and this entry r&b are still there in some cases subscribe jhal triplet suresh basically Matku Singh The Thing They Do You All The Number Subscribe Our All Elements And Just Completed For Example Electronic Form Working From Subscribe 12000 12023 40 Subscribe Sudhir And Ex And Boy And Results Rate 100 Effective Thursday To Ki And Mexico 2012 Warning Results Want One Adhikar And Active & Want One Adhikar And Active & Want One Adhikar And Active & Tonight 10 2014 Truth Table 0share 0 0share Different OK Sona List Work Through 1000 2000 To Take Lead A Good Night Note Down It's Gomez - 101 Element 2012 Thursday For Thursday Subscribe Now To The A Primitive White And Flow Of Often Needs Just One But Dozens We Importing Ajmer Road Developed B We Want To He Google Lens For The To Front Thursday 2510 Play The First 101 1000 102 Year 2009 Hello How Many District Let's Be A Giver Slogan Is The Question Solved Work Through The Amazing Exactly What We Call The X Factor Is Nothing But A That In Our Enemy So Android Often Similar Em calling latest table slip services sister name but rather be attend a 200 na velvet rathwa timli the eksar par element sense off kar ki ve gotra udhar restaurant sperm group from a 2002 ashes live with the hague element from subscribe element 2014 Ko Hand While Soaking Uday Trade Will Update Counter Reform Committee Secretary And Protest Actually Hot Movie And Counter Soil 102 Example S0 20000 To Subscribe My He Will Go Through This That The Second Part Starting With A Refuge And Quick 2020 - 02 End Tours Two Refuge And Quick 2020 - 02 End Tours Two Refuge And Quick 2020 - 02 End Tours Two Three And You Only I One lights S2 Kshatriya And Will Go Back To Our Banner Representation And Work For 800th Ursa And So Will 61st Ursa Element In The Right To The Factors And Subscribe The Video Subscribe And Subscribe The Video then subscribe That I will be properly uploaded video very soon with better implementation so let's go for entry into Quattro the world article named Lal Yadav 2018 Sudhir and Obscene to the number 0001 but not required to the justification tell that I am going through 102 and that of first follow-up And Minerals In Electronics follow-up And Minerals In Electronics follow-up And Minerals In Electronics And To Negative One Should Start With My Electronics On Negative One Should Know I'll Start From CO2 And Subscribe - Start From CO2 And Subscribe - Start From CO2 And Subscribe - 110 Adhir They Do The Meaning Of The Record Subscribe And Subscribe 202 Duplex And Heard That This Stage Wellington ODI counter and put in their hearts of but still continued it's not divided between multiple operations of any possible wound taking feedback red 202 280 12802 to the self closed scene fluid set that triplets diet included deposited solid you want him to go back end You Will Improve That Time Complexity While Doing Right Subscribe subscribe and subscribe the Channel Question Express The Current In Next 100 Withdraw Into Soft Pitch Attraction In This World Who Were Going To Reach In Electronics Finally Bigg Boss 100 Basically This Channel Subscribe Must Will soon subscribe The Channel from Sydney with love hua tha from what ever with XX plus one to end rights issues laker swift basically disappearing from the reader highest number and further from here from number plus one to end various platforms basically show words we Are going from going to land rates will all total time table b.a. The Mother After And Give The Total Time Complexity 542 President My Channel Thank You Are You All Don't Forget To Subscribe And Subscribe To 210 Complexities Content Saluk Ramesh Account Space And Deaf And Cube Algorithm Questions Please Leave Your Comment On Your Post Office Code That You Can Read in the description and subscribe the Channel Please subscribe and Share with your friends Please Click on the Bell Icon You will be notified about my videos Video Problem Limitations for improvement in time complexity Subscribe button The middle problem that they have to improve time complexity is in the description Security ok thank you for watching me with another problem very much | Count Triplets That Can Form Two Arrays of Equal XOR | number-of-operations-to-make-network-connected | Given an array of integers `arr`.
We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`.
Let's define `a` and `b` as follows:
* `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]`
* `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]`
Note that **^** denotes the **bitwise-xor** operation.
Return _the number of triplets_ (`i`, `j` and `k`) Where `a == b`.
**Example 1:**
**Input:** arr = \[2,3,1,6,7\]
**Output:** 4
**Explanation:** The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)
**Example 2:**
**Input:** arr = \[1,1,1,1,1\]
**Output:** 10
**Constraints:**
* `1 <= arr.length <= 300`
* `1 <= arr[i] <= 108` | As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters. | Depth-First Search,Breadth-First Search,Union Find,Graph | Medium | null |
111 | welcome ladies and gentlemen boys and girls today we are going to school's problem which is minimum depth of binary so basically this is the binary problem and it's quite simple as well so what the question is saying let's just see the question saying like i hope like from the title only you understand what the question is saying but anyways let's just see the question first given a binary find its minimum depth okay the minimum depth is the number of nodes along the shortest path from the root to the nearest leaf okay so what is saying like the minimum that how we have to find is from the root to the minimum leaf okay guys like this one uh let me just make this pointer size bigger little bit okay so from over here to over here like this we have to find okay it is different so now the question is like uh okay what approach can we use over here are we gonna solve this using bfs so it will be quite simple to do with that okay so ladies and gentlemen i hope so the question is clear and let's see like how we're gonna solve it and how we're gonna call it i mean okay so ladies and gentlemen let's just start solving this problem so uh okay so first of all what i will do i will just give uh two base conditions my first base condition will say if my root is null if my root is low then what i would do i will simply return 0 over here y zero because as they have given the int so that's right here we i can't think of written force over here okay anyways the second condition the base condition is if my root of left is the and my root of light is built as well so that is a gentleman now what is saying like we just got the root only okay so it doesn't have any leaf node so it just has a root only so for that one obviously simply written one over here because you know the only one known as present so what else i have to do nothing okay gentlemen now here the things come now one condition come over here the condition will say let's say like we don't have the uh left leaf okay we don't have any left path we just have the right path okay so for that what i will do i will just simply say okay if my root dot left is null if my root left is null then do one thing then go for the right one return is minimum depth from this root dot right okay like this and don't forget to add one in this one why plus one because you know we have to uh have this root value as well so let us say like if we are over here let's just say we are over here and we come over here and then let's say we just go over here again straight forward so this is one and this is two but we have to put this one as well so that's why we are doing plus one because it's already have two no plus one for this one so that it can get three okay gentlemen that's what i'm saying but there's the minimum i'm talking about the minimum one there's the maximum so in this one you know the case is like we don't have the left for right now that's what i'm talking about now similarly i will talk about let's say like we don't have right as well so following in general i also know like you're just like what the chord will be right over here if you don't have the right one if our right is null then i will simply return i will say let's go and find for the left one two dot left and plus one ladies and gentlemen so that's how we are uh solving our problem and finally i have to return back document of minimum of left corner right so what i have to do i will say minimum off uh i have to call the function for this one mainly depth and already enjoyment like i have to add organization i hope so you forward this thing but we have to add plus one over here as well and ladies and gentlemen that's all our kodi so i hope to the code is if you still you don't understand like what we are doing let me just first of all run it to see any compilation error we are facing over here then i will uh work it through the quota back again okay so ladies and gentlemen these two our base condition this to our base condition okay and in this one like okay let me explain about the base connection the person is like if we just get empty room therefore that we will simulate zero because there is no reason let's say we have some known one over here for that one i just say like okay go for this one so like uh it doesn't have any left it doesn't have any right then just simply uh written the one then we simply did another one now let us see like we don't have the left one in this one we don't have left and left one we'll go for the right one and return the minimum one between the minimum one but let's say uh we don't have right we have the only left so the i will simply go for the left and return left plus one that's all ladies and gentlemen we are doing okay uh lastly what i have to do i will simply say okay if we have these two things if we have left and right then do one thing then go for is the minimum one or either on the left either on the right and return it over like in this condition the minimum is this one so we got one over here and i have to add plus one as well because you know the root we have to count the root as well so one plus one will be two so i have to write it two in the final output as you can see in this test case so ladies and gentlemen i hope so this code is clearly like what we are doing over here so ladies and gentlemen let me just submit it and i will uh talk about its time complexity and the space complexity in this one and here we go it is accepting very well so what the time complexity in this one we are doing the time complexity is big off and because for the worst case okay ladies and gentlemen and the space complexity in this one we are dealing with this big of one for the better case but for the worst case it could be big of n minus one okay ladies and gentlemen so let me just put it together for the better one and this is for the first one i hope so ladies and gentlemen this thing is clearly like what i'm doing over here so thank you ladies and gentlemen and if you still have any doubt uh in this problem then just do let me know in the comment section i will definitely want to reach to you and thank you very much ladies and gentlemen for watching this video i will see you the next one till then take care bye and i love you guys believe me i love you take care | Minimum Depth of Binary Tree | minimum-depth-of-binary-tree | Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
**Note:** A leaf is a node with no children.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 2
**Example 2:**
**Input:** root = \[2,null,3,null,4,null,5,null,6\]
**Output:** 5
**Constraints:**
* The number of nodes in the tree is in the range `[0, 105]`.
* `-1000 <= Node.val <= 1000` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | 102,104 |
258 | hey everybody this is larry this is day eight of the leeco daily february challenge hit the like button hit the subscribe and join me on this card let me know what you think about today's farm which is add digits i am still in the city of hopefully i'm seeing that a little bit closer uh any uh south american uh people want to correct me let me know uh maybe it's getting better but yeah uh so i'm still just hanging out check out my instagram if you're curious about what i'm up to um maybe one day i'll post a couple of drone for uh videos here uh if that makes sense but uh but i'm not gonna use it on add digits what is this 258 digits easy okay repeating at all digits until the only have one digit and we turn it so yeah so i mean obviously the way to do it is just um the way to do it is just by you know it's just by assimilating it with loop and requestion and so forth um the weird thing of course is that there is this follow-up course is that there is this follow-up course is that there is this follow-up which there is a trick i don't um i don't know if there's uh how do i think about this can i explain this i don't know i'm not gonna lie this is just one of those things that i just remember uh and it does come up a lot in competitive programming though not necessarily interviews per se in that um hopefully this is right otherwise i'm never sad maybe i missed the edge case i think i missed an edge case wait did i okay maybe i'm just thinking of something else wow um is that not right six four five nine six four five oh zero yeah that's right um if the answer is nine yeah i forgot about this case but that's generally the idea um why is this well i guess if the answer is nine that's also wrong right uh clearly i actually forgot the other case now that i think about it so maybe we can take this as an opportunity to um to go over it um that said i don't know the follow-up does make it i don't know the follow-up does make it i don't know the follow-up does make it not as easy the easy is if you just simulate it which is doing it one at a time uh how do i define this but what is because a what's two plus eight plus five plus six plus seven plus three plus five um you know is it always just going to be nine yeah because it's not possible to be zero right so um well it is possible to be zero if it is zero um otherwise okay fine let's just write it out then if number is equal to zero we turn num uh otherwise we turn this unless it's zero then you add nine right um because if this is zero i'll just write it out except try to be clever if digit is equal to zero digit is equal to nine oops return digit right and it's uh it's kind of magical so i don't know how to kind of explain it to be honest uh i mean other than that just comes up a lot in competitive programming so i kind of internalize it uh to be honest um but i also don't know that this would be an interview thing so you could take it as you will maybe it is i don't know if this is because this is just trivia at a certain point you can definitely prove this uh by kind of playing around with the nine um and you can actually also if you want play around with non-base 10 numbers right so non-base 10 numbers right so non-base 10 numbers right so this property that i'm doing now only works for base 10 um you can play around with different bases and see why or how it doesn't work and i think that will give you an intuition about how to get around it um but then another way of saying it is kind of you know we have 10 well ten is just um nine plus one right so in that way you can kind of uh figure out how to um yeah and then all these nines kind of uh take the essence away from the digits kind of uh i don't know i don't feel like i'm explaining that well so maybe just like explore it yourself ask me in the comments ask me on discord let me know what you think um but yeah that's what i'm gonna have for today and it's supposed to be easy and i kind of showed you the cool way so i don't think this cool way even though it's cool but it is trivia i don't know that i considered this um you know that seriously what are the hints that they give you yeah okay what are all possible results yeah okay how do they occur periodic or randomly yeah okay oh there's a wikipedia article maybe that oh digit that is the name of things i forgot about this name um but yeah so definitely apparently in the hint you can learn as much as you like so yeah there is some congruence type things but yeah oh i did not submit watch i get wrong on this that'll be funny um but yeah but it is accepted even though it's slower than last time what did i do two years ago a year and a half ago huh okay so i just did a some thing to eat and that was man okay anyway um cool that's all i have for this one let me know what you think uh stay good stay healthy to good mental health and i'll see you next time bye | Add Digits | add-digits | Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
**Example 1:**
**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
**Example 2:**
**Input:** num = 0
**Output:** 0
**Constraints:**
* `0 <= num <= 231 - 1`
**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime? | A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful. | Math,Simulation,Number Theory | Easy | 202,1082,2076,2264 |
20 | hello everyone and welcome to python programming practice in this episode we're going to be covering lead code number 20 valid parentheses this is marked as an easy problem we'll start by reading through the problem description and examples so given a string s containing just the characters these things the various open and closing braces and parentheses determine if the input string is valid an input string is valid if open brackets must be closed by the same type of brackets and open brackets must be closed in the correct order example input s is just this that's true because there's one open parenthesis and one closed parenthesis and it's in the right order example number two you pass a string that's this well that is also true i guess because that is valid closings this one is closed immediately this bracket is closed immediately this curly brace is closed immediately those are all properly closed and the third example we have a open paren but then a brace a closing brace after that's false because that's not the right symbol to close it so in this fourth example we have an open parenthesis and then open brace but then we have a close parenthesis and a closed brace and these are appearing in the wrong order this open brace needs to be closed before the outermost parentheses closed so this one is false and then the last example is just another one that's true we have some opening curly braces opening brackets but they're closed in the proper order so the innermost thing needs to be closed first and it is so that one is true and then the constraints for this problem the length of our input string is going to be between one and a thousand and then the s consists only of parentheses characters so we're not going to see any weird characters that aren't at least one of these six things so we don't have to deal with stuff like that so let's start by pulling up a whiteboard and see about how we could go up coding a solution to this so i have a potential input string here on this whiteboard just to think about how to approach this problem and the important thing to realize about this problem is that the innermost parentheses always needs to be closed first and there's only three different possibilities that could be it would be uh open and closed paran an open enclosed brace or an open and closed curly brace those are the only innermost things that can exist that are valid so if it's a valid s string of opening closings these things will have to exist somewhere within the depths of the openings and closings so basically one way we could approach this problem is look in our string for any of these three valid closings that have to exist somewhere in the innermost part of our parentheses and find that and just remove it so that basically removes the innermost closing and then whatever was outside of that becomes the new innermost thing and then we just remove that again so for instance if we had this input string we'd say okay let's see if this exists in here well it does it exists right here so we'd want to find that remove it and then we'd go to a next iteration of a loop and see okay well now where what are the innermost things and we'll remove that so now the innermost thing would be this closing brace but if this thing was removed these would be right next to each other so it would just be this and then we would want to remove that and there's actually another one here so we want to remove that one too and then we go through a next loop and at that point the only thing left in this whole string would just be one opening and closing paren and we'd remove that and at the end of all those removals we just end up with an empty string because we've successfully gone through and removed everything that has a opening and closing that's valid so basically all we're going to do in code here is go through our string and see if any of these exist within them and if they do we'll just replace it with nothing so replace it with an empty string and we'll keep doing that until we don't find any new things we can replace and if we're left with an empty string then it was valid and if we're left with something else then it was invalid so let's go ahead and code up this solution so now we are in the code editor here we are given a function called is valid we're past a string s that's what we're going to be operating on to see if it's a valid parentheses so we're going to call this method inner string replace method so what we're going to do is we're going to have a loop keeping track of if we're able to replace something every time and if we're not then we're going to exit the loop and see if we're left with an empty string or not so we're going to have a variable to keep track of if we were able to replace something so we'll start off being replace equals true while we're able to replace something and then we need to keep track of if we were able to replace something after this iteration of the loop the length of the string should go down so we'll keep track of the starting length will just be the length at the start of the loop and if this goes down after we try to replace things then we know we are still replacing stuff so the start length is going to be that and then for any valid inner parentheses so inner so for inner in and we just need a list of all of those valid possibilities that we want to replace so they were an opening and closing curly brace and opening and closing parentheses and an opening and closing square bracket so for all of these possibilities we want to essentially try to replace them with nothing if they exist that is removing whatever they are as the innermost opening and closings and getting rid of them like we looked at on the whiteboard so s equals s dot replace uh the inner with nothing so this is just going to go through the whole string see if it can find any positions where these exist because that would be an innermost opening closing and just basically stripping them out so that we can go to the next iteration in the loop and then see whatever was one step out from that we'll strip out after that so after doing those strips if our start length is still equal to our new length after we strip some stuff well if it's equal to the length still that means we didn't manage to strip anything which means replace is now equal to false and will break out of the loop but if the starting length is different than the current length after trying to strip some things then we know we strip something and we need to go through another iteration of the loop well that shouldn't say right that should say while and so this should go through the string doing all of the strips from the inside to the outside so if we're left with an empty string after this while loop exits that means we stripped out everything in the valid inner to outermost order and it should be a valid parentheses string where passed and if it's anything different then it should be invalid so we're just going to return s equal to empty string so basically if s is equal to the empty string this will be true and if it's not it'll be false so this should be a working solution to the problem here so i'm going to go ahead and click submit let's pull over and see the result of the run here so it did pass in 36 milliseconds faster than about 14 of other python 3 submissions so although it did work and it wasn't too difficult it doesn't seem to be a particularly efficient solution because it's not faster than most of the solutions other people made and there's various reasons that could be i mean we're having to check whether each of these exists in the string over and over again so that's doing quite a few operations and there's probably ways to avoid doing that so let's go back to the whiteboard and think about another possible solution to this problem maybe one that is a little bit faster or better than the one we had just made so the important thing to note here is that anytime we see a closing character it has to close the last opening character that was seen so for instance in this string here we see this first that's opening we see this next that's another opening but then we see our first closing character and this closing character has to match whatever the last opening character scene was so when we see this we can check in this little stack we've made here is that there and it is so in this case we'd say okay this does have a matching thing is the last thing we saw then we could remove this from this kind of stack we're making and then say okay what's the next thing okay it's another closing thing uh what is the last thing we've seen on our stack that hasn't been crossed out yet okay it is another closing brace we could cross that off we go to the next thing what's left on our stack it's a closing brace we cross that off etc so instead of kind of replacing things like we did before we could keep track of all the opening characters and then as soon as we see a closing character we can remove the last opening character that we saw using this kind of stack data structure so basically anytime we see an opening character we'll push it onto a stack and then any time we see a closing character we'll try to match it up with whatever the last thing on the stack is and remove that from the stack and after going through the entire string doing that we should be left with an empty string where we were always able to match the closing character whatever it was with the last thing that was on the stack and if that's ever not the case then we know it's not valid and we just immediately return false and a solution using this method should be faster than the one we made first because we're not having to look through the string many different times and trying to see if things exist in it and replace them we're basically just going to have to go through once we'll just loop through the string once and we'll keep track of all the openings and cross off the closings as we see them so that should just be a straight up of n solution instead of something where we're potentially having to search through the string several times so let's go back into the code editor and add this solution as well so we're going to call this new approach close the last scene opening symbol with stack because that's an important part of the problem so i did go ahead and prepare uh this ahead of time just because i didn't want to type all this out but basically all this is doing is giving us a little dictionary that's mapping each opening character to its closing character called close map so an open paren is mapped to a close an opening curly brace to a close etc so we're going to need to use that just to make sure we can match things up efficiently and now we have to initialize the stack that is going to keep track of all of the opening characters we've seen in order that we see them so let's call that say opens it'll be start off as an empty list and then as we see those opening characters we'll append them onto the list and now all we have to do is write our single for loop and go through and implement the logic so for symbol in s if the symbol is an opening character which is anything in our close map the keys of the closed map are all the opening characters so if symbol that is a symbol in closemap.keys that is a symbol in closemap.keys that is a symbol in closemap.keys then we want to put it onto our stack so opens dot append symbol so that's saying anytime we see an opening character we want to put it onto our openings stack or list here so now if we didn't see an opening character that means we're seeing a closing character and we need to handle that case so in that case alif else if so if we have a closing character and our opening stack is empty that means there's nothing in there to close it off against which means we're seeing a closing character before we saw the appropriate matching open character and if that's the case this isn't a valid parentheses so we just want to say false on that so if opens is empty in that case so we're looking at a closing character but we don't have anything to match it off against that's going to be false now there's another scenario where the closing character we're looking at here might be the wrong thing and we should return false and that's if it doesn't match up with the last opening character that we saw so or if the symbol we are looking at does not match up with the last thing that we saw so our close map the last thing that we saw was opens the last thing it opens which is opens dot pop so basically we're treating this list as a stack so opens.pop is going to take the last so opens.pop is going to take the last so opens.pop is going to take the last opening character that we saw and take it off the end of the list and we're going to pass it into close map to find what the appropriate closing character should be so for instance if the last thing we saw was a open parenthesis we're popping that off of the end and then by passing it into the indexer for close map we're saying okay this should be the matching closing character so if our closing character is not equal to that matching closing character that it should be then we know that it matched the wrong type of thing and this is also then an invalid uh sequence and we should return false so basically if the opens is empty or if the closing character doesn't match the closing character that should be we need to return false so now this loop here should be going through the whole string any time it sees an opening character it will put it in our open stack and anytime it sees a closing character it will pop off that last opening character we saw see if it matches up and if it does it'll continue on to the next iteration if it doesn't it'll just exit and say false but after this runs through the entire string if we haven't found a situation where we didn't match what we wanted to that means we got through the whole string and didn't return false yet so if we get to the end and that's the case and we still haven't returned yet that means the only other situation where we might have an invalid string is if we had more opening characters than closing characters that would mean that the open stack here still has some opening characters on it that haven't been closed yet and if that's the case it's going to be false so what we can just do is return well if opens is empty that means all the opening parentheses were appropriately closed so basically all this is saying is if we managed to close everything that we opened then we should return true and if we didn't manage to close everything that we open then this will be false oh i noticed a problem here we're going to have to return false not just say false so i'm going to go ahead and click submit on this one and hopefully there are no issues it is running let's pull over and see the run so this time we got a speed of 28 milliseconds which is a bit faster than the first attempt and that was faster than 82 of other python 3 submissions so i hope this gave you a couple ideas about how you could approach a problem like this and hopefully also illustrate a bit about the value of a stack data structure so something where you put things in sequentially and then you take off the last thing that you saw first so a last in first out type data structure can be useful in certain applications so thanks for watching and keep coding you | Valid Parentheses | valid-parentheses | Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
**Example 1:**
**Input:** s = "() "
**Output:** true
**Example 2:**
**Input:** s = "()\[\]{} "
**Output:** true
**Example 3:**
**Input:** s = "(\] "
**Output:** false
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of parentheses only `'()[]{}'`. | An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
{ { } [ ] [ [ [ ] ] ] } is VALID expression
[ [ [ ] ] ] is VALID sub-expression
{ } [ ] is VALID sub-expression
Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g.
{ { ( { } ) } }
|_|
{ { ( ) } }
|______|
{ { } }
|__________|
{ }
|________________|
VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards. | String,Stack | Easy | 22,32,301,1045,2221 |
73 | foreign next problem is called set Matrix zeros and in this problem we are given an N times n integer Matrix called Matrix and if an element is zero we have to set the entire row and column to zeros and we have to do it in place so for the for example we have the central zero so we have to make the second row and the second column in a matrix three times three to zeros and as you can see here we did that in the second example we have the zero at the located at the First Column first row so we have to make zero we have to make zeros all the elements that are inside the First Column and inside the first row which we do after the transformation and our second zero is in the first row we already transformed all the numbers to zeros in the first row the remaining work is to transform all the elements inside the last column to zeros which we do here um the m and then are just major dimensions and they can range from 1 to 200 and we have a normal distribution from the for the elements of the math matrix ranging from the minimal integer to the maximum intellectual integer now if we move uh we also have some additional follow-ups uh first is that's additional follow-ups uh first is that's additional follow-ups uh first is that's a straightforward you so solution using M times n space is probably a bad idea um that means that we would have to basically create a the same uh same Dimension Matrix as our input as additional space we will try to do it in less space so that's the second follow-up simple Improvement uses M plus follow-up simple Improvement uses M plus follow-up simple Improvement uses M plus n space but it's still not the best solution and our desired solution uses constant space so we will know how we will see how can we derive the cost of space solution so here we have an example and this is the Matrix for the from the second example from the program statement and as you can see we have here um additional data structure these are basically just arrays um and they are of the same so this array is of the same length as the number of columns which is four and this is basically a number of rows which is three in the in our example so to get the Matrix to get the desired Matrix transformation we will Traverse The Matrix which is basically M types and time complexity and if we see for example in the first column if we see in the First Column so after returns like this if we see a zero that means that we have to mark the corresponding row and the column that has to be transformed so for example here we have so this can be a Boolean and the default value will be false and you see that our first element is zero so we have to transform we have to say that our first row should be all zeros and also our first column should be all zeros next we go to the element one and in this case it's non-zero element so we this case it's non-zero element so we this case it's non-zero element so we still have faults here inside the second column and also we don't change the value for the first row because it's set to true then we move to number two we still keep the true be not we do not overwrite the True Value in the first row because we know we have to transform all the elements inside the first row to zeros we just put uh we keep basically the third value because in the input the Mad matrix it's not and then zero it's a non-zero value not and then zero it's a non-zero value not and then zero it's a non-zero value so we just keep our full swap in this additional data additional array and the last element zero so we have to put true here because we have transformed the last column as well we have to transform all the elements in the last column to zeros as well Now we move to the uh to the next row and as you can see there's no zero elements in both of the rows so this will remain false we don't have to transform the second and the third row and also these values here these false value will not be turned switched to true because as you can see here both of them don't contain the only contains the non-zero elements only contains the non-zero elements only contains the non-zero elements there's no zeros inside these two columns now we can use these data structures to control uh the transformation of the Matrix so basically if we have true here we will Traverse this array and if we have true here in our input Matrix we will transform the whole row to uh non-zeros to zeros in this case to uh non-zeros to zeros in this case to uh non-zeros to zeros in this case so because it's true it will if all of them will become zeros then we go to the second uh element in this controller array and it's false so we don't do anything with the second column same goes for the third column and for the fourth column we transform everything in the fourth uh in the fourth column two zeros we do the same then traversing this array for each row if it's uh if this value is true we transform all the values in the input Matrix to zeros here is false so we will just keep the values as they are and so on so in this case we would have M plus n uh space complexity because we have to create an array that size of the number of columns and also on the rated size of the number of rows but the thing is we want to reduce this to constant space so in this case as if you can notice that our first and let me just quickly switch to another color here our first row and our first column can serve as these control arrays and what I mean by that we will use the input Matrix actually a part of it the first row and the first column to mark that the specific column or a specific row has to be transformed to zeros and we will do the same transformation as we did here so uh we will just instead of using true and false we will just put zeros inside the inside element so for example uh here we in the first row we all of them will become eventually zeros because we have a zero inside the as a first element example here and the only thing that left to do here is to before we use the first row and First Column as the controller arrays is we will Traverse it both the First Column and first array to check if there are zeros inside of it before we do transformation before we start to insert the zeros and specific columns um or rows and if we will just have two booleans uh the first row has uh has a zero and the First Column has a zero so we can accordingly transform both the first row and the first column so let's hold this problem using Java program language first we will just for the readability purposes we will Define our Dimensions rows and columns uh then we will declare two booleans uh for um tracking if our first row should also become zeroed and uh if our first column should become zero and that basically means that First Column or the first row contain zero themselves next we will Traverse through the first all the first uh the first row and if there's any zero inside the first row We Will declare our zero first row uh we will set it to true and the same goes for the columns uh we'll Traverse our first column and if there's a zero in the First Column we will just put the set the zero First Column to true by doing this after we are done with reversing the The Matrix we know that if the zero first row is equal to true we know that we have to zero all the elements inside the first row the same goes for the First Column if it's at true we know that we have to zero all the numbers that are inside the first column now we've traversed to The Matrix first iterating through rows it's a standard double for Loop um and checking if the number in the current number it coordinates I and J is equal to 0 and if it's equal to zero we will set the corresponding Row in the column and we will do this by using our first column and first row so for example if we have a zero element inside the second row second column we will set 0 to our second element inside our first row and our second element inside our first column so that we know that we have to zero out all the elements that are inside the second column and second row which we actually do inside our next four to four Loops we check we first we Traverse row by row and for each uh for each row uh we check in the First Column if the value is equal to zero if it's equal to zero we have to transform the whole row to zeros we do basically the same now for the columns we to reverse by The Columns and for uh for each um inside each column we check it uh inside our first row that we have uh a zero value if you have it in that position declares what column which column should be zeroed out and the remaining thing to do is to check if r0 for a show we set to true in which case we zero out the whole row and if our zero First Column if our first column is um uh contains a zero and if it does we just zero out the whole column in this case we are using only the input Matrix itself so the space complexity is constant while we have at most traversal two Matrix which is um basically the product of its Dimensions when it comes from times time complexity which in this case is just m times n where m is number of rows and then it's a number of columns | Set Matrix Zeroes | set-matrix-zeroes | Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s.
You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
**Example 1:**
**Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\]
**Example 2:**
**Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\]
**Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[0].length`
* `1 <= m, n <= 200`
* `-231 <= matrix[i][j] <= 231 - 1`
**Follow up:**
* A straightforward solution using `O(mn)` space is probably a bad idea.
* A simple improvement uses `O(m + n)` space, but still not the best solution.
* Could you devise a constant space solution? | If any cell of the matrix has a zero we can record its row and column number using additional memory.
But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?
There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero. | Array,Hash Table,Matrix | Medium | 289,2244,2259,2314 |
374 | Hello hello guys to Ajay, I asked on this occasion that Sachin himself will submit this question, it is a festival whose religion is on this number and people ask this question once, this question also for a little bit, after this see what problem has to be set here too, then you can understand this thing. Okay, and you add this number, okay, so like number one number 10, now tell me this, I only know this much information on the number, so to use one thing, stars are included in the function from the beginning to the end with many numbers. For now, I am in the West, in which he has shifted, to tell me which number, but the problem statement in front of me is so big, okay, the problem statement in front of me is so big, from one to three to the toilet. Pushpi till now Singh is that he gave me the facility to use the day function and that function called gas. If I called him and I asked him, I have not done anything till now, my friend, you did not get 982 gas, so it is okay to think. I asked him did you get it done somewhere in the 90s? He will not answer me in true or false. He will ask here plus one here - mother these days ask here plus one here - mother these days ask here plus one here - mother these days ask on glass - 140 show some of these albums ask on glass - 140 show some of these albums ask on glass - 140 show some of these albums when he will answer me plus one then he is saying that The number that has to be picked up in it, are you thinking that it is from my gas number which I have just added to you, then its plus will tell in Mandalgarh only that if you click on it is higher than my guest number. - Mannat, the number he has to pick is - Mannat, the number he has to pick is - Mannat, the number he has to pick is based on my gas number and if he returns it then I will be happy because the number he has to pick is the same as the one I have just dialed. Okay, so actually the question remains. The only question left is that there is such a big problem in front of you do the statement on one number, okay that Yadav President will do it, he will say that do it on the number, which number is bigger than yours or - 110 will spoil that page number and is bigger than yours or - 110 will spoil that page number and is bigger than yours or - 110 will spoil that page number and this number of yours. If the number is less than 1000 and will return zero then the number he has to pick is equal to the office number so earlier that day this is the number which we have given that the gas is bad which will return to me, this is the problem state this is the problem because of this I am in problem. Optimization can be done to find his pick number. Okay, I do n't need to travel from one to 100 so that I can click and do the driver. Okay, on this day, place him on the gas off number. It's Friday. Guess that number. I will sit, whatever he had to pick, it is okay, so I do not need to type from one to thousand, but I will do, I can do binary search on it, by typing OK by less, we will see these three options, which one I It was okay to go to the area, the day my Gas Karao number and his pick Ravana number became equal, that day it is very big but if there is any one of these situations, it means when Laxman returns and again set it on the number. One this greater than gas to pick this greater than job also I do gas his own you can understand this we understand that cigarette inside we here what he has picked fix smaller than thumb and finally here pick in juice the karma is equal to that In this, if I gas now, then these three situations mean taking Edison, if pick and we are equal ahead, then it is very good, if cigarette Annamma is either off, Hello friends, Elephant and I will cut off the points, I will then cut off Vansh but will not search a bit, get her picked, number if half. Bigger than toilet vs part is ok and if the pickup number is smaller than my gas number then I will cut the right side police and give it on time in school tiffin, it was just a matter of reading out and applied whether you will set it now it seems As to how you will apply it, there was a little board problem, this too there was butter in front, neither was it as simple as applying chilli once in front, like let's say just tomorrow, I will tell you in these short words that I am going to do nothing, just apply it. Here, for example, if you and I show you a little travel, then she is putting a little note on it and now name it after keeping it as Noida, then I understood, then I would have written it like this, it is a generalized fault, it is okay that I am basically I am waiting to see what will happen and how will I know that he decided to use gift to me. Find the function called gas. So he will know how close his pick number was to my number. It is okay for you in short. Wise that we will make it on one and we will make it for ₹ 1000, I have written a tremendous letter to you will make it for ₹ 1000, I have written a tremendous letter to you will make it for ₹ 1000, I have written a tremendous letter to you will understand something, I took it out for the first time, if I say installed, then I took out the name, I am guessing this number is lagging behind in it, so I took out the minute. How much will it cost or in minutes will it take to get your money? Private data is laughing powder type. If you understand then by now we will pass this 518 to gas. I was shifted to the accused. When I pass this favorite, what will be my return? I will get return plus. The one which is telling me that sorry laughed, I will have a liter - - - The that sorry laughed, I will have a liter - - - The that sorry laughed, I will have a liter - - - The temples are telling me that if I pick her up with my gassed number then it would be better to make her number smaller than mine. But if the number he has picked is small, like me, he will make it - 110 - like me, he will make it - 110 - like me, he will make it - 110 - I will say that brother, you will get 500 help, you are not going to get anything from phase to 100, by picking it and keeping it at minute minus point, by picking hike. Keep it at 499 and continue your setting from closed to 489. By calling the same gas after the same guest, half of the problem statement and half of the problem have disappeared just like that, so the thing became its bani asra and paid for it. Ok, so try traveling on this bike, you will keep getting looted till now, you may not understand but friends, if you had taken it out, I would have taken it out on the media, it will cost Rs 250, but again get it picked up, the number is smaller than the number one, please gas me. Then again I will say - If he does smaller than the number one, please gas me. Then again I will say - If he does smaller than the number one, please gas me. Then again I will say - If he does 110 then I will say again that it is okay, it means that from 250 onwards there is nothing to be found in the point name, pick it up and keep it in your mind, now keep the spark again, okay then interest, this thing will be imposed, right? Very good, this is also a job. Judging this problem statement, I will write it quickly for you. Okay, so let's write this quickly. Okay, so what do I have to take here? He could have done it initially, so keeping it on the people, Sachin. Will continue and till you subscribe, before doing my work, I am adding this number to know how to do this, remember that now the school has given you the result, so you are asking this, how far is it from her house, she keeps the name. I am this jerk, then you can name it anything, it doesn't matter otherwise, the midwicket pick which he had picked is exactly the same, so I have guessed which number was to be picked in this, so I will return the minute we picked this number. Had done and if there is nothing other than this then we will choose a direction. If gas fennel I have returned here - If gas fennel I have returned here - If gas fennel I have returned here - do not mean then it meant that pick his worker and use my number which is less than one number. So I write here that his picked number is smaller than my gased number, then it means I should continue Sachin on the left side. To continue Sachin on the different side, keep it at the minimum that brother here is the area. Go in and the simple meaning of the next one is, what will be the simple meaning of gas after minute, I will return plus one. Okay, if you don't want to write like this, then write it like Singh Sarpanch as you like. Turn on this clear minute or in the form of plus one. This means that its sold value has increased from my gassed WB, so I should continue Sachin on the right side, people should pick up and keep me, I will be on Mitt Plus One, while doing this, I am sure that from here on From here something or the other will be returned but if this is a claim then I will have to write minus one outside as well. It's okay because it has to be satisfied that my function will always retail. Tell me my answer will be returned from here but still Tuesday sweater. If the compiler is fine then run it once and see once it makes profit. So we have made this number. If his pick is equal to our gas then it is great. If his pick is smaller than our gas then let's go to the left to search and if Its pick is big like us, so right, I will keep searching, it is very good, I would like to run it once, okay, now it seems right, Hmm sir, after understanding one thing, I will kill him with this, if the testicles are nearby. I hope you would have liked this portion, there was nothing, but we will see about it, I would like to repeat this further, such questions take more time for God's testing, the questions are very easy method or but the statement might be a little bit confusing like you here if you pay attention to them. If you will not study from, what does minus one represent, what does plus one represent, what does zero represent, then it is possible that you may spend a lot of time in a very easy question, okay, so you will have to have a little patience at that time. But Syed, we meet him in this video OK GO O Shravan | 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 |
289 | hey everybody this is larry this is day 12 of the april eco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom today's problem is game of life okay um i guess the game of life is pretty standard so let's take a while to see how everyone else is doing uh yeah so there's a this is monday or tuesday wherever you are i hope you are having a great week uh everything's going okay i am going to i don't know let me know what you y'all been what movies y'all have been watching i've been uh going on watching a lot of movies lately let me know in the comments or discord there's a lot of cool smart people hanging out on discord i need to create some thing also if you're in new york let me know if yeah on discord because i think we're trying to get some like hangout or whatever going around um we'll see where that goes anyway today's problem is game of life so we know what game of life is i do if you know then i guess you know that's what this is reading and i guess it's good um you know uh whatever but let's look at the follow-ups just because you know this is follow-ups just because you know this is follow-ups just because you know this is pretty straightforward could you solve the price solve it in place uh remember the board needs to be updated simultaneously you can update some cells first and update okay and this question to the array in principle the board is infinite what would cause problems when the act i guess this is just talking about it um yeah i mean i think you can always do something like uh repeat doubling is always a an option um i think the thing is that you're trying to do the math on the repeat doubling and of course if you do the math um on the repeat doubling which is actually comes up in hash tables and stuff like this if you ever study it um then you'll know that uh maybe repeat doubling is in the but basically once you get to some fill factor in this case you could wait until it hits the border then you can double it right in that case it's going to be amortized constant just because you can't do the math the same way you do it with hash tables i think that problem we could talk about that if y'all like but that's basically the idea that i would have there um so in the two dimension maybe that's a little bit more tricky but i don't imagine so um because i think you could treat the dimensions independently in any case for in terms of uh that um of course you can also treat maybe sparse arrays or a boss matrix and play around with that depending on how it goes i don't yeah it may be a little tricky uh the second part which i guess we'll try to do now is to impress because this is relatively straightforward um i don't think this would be a medium anymore to be honest just because this problem is very old but um with that said not to say that you know in an interview it would still be okay but um but yeah uh so how would you do this in place i actually don't know let's see i think it's so there is a cheating way of doing it in place but i don't like it which is just you know you see that these things are ins so you kind of use like the upper bit or maybe use like another bit right off that inch because an inch could fit 32 bits or whatever so you could play around with that idea and that'll technically work so that's fine maybe but i feel like that's almost cheating and not in the spirit of things um because maybe one of what these are bullions right so then can you do that in that way i think in that case i would have to look at the rules and kind of think about it which i haven't done yet to be honest uh i hope it's not the upper bit thing because that's like uh i consider almost cheating or it's like it's not that interesting right like you just use more you use extra space just embed it into the thing or something right um okay so the rule is fewer than two is dead um so i guess the way that i would think about solving this if you have to update this simultaneously so to speak is that um you try to you know it is simultaneous you try to exploit the rules in a way such that it is not simultaneous right maybe it doesn't make sense for the game of life but there are rules where okay you maybe change it to zero because no matter what happens the change to zero will always be true etc right um so yeah so i think i would see it that way and then see if you could figure out some ordering in which you can do it i don't know that i remember my experience of game of life is that i don't think that's the that's a thing but i could be wrong here um let me see let me i do have to go watch a movie so uh that me that's why i'm asking i'm watching in case you're wondering at home uh everywhere everything everywhere or at once someone like that um it's got great reviews i'm gonna try to catch tonight show um but yeah i don't know um i mean yeah i don't know if i know one that isn't like quote-unquote cheating and if we are quote-unquote cheating and if we are quote-unquote cheating and if we are going to cheat i don't feel like you know like if you're gonna do some kind of hacky things like that then i at least i always opt for making more beautiful code unless you um need to optimize right like there's no you shouldn't prematurely optimize because if you uh like if you like maybe if you're doing like embedded systems or you're put putting it in your handheld which at least way back when a day like uh maybe that's a thing that you have to consider uh like space efficiency like programming for nintendo like you know 20 years ago or something like and yes uh maybe more now 20 years ago even um the playstation's already out but you know i can't do math all the time so um yeah uh i don't know i don't think that there is i would be honestly a little bit kind of surprised um if you can just because and some of this is arrogance in the sense that if there's a way to do that i would have known already in the sense that i have you know and this is maybe you know applied to your career as well is that when you have um oh my alarm calls me hang on um i had to tell my alexa to uh oops now it got triggered again to turn off my uh my alarm because it just kind of it was to wake me up in case i was taking a nap too long um but in any case um yeah so that's what experience means right is that you know you have seen it enough and i've seen the game of life a lot of variations a lot of time it comes up on aoc uh the advent of code it comes with a lot of it is a very um you know finite automata type thing where everyone's just very interested in this form and a lot of uh um uh there are a lot of uh what you might call it uh there are a lot of easy computer sciency problems to explore with just like symbol ruleset right which is why it draws a lot of people to it and you should read the wikipedia article um uh by the you know mathematician conway he passed away two years ago i want to say um that was kind of you know sad obviously but um so yeah so definitely like to that sense and i probably have been very interested in it at some point in the past especially this idea of um you know if you really read deeply into it and you know i encourage people who are interested to do so um there's also like this stuff with respect to roof rooms uh a new kind of mathematics i bring us the book i'm calling it off my head so if i miss uh name some books or whatever leave a comment or google or whatever but yeah so definitely it's just very interesting and my point here is that if i have known it maybe i would have seen it i mean i'm not 100 certain i you know i'm i have a lot of gaps in my knowledge like the z algorithm from the other day but yeah but that's what i believe so before that said that's just my long way of rationalizing and explaining to you that i am just going to do it with the extra bit the cheating bit um and then um well i'm going to do it in another way right and then i'm going to do it the extra space way and then i'm gonna rewrite it so that you can see what it looks like um when you have the cheating bin as you call it um i quit that but it's not maybe it's fine i don't know okay let's get started let's just go um how many iterations do they want i actually missed that part is it just one state okay so it's just the next state um okay so yeah so you just do next board is equal to uh well let's set it up r is equal to language board c is a link for port of zero uh just making sure that it cannot be zero so okay otherwise you get a whole bounce uh okay so then here we set it to force times uh c right so now we're just saying of ic board so now we go for x in range of r for y in range of c we go maybe do something like uh you only care about live neighbors in these rows so maybe we do like if count oops counting of x y uh or maybe just c is your count of x y so then you can do uh and then you could do all sorts of permutation meaning if point sub c i don't like this one zero thing but it is what it is so because i think that's i don't know okay uh oops board of x y if this is um let's see fewer than two oh this is one um okay if this is one i mean this is just really going through the cases right if c is fewer than two uh next for um x y is equal to force right uh yeah it else if c with uh is between two and three then next four x y is equal to true and then else i mean i also yeah i just want to be clear i know that i can rewrite this if statement in an easier way or shorter way but i want to be as explicit as possible so that is you so that when you make a mistake you don't have to just debug your logic you can just look at the code and look at how it translates to the rules that they give you right so that's basically the idea um okay otherwise um okay so that means that this is dead if c is equal to three next point let's go to oops true else next port stays dead right and then now at the very end uh we copy it back over right next and i know you can do some stuff but uh yeah but i like to be explicit for this particular example just for illustration there's no return but of course we have to write this count function uh which we haven't done yet um yeah uh yeah let's see right um therefore dx in range of from negative one to one of course it's one plus one because it's exclusive and i always find that a little bit awkward but i'm just writing it out so that you can kind of see what i mean but yeah if dx is equal to zero and d y is equal to zero we contain u i sometimes write this differently but today i'm just gonna write it this way so yeah i guess actually i guess one minor optimization i usually write it together but i guess i can do it here and also that if um we have to make sure that this is inbound uh so if not this contain you might have to need a parenthesis because i'm not sure um and then yeah just for symmetry reasons uh do the same thing here and then if uh okay so total zero if a board of n x and y is equal to one right and then return total so this should be okay i hope this is okay because otherwise it's embarrassing but i mean the idea should be okay it's just that might have typos and stuff like that right uh yeah so that looks good let's give it a submit apparently i did it a couple of years ago so that looks good right so this is gonna be linear time linear space um because we look at each cell uh maybe uh well let's say 10 times from left up down left right and stuff like that um and yeah and that should be good right like i mean obviously because we just got accepted so the way to do it in place and i don't i'm not a fan of this maybe we can kind of see if there's any clever way to do it in place um but the way that i would do it is just by instead of having this next sport um okay let's just say this is so awkward um let's just say we so now you can you know you can think about a binary bit as you know a number of base two so then we only care about the current board contains one bit and the most uh least significant bit and then one more in the second one and then we can store the next price here and then afterwards move it to the right so that's basically what we're going to do um we just have to make some changes here we would have to say if this i know that you can use a bitwise operation here for those smartypants so i learned advanced but um oops almost had a typo there but i wanted to make sure that you know i just want a mod 2 so that is clearer um and here we also want to um and yeah and that should be maybe good for now uh at least this part but here now we have to set up the next board right so yeah let's just say maybe uh next space is equal to force and then now we can just convert it here um and this is where um i talked about a little bit about don't repeat yourself and stuff like this um that's where this could be helpful by having a few if statements but that's okay we're going for the most direct code so that now uh before we might have what we in something like this right uh and that'll be fine but of course this doesn't exist anymore so what we have to what we want to do is store it in the upper bits right so then here um oh no not that uh is to go to um so yeah we'll be like we'll keep into deemed with being as explicit as possible but uh well yeah so then we add two if this is the case right um and then at the way n um yeah we can just do if this divided by two is equal to one um again i'm you know just being very explicit otherwise it's equal to zero let's try that again uh again like you know you can use bitwise operations i'm trying to be as generic as po well not as generic but i think as clear as i can to maybe possible newcomers and stuff like that let's give it a submit should be the same a little bit faster apparently but uh but yeah uh that's pretty much all i have again this is gonna be linear space and linear time i don't know like i said i don't yeah this is a little bit awkward so but you can do it if you like is my point what did i do in the past why is it faster okay i mean i did i guess i did the same thing pretty much i didn't want four opens i think the function cost probably make it slower but not by that much i don't care but yeah uh that's all i have for today game of life um yeah stay good stay healthy to good mental health i'll see you later and take care bye | Game of Life | game-of-life | According to [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. "
The board is made up of an `m x n` grid of cells, where each cell has an initial state: **live** (represented by a `1`) or **dead** (represented by a `0`). Each cell interacts with its [eight neighbors](https://en.wikipedia.org/wiki/Moore_neighborhood) (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return _the next state_.
**Example 1:**
**Input:** board = \[\[0,1,0\],\[0,0,1\],\[1,1,1\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[1,0,1\],\[0,1,1\],\[0,1,0\]\]
**Example 2:**
**Input:** board = \[\[1,1\],\[1,0\]\]
**Output:** \[\[1,1\],\[1,1\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 25`
* `board[i][j]` is `0` or `1`.
**Follow up:**
* Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
* In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems? | null | Array,Matrix,Simulation | Medium | 73 |
1,697 | hey what's up guys this is john here again so this time let's take a look at 1697 checking the existence of edge length limited path so i mean this is another graph problem i think it's quite interesting and you're given like a graph of n nodes and in the form of an edge at list which is a uv and distance between this between those uh two nodes and you're also given like an array of queries so the queries is also like a u and v where you can call it p and q right so u and v and then there's the limits so your task is to determine for each of the queries if there is a path between this p and j so the p and q such that there exists a path that the path on each i mean the distance on each of the edge is strictly less than the limit and note that there might there may be multiple address between two nodes right so that's the uh basically the uh the description and here's one examples here so we have the three nodes here zero one and two and we also have four edges here so four eight and from one to zero between one 0 there are two edges so one edge has distance 2 and the other one has 16. that's why we have a two values here and then we have a we have two queries so the first one is from zero to one so it's asking us to check so from zero to one the path right the path from zero to one if there is if there exists a path from zero to one i mean each edge on that path is the distance is smaller than two and the answer is false because the smallest we can get the smallest path from 0 to 1 is 2 is not strictly smaller than 2. so that's why we have fours here and then the second one is the from 0 to 2. if there's a path whose uh each edge is smaller than five and the answer for this one is yes because we can have two and four that so here's the path okay and yeah so that's the description and here's another examples here right and then the constraints so the constraint is what is the 10 to the power of 5 the other one is 10 to the power of 5 as well and here there might be multiple addresses between two nodes so that's the constraints um so the brutal force way the brutal first way to solve this problem is you know for each of the queries right so for each of the queries we'll try to you will try to find the shortest path between this p and b between is p and the q and the wow and basically it's a just like a diagonal that is through a problem uh solution uh we use die crystal to find a path that can give us the minimum uh the minimum distance on each of the edge and if that one is smaller than the current limits then we know okay so we will return true in this case for this query but the problem for that is that since we have a pretty big uh constraints here so for to loop through each of the queries we need a on time o in time and for the deck the dijkstra right so the dark throws complexity is another end of log e if i'm not mistaken so where n is the number of nodes and e is the number of edge so in total we have o of n square of log n i think yeah since the address also can be up to 10 to the power of five right so and this will go to e and that's why actually that's why this one is a it's a hard problem right and we have to find another solution to solve this problem you know a common solution for a graph problem if we cannot solve it in a traditional in a regular way is it's a union find because the union finds so the union find the time complexity for that you know after the path compression and some rankings we can consider uh both the union and fine to be o1 time complexity and we just need to find the relations between the unified uh characteristics and the queries and the answer for each query if you watch this if you read this thing uh more uh several times you might be able to find that you know actually so when will we return true right and when will we return false if we are um if we sort the queries by the limits okay and let's say we have some queries here we have queries from p1 to q1 right and the limit is s2 and then we have another one that's p2 equals to q2 and the limit is five something like this right and then p3 q3 and maybe eight so for two here right i mean how can we know if this p1 q1 2 will return true so it will return true if like i said if there are like some path that can connect oh sorry if there are some edges that can connect this p1 and p2 and whose uh distance right the big the distance is no bigger than two it's actually small it's strictly smaller than two right and same thing for this p2 and p uh p2 and q2 so if so we return true for this one if there are some edges that can connect the p2 and q2 right who's like um the distance is smaller than five so if you can find this if you can find if you can make these observations and now i think it's more clear that we just for each of the queries here we just need to try to find some address that whose distance is smaller than the current limits and it will try to connect we'll try to connect these two nodes together and that's the perfect a perfect candidate by using the union find and now we have i think the solutions becomes much clearer so we sort the course by the limits from smallest to the biggest so that we can build the uh the graphs uh bottom up and then we will also sort the edges the address list from the smallest distance to the biggest and for each of the queries and since we are need we need to make oh we also need to maintain that in the index for each of the queries that's why uh even though we're sorting by this one but we're still going to maintain the current the original index so that we can use the index to populate the final answer array so basically for each of the queries here from the smallest to biggest i would use this one as the parameters and we use it to find the uh the edges whose distance is smaller than this one and then we would try to union those edges and after that we basically we simply check if this p1 and the q1 is connected if it is then we know okay so we there has to be a path that can satisf satisfied this condition and then we return true otherwise we return false right and since we are like sorting this uh queries from smallest to biggest so whenever we have unions sum of the edges here we don't have to go back to do it because you know uh it does we don't really care right because we can use as many edges as we want as long as they are smaller than the current limits so that's why we can just try to union everything that's smaller than this one and then and we can just keep adding the edges and then yep then there you go so we for each of the one we just use the same logic to check and then we should get our final answer cool so i will start the implementations here i think first i'm going to try to create templates for the union find right so for those who still don't know the union fine i recommend you to look find some other videos that can give you a better explanations about the union find so here i'm only going to do the implementations so for union find we need two functions methods the first one is to find so the find is find the root right so find the root for the current group so the way i'm doing this i'm using a path compression all right so here i'm using recursive call first current one and then we do a find of the parents x right and in the end i return the uh the parents so that's that because at the beginning you know every note has it has itself as served uh as the uh as a parent and that's why whenever the parent is not the number itself and then we know okay so this parent has this card number has a different has another route that's why we just keep looking up uh while looking up we also uh compress the uh doing the path compression so that's the find and then we have a unit right so the union is this x and y and we just do a r1 equals to find x right and then r2 equals to find of y and then if r1 is not equal to does not equal to r2 and then we do that the u the unit and here i'm not using the rank the rankings here i'm just using the sorry i'm just always assigned this r1 the patterns of r1 to r to us patterns of r2 to r1 okay so that's the uh the templates of the union find and after that let's just try to sort this two list so the first one is the edge right so for the arch we want to sort by the byte by the distance which is the we need to use a lambda function right so we have a x dot x two right so that's the third element and then uh we also need to sort the course by the limits while also maintaining the index that's why i'm going to create a new list of queries and so the first one is the limits and then we have a u we have a v and then we have index and i'm going to do a like loop here for u and v and l right in enumerate of the course p-r-i-s so i'm just using uh p-r-i-s so i'm just using uh p-r-i-s so i'm just using uh like a short versions of the for loop here so i'm just i enumerate the queries including the index itself and i just create a new uh tuple word set a tuple right for each of the query itself so that i can just easily sort by the limits now i can just do a sort and i don't even need to specify the lambda functions because by default it will be sorted by the first element which is the limit that's why i put the limits at the first one all right cool so that's that and now we can just uh now we need the answer right so i mean the answer at the beginning everything is false right and the uh the length is the length of the curse oh and that's why we need another we need the m here so i'm going to use since we already have n here i'm using m is the length of the chorus right yeah so uh that's that and then we have a four uh chorus so i'm going to have like the uh the limits uh so i would also spell it out so create limit right and then we have a u we have a v and we have i right in the queue that's that and so yeah and in the end right once we have the our answers we just need to do a answer.i equals to the uh something answer.i equals to the uh something answer.i equals to the uh something right either true or false in the end and then later on in the end we simply return the answer so the way we're doing this is like i said we have to with the current q limits we'll find the uh the valid adjectives that we can use to do the unit and the way i'm defining is i'm going to introduce another like edge index of equals to zero at the beginning right and then while the edge index is smaller than the uh the size okay i need another one another length which is the i guess i'll just call it uh edge size maybe that's the length of the edge list so while this one is smaller than this and the edge list of the edge index and number two right is smaller than the q limit now since the add list has three elements and the index two is the distance we're looking for right and since the edge list is really sorted by this one that's why i can just loop through from the current index and if it is if the current one is smaller the current distance smaller than the limits i can just do the unit right so the unit is a union our union the address list of this which is zero and one right so the zero is the u and the one is the v so i just union those two and then after that i just increase the index by one since this add has already been uh union so we don't have to be we don't have to use it anymore that's why we can just keep moving the edge index forward cool so and once this while loop is finished we have uh used all the valid address we can use to try to connect the current uh queries right and then we can simply check you assign this answers with the find of u equals to find of v so what this one does is basically this is the way we're checking if this the u and v has been connected or you know in another word if the u and v belongs to the same group right so finally you find u and find v give us the same group here right and then we can just we can use the uh we can just uh return true because we know okay so we have already find a path otherwise false yep i believe that's it so let me run the code oops sorry invited syntax oh no it should be a colon not semicolon queries oh yeah q e r i e s chris okay and all right accept it okay so it's a it's successful yeah so that's it and so for the time complexity right so you know like i said so the union and the fine we're treating is like a one here so we can just ignore these two parts and so the most significant uh complexity is this two sortings which is are both unlocked and right because both the address and the queries can be uh up to n length that's why the uh and then here we have a so we have unlock n here's like just a o of n and uh but for but here you know since the uh oh even though we have a while loop here but you know we're only going to use the each edge once that's why idea so here we're only we're we can also consider like o one right and then the defined and union are also one so in total i mean it's a old log it's an unlock and solution for this yeah i guess that's it for this one i think this one is it's very interesting unified solutions and so the observation you have to be able to make is how can you come how can you con relate or how can you connect the answer for each queries with uh some union find uh algorithm and in this case uh it just happens to be uh i mean you just have to uh write it down or and then try to analyze so what does the true mean for each of the queries and so for this one it means that and with this kind of limits can we find some edges that can connect p and j together so that's the definite that's the meaning of the of true for the queries and if you after that i think it shouldn't be that too hard to find a sorting and also this wow this like index thing so you can solve this problem into a log and time compress complexity and yeah i think that's it for today i guess and thank you so much for you guys to watch my video and stay tuned see you guys soon bye | Checking Existence of Edge Length Limited Paths | strings-differ-by-one-character | An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance **strictly less than** `limitj` .
Return _a **boolean array**_ `answer`_, where_ `answer.length == queries.length` _and the_ `jth` _value of_ `answer` _is_ `true` _if there is a path for_ `queries[j]` _is_ `true`_, and_ `false` _otherwise_.
**Example 1:**
**Input:** n = 3, edgeList = \[\[0,1,2\],\[1,2,4\],\[2,0,8\],\[1,0,16\]\], queries = \[\[0,1,2\],\[0,2,5\]\]
**Output:** \[false,true\]
**Explanation:** The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.
**Example 2:**
**Input:** n = 5, edgeList = \[\[0,1,10\],\[1,2,5\],\[2,3,9\],\[3,4,13\]\], queries = \[\[0,4,14\],\[1,4,13\]\]
**Output:** \[true,false\]
**Exaplanation:** The above figure shows the given graph.
**Constraints:**
* `2 <= n <= 105`
* `1 <= edgeList.length, queries.length <= 105`
* `edgeList[i].length == 3`
* `queries[j].length == 3`
* `0 <= ui, vi, pj, qj <= n - 1`
* `ui != vi`
* `pj != qj`
* `1 <= disi, limitj <= 109`
* There may be **multiple** edges between two nodes. | BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*"). | Hash Table,String,Rolling Hash,Hash Function | Medium | 2256 |
383 | Hello everyone, welcome to D channel, in today's video we are going to solve problem number 383, whose name is Rasom Knot, which is one of the problems in lead code. This problem is also featured in the list of Challenge for new users, so it is a good one for business. If it is a good exercise then let's solve this question without any delay. Best start so what is the question? First of all we read what is written in it. Given you string note and magazine return true can be constructed by using D latest from D. Max in and fox respect vice h letter it in magazine can only be used onesome note Okay so here we will get two strings tension note and magazine whatever letters are there we have to see if the letters of the magazine note can only be used onesome note Let's understand it with an example. There is a letter A in the note and letter B in the magazine. The letter in the magazine is B. We cannot construct A by using B, hence the output falls here. Second. In the example, the letter in Rasan Note is double A and in Magazine the letter is A & B. double A and in Magazine the letter is A & B. double A and in Magazine the letter is A & B. So here because we cannot construct the use of one letter, I have used the latest of Magazine. I have written here and in Magazine there is so this condition is If we solve our problem with chali, then here we have already given the function can construct. If we have to return true or false, then in order to understand, let us create a drop variable. Construct OK From the letter, so let us understand the problem a little. Hain So Magazine I may have given us some letters and we may have given some letters in the handsome note Sam Note, using the latest of Song Magazine, Han Magazine Main has given here di to become sakya ok di to a gaya tension note ka but now we again This di cannot be used with any other character which is not a letter. We have to replace it with some other character other than the letter so that when we check it again for the second number, it does not work, so we can change it. The second letter we will give is K, then if we search for K then KV will be here, so we remove K also, the last letter is H, if it is not there then H will not be formed. Okay, if this letter is not present in it, then we will get the value of construct here. False i.e. if it is i.e. if it is i.e. if it is not there then there is no need to check it further because if one letter is not formed then the rest of the letters have no meaning because tension note cannot be formed now, it cannot be formed when the second condition is true. It will happen as long as the letters are continuously found inside this magazine string, that is, the value of our construct is true, what is found will remain true, then I will again check for the letter in the magazine that letter is present in the magazine. Otherwise, we will do a trade in the magazine and then we will message, so I am ok, so we have to check that the letter of Rasom note is the ration note. Now if this condition is true then I have to calculate the value of the construct. Is true i.e. it value of the construct. Is true i.e. it value of the construct. Is true i.e. it can be constructed, if not then here is where we have to check whether the value of the construct is not present even after checking all the latest of the magazine, it means that we can break the form. So here I will write if construct is equal then give break de loop and here I have to return construct is ok, before this do camera, I will replace the letter with some other character which is not a letter, I will replace it. After I can break the loop Run Time Fast End 72.69% 72.69% 72.69% People That's a Good Thing Like the Video and Share with Your Friends I'll See You in the Next Video Keep Learning Keep Going Keep Educating Yourself Next Time | Ransom Note | ransom-note | Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.
Each letter in `magazine` can only be used once in `ransomNote`.
**Example 1:**
**Input:** ransomNote = "a", magazine = "b"
**Output:** false
**Example 2:**
**Input:** ransomNote = "aa", magazine = "ab"
**Output:** false
**Example 3:**
**Input:** ransomNote = "aa", magazine = "aab"
**Output:** true
**Constraints:**
* `1 <= ransomNote.length, magazine.length <= 105`
* `ransomNote` and `magazine` consist of lowercase English letters. | null | Hash Table,String,Counting | Easy | 691 |
1,452 | hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screencast of the contest how did you do let me know you do hit the like button either subscribe button and here we go cute were people whose list of favorite companies it's not a subset of another list yeah so this one I think I just was trying to well one was I just want to make sure what they meant by subset I mean I know that some set has a definitive meaning but I feel like it in recent days lead code new codes definitions were an exact so I just want to make sure and it's not even just equal sometimes different problem centers will have different definitions and by dad and because subset for a list means something else and here it turns out that it means the proper subset I believe where every item is inside other item or another word maybe even dominated that you can use maybe but in either case I looked at an N is to go to a hundred their 500 company sounds like I'm the nose so right now I'm gonna start implementing the blue force but which is N squared times the number of companies L so N squared times L was always you go to the biggest lists of companies or something like that and that's pretty much what I do I did have a little bit worried with respect to the running time but uh but yeah and I also converted here I was like just double-checking some stuff I was like oh double-checking some stuff I was like oh double-checking some stuff I was like oh yeah I think at some point pretty soon I converted it from a list I was going to use sorting and a binary search or something like that but I was like okay actually just convert it to his set it's fine yeah so I can wear it to a set which allows me to do quicker lookups and then after that I just do a proof for us I just wanted to make sure that this works that I can create a set that way while I continue to type so that even look at it later now I think there was a compile it just tells me there's a compiler like because I have the type one companies because I do look at it later and I go yeah that's fine thanks and now we're like okay is not equal to j then we want to check whether the person is strictly person I see list of companies is strictly inside person J's company and I was like okay I spent I end up spending about five minutes on this farm my plight could have should have done it faster but oh yeah that's pretty much what I'm implementing you know I never looking back it seems like I'm really slow but for some reason because I think I was still very so doing this time I didn't know if I was thinking like it do I need an optimization and I think near this time I was like okay if I need an optimization I'll just do it later like I would take a risk on a five-minute penalty because sometimes it five-minute penalty because sometimes it five-minute penalty because sometimes it is what it is if it doesn't tell me stuff that if every item is found and we want to set far as you go to true and also I did a little bit of a micro optimization so I don't know why I voted this way I think I was just washing a little bit mentally instead of just waiting quick Chris that's nice entry what it does but yeah but now it's saying now if we don't find a case where someone totally likes all your companies and more we added to in a way that is the result and we just couldn't earn the I yeah that's pretty much it I when I don't know submit even though I probably could have tested the stress tested a little bit more that's cute Bowie people whose list of favorite companies is not exceptional but not less so I've like could have done this one faster but I think I just wasn't sure if a man like Bob was upset and I was it I don't I was a little bit skeptical about this one in terms of running time so basically what I did was proof for us it's n square and then for I is not yeah so for n square you for every I you compare it to a J and then see if everything in I is in J or not in J well we've there's a one case where yeah if I if all of I is in all of J then that means that I gets dominated yep otherwise if you cannot find it instant that's the case then we add to index I was I actually had a little bit I was a little bit scared about the running time but I think I miss better constrains now that no there's 500 companies right yeah so I you said to make the lookups easier but yeah although I did proof force and Q or N squared times L for Elvis to number of companies so I definitely wasn't confident about this one in terms of wedding time I was thinking about maybe I have to end at the way least can convert from string to like an inch or something like that but it worked okay so maybe the test case week but I'm not sure because I do have some early termination but it's still not yeah after actually break on here I don't know why I didn't break on here either but yeah oh boy I mean this is just proof for us | People Whose List of Favorite Companies Is Not a Subset of Another List | restaurant-growth | Given the array `favoriteCompanies` where `favoriteCompanies[i]` is the list of favorites companies for the `ith` person (**indexed from 0**).
_Return the indices of people whose list of favorite companies is not a **subset** of any other list of favorites companies_. You must return the indices in increasing order.
**Example 1:**
**Input:** favoriteCompanies = \[\[ "leetcode ", "google ", "facebook "\],\[ "google ", "microsoft "\],\[ "google ", "facebook "\],\[ "google "\],\[ "amazon "\]\]
**Output:** \[0,1,4\]
**Explanation:**
Person with index=2 has favoriteCompanies\[2\]=\[ "google ", "facebook "\] which is a subset of favoriteCompanies\[0\]=\[ "leetcode ", "google ", "facebook "\] corresponding to the person with index 0.
Person with index=3 has favoriteCompanies\[3\]=\[ "google "\] which is a subset of favoriteCompanies\[0\]=\[ "leetcode ", "google ", "facebook "\] and favoriteCompanies\[1\]=\[ "google ", "microsoft "\].
Other lists of favorite companies are not a subset of another list, therefore, the answer is \[0,1,4\].
**Example 2:**
**Input:** favoriteCompanies = \[\[ "leetcode ", "google ", "facebook "\],\[ "leetcode ", "amazon "\],\[ "facebook ", "google "\]\]
**Output:** \[0,1\]
**Explanation:** In this case favoriteCompanies\[2\]=\[ "facebook ", "google "\] is a subset of favoriteCompanies\[0\]=\[ "leetcode ", "google ", "facebook "\], therefore, the answer is \[0,1\].
**Example 3:**
**Input:** favoriteCompanies = \[\[ "leetcode "\],\[ "google "\],\[ "facebook "\],\[ "amazon "\]\]
**Output:** \[0,1,2,3\]
**Constraints:**
* `1 <= favoriteCompanies.length <= 100`
* `1 <= favoriteCompanies[i].length <= 500`
* `1 <= favoriteCompanies[i][j].length <= 20`
* All strings in `favoriteCompanies[i]` are **distinct**.
* All lists of favorite companies are **distinct**, that is, If we sort alphabetically each list then `favoriteCompanies[i] != favoriteCompanies[j].`
* All strings consist of lowercase English letters only. | null | Database | Medium | null |
174 | Hello Everyone Welcome to Difficult Channel Subscribe To A Situation Has Done Game Liquid 174 Is Hotspot Of Birth And Its Very Interesting Problem Subscribe Must Subscribe School Width Minimum Amount Power S Key Settings Operation Electronic Example Dheer Vo Grade - - - Electronic Example Dheer Vo Grade - - - Electronic Example Dheer Vo Grade - - - - - subscribe to subscribe Video subscribe to aadheen name list 174 Pomegranate for this they celebrated the birth anniversary of Mahatma Gandhi and with this notification electra n f and subscribe now school key and important pastries the power of united in itself was beyond and Video then subscribe to subscribe our 200 Just Remember This Point Which Will Help Us A Lot In Coming Up With Android App The Lips Reduce Problem To Various Modeler's Subscribe - - Now School Subscribe Our Subscribe this Video subscribe to subscribe our Meanwhile Planets K switch off minus to Subscribe My Channel Subscribe Our Robert Mix It Aur Tulsi Isbich Dil Is Particular 12345 Let's Unite And Give Thursday Subscribe Nuvve A Plus Movement In One Side Reaction And Nights To Give Way To Power At The Center Subscribe Button To See The Point Hai This Point When there is skin problem the lessons you learn light settings mist power and water servi subscribe to subscribe our 204 equal to band se minimum power eight subscribe to subscribe for - 121 for - 121 for - 121 a piya to more rhythmic 12182 in power minus plus to make attractive one and how much You need to empower women not do subscribe I hope you understand all these taste cases that you 100 gram paneer version am trying to bed DPR 1005 minimum amount of power The Video then subscribe to the Page that and have increased the time in both Amit Index And All The Three Do Subscribe Appointed Porn Vid That Androided For 20 Serving Slide 214 Using Arduino Code That Makes Sharp Difficult Subscribe My Channel Subscribe Will Win Subscribe To Member This point is well because it is difficult computed while going from Directions from one of the perspective Thursday Subscribe Apart from School College Died On Tel Half - 5 Minutes Of Power The Apart from School College Died On Tel Half - 5 Minutes Of Power The Apart from School College Died On Tel Half - 5 Minutes Of Power The Means Of Much Power Deficit Which Gives The Night At This Point And Then One Plus Subscribe To Are In A Big Question That Power Tariff In Greater Than or Equal to One 100 subscribe this video channel subscribe and subscribe that from Naav Lips Fielder Se Control and Getting from Extreme Right Volume Withdraw from Difficulties and subscribe 430 subscribe Video subscribe to subscribe our that from five minutes of power bank account se FD Enter jis pot le video sirf Video give night subscribe and subscribe the that 510 great leap years this period total power subscribe 919 subscribe and artificial night yes benefits of rights took place me knowledge compute dress power need for this particular entry and the volume - stand particular entry and the volume - stand particular entry and the volume - stand For student in five minutes of power in this particular direction so much power should give water cooler that December - 5 - that December - 5 - that December - 5 - 151 - - 05 151 - - 05 151 - - 05 200 minimum of fifteen units of power after becoming to the night and from this particular to left moving in this particular direction one Plate computers for the direction that here a place zoom the night is moving destroy i want minimum one enough power to maintain for this is the means off subscribe this moving crowd yielded at this i one minus 10 current affairs - one minus 10 current affairs - one minus 10 current affairs - 10th class 11th hai to Is this night is moving in this particular direction Hasp Our Video Must Subscribe To Is This Night Will Have Enough Power Hotspot Regular Unit Dhundh Subscribe Veer I Let Continuous Next Idiom Is a Big Salute This Political Social and Components - Five - Five - Five Salute For This Point Se Left You To Cash Withdrawal Subscribe To Yo 1992 Sub - 5 A Pick From 16th Is This Night Is Movie In This Particular Direction How Much Power Window Is One - Power Window Is One - Power Window Is One - Pickup Sex On 8 - 22nd Pickup Sex On 8 - 22nd Pickup Sex On 8 - 22nd Is 16 To Possible Options Either to give this might seem enough power and 16513 subscribe to 6 a plate central police have rich vibrations subscribe from within dubai settings for this particular sale wishes for power and suddenly coming from subscribe to this means a big salute That Will Give A Minimum Of Two Years Before Death Sentence Him Zoom Standing At This Particular Political Leaders Like Subscribe And Subscribe For More Video Subscribe - - - - Play List Vasool Decade Ke Liye Tumor Moving From A Half Cell Towards The Lower End Its - A Half Cell Towards The Lower End Its - A Half Cell Towards The Lower End Its - Android Power minimum level subscribe this Video not support to - - 4a a day or two options available here they can do in this particular direction and twenty minutes of power and banking Govind spot production and give five minutes of power which is very much liked so subscribe my channel Subscription to Speed Come in Slightly's Season's to Speed Come in Slightly's Season's to Speed Come in Slightly's Season's Final Decision Salary Flu White Point Solution Festival Ki A 247 Liquid - To Do Must Subscribe A 247 Liquid - To Do Must Subscribe A 247 Liquid - To Do Must Subscribe Tubelight and To-Do List During Tubelight and To-Do List During Tubelight and To-Do List During Five Eight Tips Field Friend Pass 1.5 Inch 1.5 Inch 1.5 Inch Subscribe to Channel - - 2 - - 2 - - 2 The President The Fear Of Going Towards Right Bank Address Political Rally Minimum Us Emphasize Power This Matter By Into Broad Gauge And Power Loom Celebs By Subscribing Nav Vihg Complete Fielding And That A Dimple The Power Volume Un Davidson Confusion Left Don't Worry Everything With Little Clear In The Solar System Points 158 Next Point To Variables Eminem For Calculating Rule And Columns Of Liberation-in-Life In Volume Subscribe Loot Festival Loot Indiscriminate Harvesting Strong Plus One In Recent subscribe and subscribe the Channel Please subscribe this hai adarwise loot lo daily requested video ki adarwise also sign board and air disorder computer from this equation and considered enough now live web school on Thursday that and within ther power minimum one minute but please this is particular in recent years of Competition is under subscribe button on Thursday | Dungeon Game | dungeon-game | The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately.
Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).
To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step.
Return _the knight's minimum initial health so that he can rescue the princess_.
**Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
**Example 1:**
**Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\]
**Output:** 7
**Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.
**Example 2:**
**Input:** dungeon = \[\[0\]\]
**Output:** 1
**Constraints:**
* `m == dungeon.length`
* `n == dungeon[i].length`
* `1 <= m, n <= 200`
* `-1000 <= dungeon[i][j] <= 1000` | null | Array,Dynamic Programming,Matrix | Hard | 62,64,741,2354 |
7 | hi everyone once again welcome to my channel and today again we are solving another problem from lit code top interview question list and the problem is reverse integer so i always recommend everyone to solve the top interview question list first if you are preparing for interviews so that list has almost around 146 problems and i have published around 90 problem video solution and created a dedicated playlist for that you can check out and try to solve as many as possible because these all problem will cover all the data structures basic concept and idea once you have know the basic concept and able to solve these problems then you can solve any problem by practice and practice so the let's focus on this problem so in this problem we are given a 32-bit integer we are given a 32-bit integer we are given a 32-bit integer x and we need to return its digits reverse so we need to reverse its digits if reversing s causes the value to go outside the sine 32 bit integer range like this is the range of sine 32 bit minus 2 power 31 to 2 power 31 minus 1 then we need to return in case of over or under flow and assume that the environ does not allow you to store 62 4-bit integer sign allow you to store 62 4-bit integer sign allow you to store 62 4-bit integer sign or unsigned so this is very important constraint because of this constraint this problem is little tricky though this problem is marked as a easy inlet code while i can say it's not that easy if with this constraint so how to solve this kind of problem so let's see the example here it is given x is 1 2 3 and we need to reverse is 3 to 1 so how to solve this problem so this problem can be reversed like integer can also be reversed in same way as that the string we do reverse while we need to find out the like significant disease so for this example in 1 2 3 so first we need to reverse it so for reversing we need to know what is the last digit in this so how to find the last digit of a number so for finding the last most digit of a number we do modulo y 10 so once we do modulo by 10 we will get 3 as the last digits from this 3 so the we will also initialize our reverse integer that is from 0 and once we get the digit the last digit what we will do we will take reverse multiplied by 10 plus the digit we got from the modulo so this is 3 so this reverse now it become 3 now once we got this digit does it matter in other further cases no so we need to just forget out so for that what we need to do we need to basically trim this last mode this is as we already use in our river so for removing the last mode digit what we do we will take 1 2 3 and divide it by 10 and this division we will do integral division so in python you need to use the double slice that will gives you integral so once we do this we will get over here 12 so once we got so now our reverse is 3 at this stage and number is left 12 so we will apply the same steps again in 12 so this will become 3 into 10 plus 2 so 2 we get from by modding 12 mod 10 we will get the 2. so this is what this number reverse will become over here 32 and after dividing 12 by 10 this will become 1 then we will again repeat the same step and finally we will get 3 2 1 as the reverse which is answer over here so this is how we can solve and reverse the number but we need to take care the special cases the special case when we are reversing and our integer crossing the into max so i have written down over here these values of 2 power 31 and 2 power 31 minus 1. so the min value and the max value of integer so for example let's say we got let's take this first positive side part if we got a number something like 7 4 6 3 and then 8 4 7 4 1 2 so this kind of number if we got so if we try to reverse it this reverse will work too that is fine then 1 then 4 then 7 then 4 then 8 then 3 then 6 then 4 but at this point if we take this so far it is fine as this number is ah in the range is still in the range so we can return the reverse easy but what if this number something else like more than 7 if it is 8 let's say let me change the pan here so if it is 8 then if we try to put over here 8 that is this whole number y including 8 is greater than or equals to the river integer max so into max it greater than equals to into max that is the case which this is getting overflow so how to find this kind of number so before that like when we are taking this like multiplying so as so far till this place so let me change again panning here so till this place we are okay this is our reverse so far now when we are adding another digit so this is the another digit so when we are adding another disease first we are multiplying by 10 so with this 10 we need to check if it is not crossing if it is crossing by multiplying 10 that means it is overflow so we will check if our reverse is greater than into max so let me just write as max value by 10 if it is that means it is overflow case so we will straightforward return 0 another case reverse can be equals to this max y 10 in that case we also need to check the digit we got by the 10 modulo if it is greater than max mod 10 the last digit in our max value so mod time if it is greater than it is also a case of overflow we will return 0 here same we will apply for the negative part so negative part what we will do if reverse is greater than the ah if reverse is greater than min by 10 that is fine we will return 0 and if reverse is great if reverse is equals to mean by 10 then we need to compare digit if digit is greater than the min y mean modulo 10 if it is the case then again it is a under flow case so we will return over 0 in this case so this is the or condition so this is the idea you can try to pause the video and try to implement the code by yourself first if you can able to because every step i already covered so here the coding part you can see so basically yeah in ah maximum like into minimum value we need to compare left i think my bad i x compared with the greater than instead of greater it will be less than as we are getting sign so this is the case so here this is the code so we declared first reverse variable then we are iterating until our x is not zero then we first got the digit the last modes digit in x by taking modulo with 10 and then remove trim that digit by dividing by 10 once we got the digit we will check if current reverse is greater than into like max y 10 or if equal and the digit is greater than modulo value 10 then we will return straight forward 0 this is the crossing the into max and this is the left side of the into minimum otherwise we will update our reverse y with the current digit like previous value into 10 plus the current digit once we done at the end we will return the reverse is the reverse of x so let's try to compile i have already written few test cases let me create the negative test case boundary as well so let mark it as 9 and it is negative so let us run first this code at this code already i tested so it will work definitely so there is a is not a valid type of integer so yeah i am giving the wrong integer as it this is not possible so instead of this i should give the reverse of let me make it 1 over here and take something 7 here i guess so let's see if it work otherwise we will remove the test case ah yeah that's like is not valid integer it is already overflowing as we can only pass the 32 bit 30 integer values for x so let's try to compile again the negative part is also crossing so let us remove this extra test cases better to do with the default test cases first and you can see it's getting compiled for all the test cases let's try to submit the code and this got accepted let me show you the submission so it got accepted with the 100 percent acceptance rate so that's it so the time complexity of this solution as you can see say the number of digit in x that is for example it is constant actually so the maximum there can be a 10 digit in 32 bit uh signed number so the time complexity of the solution of one and space complexity is also over one so if you like this solution hit the like button and subscribe to my channel and also try to do solve other problem from top interview question list that is very important when you if you are preparing for your upcoming interviews thanks for watching | Reverse Integer | reverse-integer | Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1` | null | Math | Medium | 8,190,2238 |
349 | Soon A Ho to A Ho to A Ho to Ajay, you all are doing great, my name is Yatha Batra and today we will clear the simple question and the name of this question is Intersection of Two Years so as you can see on my screen. Yes, this is a recent question of 359 intersection of toe that if this question is latest then it is ok, I will follow it by asking a simple question which is called And Not Done, I could have used order from you here also but in other hotels, so use it. I am doing this because according to Kareena, door or frustration does not become explosive, I get the reference from a little inverter, it is my own mood, so you can do it for anyone, make me also in the mood that I am an undertaker, thank you all subscribe, I do it like this. We will have to make a map by one Saxena, we will have to make a map on our right, we will have to make an unmute map, so here you can see that I am famous, this is the dress and input, when you ask this question, the plate will not be taken for coffee, it will be mixed. And by inputting this hair fall, all these less auction of clans game are in that person's burial, so first of all, we will need you, the most important is that we will have to make each and every point and one, we will have to make a castle, okay so First of all and always make and award that illegal chilli spelling is a little, here you have to give in unwanted that you statement plate, then you will definitely have to give its data is mixed and that you give the date of it otherwise arrow will come okay. So the proof, I keep its name, I keep the hash, you can keep anything, working in 10 bracelets from, create a person from which I have countless sitting in this function, so in this function, the return we give you is tight, it is better. So therefore die and food will have to make a doctor ignorance is time n template so here you have to give in and I fry it output we are getting sugar cleared that we have so far we just created a map and sequence app And we have given it to you, now the logic has come to the fore, it is known that the first number one is cashew nuts, so whatever you say to him, we will put all your performance in our opinion and along with it, we will also put his work so that we Whenever we dross the setting Reddy, then Agneepath comment of making electronic is not zero then when should I print it, if neither is zero then let's get it done ok then next fast approaching then I said today we will see then Prabhat Singh two hosts first think this tractor hermitage Can use ringtone a wick in the arid zone use officer okay swar me tangari to sort we can also take a simple step loop control usually gives our one some more specific functions usually here democracy will be a little point and We don't even have prostate people in this class, so I will put the clip on the maximum. Agreed, there the modes and lums are this. This person's name is Akshay's. Like, if I press it at home, there is a service and function in it which is Most of that we are the provider with you so this is what we did now all this is good if I explained it to you in the video don't think this is straight appointed we are the loved one and here we are taking care of our fine and now let us increment it means genuine Treatment Ghrit Incremented that the understanding is that if there is no element in the map, then first of all we come up with one and because what happens in the gap in tomato is that if we do not have the element printed then it is decided and with it the person who When her dowry comes, then you can see that if any element is going out first, then in the meeting held to investigate it, that feeling has been done in these comments, now the work will go after that, so in the episode, we will talk about our meaning in our hair function. It is important that in it we can store the current of elements in our cities, how many times this element has appeared in this array, later we will see its time complexity proof, because we are a Shaktiman, we are very powerful, so name school options and Here the help face of I Plus is clear that we are the setting and network families. If this laziness of ours is there, then hello, I am here, okay, equal means elastic qualities are due, then it should be a gimmick, there is that we are asked. I should do something about this enrollment, now the doctor has told you that it has a function, till the ask, it works like a daughter inside and if there is a fog in the food hotspot of the patient, then we can see it like this, its name is now hello very good, here we have given you a better As I have discussed earlier also that Jaisalmer gets the element and we will make it command zero, Fakir should not be printed again and then it does not come in our output tractor, so here we can say this and in this Through online ad and we click values equal to Shiva, click values equal to Shiva, click values equal to Shiva, okay friend, I would like you to ask the element in person, whose law is not this, initially like he asked an element, his 5th and took water, our own increase in production. I must have removed it and now we will return it Fennel that everything should run fine 34 and I have not made any mistake so let's see so first let's run this cord so here we have named it line 0 Almost this was the top, man, okay, you will quote the run of it, the anniversary updates are 198, its for millisecond, let's submit it, so it is like I have to submit the calories but the expenditure, so then it got submitted and I am sure that you have got its implementation right. Implementation is done, I have understood that how we can do it, there are many methods on this, you can do it 2.4 Myth TV, in that first of all you can do it 2.4 Myth TV, in that first of all you can do it 2.4 Myth TV, in that first of all you will have to do shopping, then why do you have to use pointer method, you can use it from side also in that You will have to make two sets, you have to get only the unique elements printed here, okay, or you can do it with smell, I have taken the specific one only, now you can do it with water also, Yudhishthir, is it clear to you? Om, this is something good. Swapn abhi problem meet me coffee with you like this video if you have learned something from this then please support me work bangla film video and sharing and subscribe my channel vikas in such problems shampoo hair for weeks that you have to alarm quality interview for relation Role of or you are interested in data structure of its problems or you want to spend money in quantity programming time 10 subscribe my channel that a little while videos and updates thank you so much that | Intersection of Two Arrays | intersection-of-two-arrays | Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000` | null | Array,Hash Table,Two Pointers,Binary Search,Sorting | Easy | 350,1149,1392,2190,2282 |
537 | hey how are you doing guys it's hilah bella here i recording stuff on youtube chat description for all my information i do all liquor problems uh make sure you subscribe to the channel give me a big thumbs up to support it and this is called complex number multiplication um given two strings representing two complex numbers uh you need to return a string representing their multiplication note the base i raised to the power of 2 is equal to -1 equal to -1 equal to -1 according to the definition let's look at this example we can see that there are two real numbers and uh the imaginary unit which is uh the imaginary number uh is the solution to a quadratic equation right so we return this output you can see these steps right here you convert it to the form of 0 plus 2 i here uh it's the same the input strings will not have extra playing uh the input strings will be given in the form of a plus bi where the integer a and b will both belong to the range of minus 100 and the output should be also in this form well um there is a formula um a plus b i multiplied by uh c plus d i is equal to ac minus uh b d uh multiply not multiply plus uh a d plus uh b c and multiplied by i yeah um let's say we got a b c d indices 0 1 2 and 3. uh go ahead all you need is a an array of the type integer then we create a stream of uh their concatenation this both these two strings a plus b ah dot split uh at you know two backslashes and we say uh plus or i you could notice from the description this problem right here right then um after that you should call map to integer in order to get uh this value in initial representation uh you use this method reference integer parse integer and you say to array together to put that to add those uh parts to that array yeah um finally you return array at zero which is a right you need to look at this part right here ac minus bd plus ad plus bc uh multiplied by i at you know we can see well we'll look at a which is at zero so array at zero multiply by array at c which is two minus array at b which is 1 multiplied by array uh b d which is three right and plus um you could also notice that from the description of this problem right uh the first real number then the plus then the second real number and i that what we are doing here plus uh the second real number which is uh array at zero uh multiply by d which is array at three uh plus array at one multiply by array air c which is true and you need to add i at the end yeah and we can run this code yeah seems good let's run this code accept it let's submit there we go success um yeah thank you guys for watching leave your comments below i want to know what you think follow me on social medias follow me on instagram add me on snapchat uh give me big thumbs up to support my channel uh as i said before uh leave your comments below if you need some help right any help you need just leave your comments below or just contact me directly and uh i'll see you next time thank you bye | Complex Number Multiplication | complex-number-multiplication | A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where:
* `real` is the real part and is an integer in the range `[-100, 100]`.
* `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`.
* `i2 == -1`.
Given two complex numbers `num1` and `num2` as strings, return _a string of the complex number that represents their multiplications_.
**Example 1:**
**Input:** num1 = "1+1i ", num2 = "1+1i "
**Output:** "0+2i "
**Explanation:** (1 + i) \* (1 + i) = 1 + i2 + 2 \* i = 2i, and you need convert it to the form of 0+2i.
**Example 2:**
**Input:** num1 = "1+-1i ", num2 = "1+-1i "
**Output:** "0+-2i "
**Explanation:** (1 - i) \* (1 - i) = 1 + i2 - 2 \* i = -2i, and you need convert it to the form of 0+-2i.
**Constraints:**
* `num1` and `num2` are valid complex numbers. | null | Math,String,Simulation | Medium | null |
1,496 | hello hi guys good morning welcome back to a new video in this video Problem path Crossing and the special part in this video is how to optimize the complexity without changing anything but only changing the data structure we will see this kind of problem uh it has been asked by Amazon in the last one two years and it just says that uh we have a string path which says that I my path of he can be north south east west and each like each of this character represent moving one unit in that specific Direction nor south east or west now I start from the origin itself I just have to let know that I have to return true if the path crosses itself which means I come onto an existing point from where I have traveled as in if you take this example north east south so one unit North 1 unit East one unit South but you see I did not cross any paths so my ANS obvious B any points my answer is false here you will see I'm seeing Northeast South West with this West thing I reached to a point which I had already see or already traveled because I traveled I started from 0 comma 0 then I went to 0a 1 then I went to 1A 1 then I went to 1 comma 0 then from this 1 comma 0 I came to 0a 0 back which was already VIs Point does I'll say that in this itself I have seen a point which was already there so I return a true so it's as simple as that uh what you can do is you know that you have these two as a coordinates X comma y if you encounter a character as n what you will do is you will increase your y by one if you encounter if you are X comma y if you encountered n it will increase to X comma y + 1 which you can increase to X comma y + 1 which you can increase to X comma y + 1 which you can also see now if you have X comma y if you encountered a East then what you saw that simply your X will increase so it will be x + 1 comma y if you had X comma will be x + 1 comma y if you had X comma will be x + 1 comma y if you had X comma y if you encountered a South what you saw that your y will decrease so XA y - saw that your y will decrease so XA y - saw that your y will decrease so XA y - 1 if you had X comma Y and you encountered a vest what you saw your x value got decreased so it is X -1a Y so value got decreased so it is X -1a Y so value got decreased so it is X -1a Y so it is just that in these directions I have to keep on moving my coordinates and as soon as I repeat any of these basically as soon as I repeat any of the coordinates already and now when I say repeat I mean if I have already visited that now visited okay how will you maintain the visited you can keep anything a map a unordered map for sure you also know that map's complexity is in login while unordered map complexity is just n so you will try to take unordered map right all or you can also take a set also unordered map or unordered set so with this you can easily solve this now with this case as you can see that you have to take these two coordinates simultaneously so you have to take the pair of X comma y to see okay if this pair is already in my set or not so if the key is not a proper thing as in if the key is actually a pair right so you will have to write your own hash for that if you want to use an unordered map so one way is if you have because see if you had a simple and integer then you can easily write an unordered set for it if you had an integer you could have easily written an unordered set if you had a string you could have written the uned set if you had a float double anything if you had you would have written the uned set for it but you cannot write unordered set for a pair of int comma int you cannot write this kind of complex input in your unordered set if you want right you will have to Define your own hash for it which is kind of hard because it can have collisions and stuff so rather what we can do is we can convert this particular pairer to a string or to maybe one integer this one integer is again converting being like again converted to one integer is complex so what we will do is we'll convert this pair of in comma in to one string now how to do that as simple as that we know that pair of int comma int is actually nothing but X comma y that is what we wanted to store in our hash set right just convert and say okay convert this integer X to a string X add any delimeter add any and I say when I say any you can add any delimeter you can add your name also as a delimer here let's say for example I add a comma as a delimer and then I'll add a string as a y so this will become x comma y ultimately will become a string which will for sure be just mapping this which means I'll just convert this x comma y integer as a pair of integers to a string X comma Y and then I will use this in my hash unordered set un now I'll write unordered set of this particular string and then I'll keep the track of this particular unordered set and see if any element I encounter repeats any element repeats then for sure I return a true so let's quickly code this up it's going to be pretty simple again firstly I'll show you that how we'll do it by simple pair and then we'll just transform that simple pair to our actual answer by optimizing it so as we know that we are using pair so we will have to use a set so here I use a set because I am using a pair and I initially starting from a z comma 0 so I'll just insert 0a 0 in my set itself now when this portion is done I know I have to DET all the characters of my path right all the of my path now if the path as we saw if the path is an N then my only y coordinate will increase nothing but like exactly same as what we saw here if it is this only Y coordinates else if my C is south then my y coordinate will decrease else if uh if my C Is East then my x coordinate will increase else if it is west my x coordinate will decrease now with this my X and Y coordinates are decreasing and increasing now I'll just check if that XY pair which is the new XY y pair if that XY pair I have found again which means it is um like not like if it is not equal to s.n which means I have found this so s.n which means I have found this so s.n which means I have found this so sorry bro uh you can easily return a true here itself because you have found it okay that's great um and if not then uh simply you can just insert that pair in your set because it will help you uh later on in future ultimately if anyhow you cannot able to return of false here itself so you will see it will run but you will see the time complexity for this is going to be n log and space is for sure o ofn because you are using a set but the time complexity is going to be o of analog in now to optimize this what we will do is we will rather use an unordered set now here instead of pair we will use a strain again we did not optimize any logic we just optim we just modifying the data structure used so we'll just do s do insert now here to S do insert um what I can do is I can just insert a 0 comma 0 like this now if it is I'll just simply increase my these values now I'll just check uh like I'll just say uh string um cord now I just say that I converted that string to a Cod so I'll just say two string uh two string to a value u x plus I just add a comma and then plus I'll just say two string value y now I converted this coordinate to a cord I just check now this coordinate if that coordinate is in simply do this and if not then simply insert it else now with this you'll see that your time complexity has decreased to O of n rather o of n log by just simple transforming your input to a string input so yeah that's how you can solve this goodbye bye-bye | Path Crossing | lucky-numbers-in-a-matrix | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. | Array,Matrix | Easy | null |
1,232 | hey guys persistent programmer here and today we're gonna do another week cool question check if it is a straight line okay so let's look at this problem statement and understand what the question is asking you are given an array coordinates with coordinate I equals XY where X Y represents a coordinate of a point check if these points make a straight line in the XY plane so what the question is basically saying is that we're giving a coordinates 2d matrix and in this matrix the first position is the x coordinate and the second position is the y coordinate so if I were to draw this out in a graph so you see the one two so that means that the x coordinate here this is the x so the x coordinate here is 1 and the y coordinate is 2 so that's what the question means and what they're asking us to find is if this grabs out a straight line then we need to return true so our output should be boolean so boolean true otherwise if it doesn't make a straight line then we need to return false ok let's look at some strategies we can use to solve this problem great so we need to make two observations to solve this problem so the first observation is if I'm given two points the line between those two points is always going to be straight so if I'm gonna given two points so if I only have these two and that's my input I can simply say that I need to return true because if we draw a line between any two points there it's always going to be a straight line okay and the second thing we need to observe is our slope so let's do a review of what our slope means and how that relates to this problem so the slope is rise over run so what this means is our y2 minus y1 so this is said this is y1 and then this is X 2 and this is y 2 so we need to take the difference of y2 and y1 and we'll take the difference of X 2 and X 1 all right so what does this get that give us so 3 minus 2 is 1 and 2 minus 1 is 1 so our slope is 1/4 for this these two points slope is 1/4 for this these two points slope is 1/4 for this these two points these first two points right so my slope is 1 here now what do i what do I need to ensure to find that my slope at each point is also going to be the same so if our slope is the same that means the growth of this line is the same which means it is a straight line and we can apply this concept to figure out whether it's a straight line or not so let me give an example of how we can compare this to another point and find out if the slope is the same or not so let's say we have our initial X&Y here x1 and say we have our initial X&Y here x1 and say we have our initial X&Y here x1 and y1 right and we're comparing it to the last point so 6 & 7 here right so we can last point so 6 & 7 here right so we can last point so 6 & 7 here right so we can say that this is the new Y then call this a new Y and this can be new X so we'll do 7 minus 2 which is 5 and we'll choose 6 minus 1 which is also 5 and this 5 over 5 is 1 so again you can see that our initial slope is equal to our slope at any other point in this grid so that's what tala tells us that yes this line is straight because the rate of growth is the same now let's take a case where this slope is not the same so let's say I had a point here so 7 right so instead of six seven let's say I had seven here right so the new X is 7 and my new y is 7 now we do 7 minus 2 which is 5 and then 7 minus 1 which is 6 so this is not equal to our initial slope which is 1 right so in this case the answer would be false so if you understand these two concepts and how to apply them then the code is pretty straightforward ok so to review the solution the time for this would be all offenses we're iterating over the coordinate and the space sorry the space is actually off 1 we're not creating any auxiliary space we're just doing in place operations here so the spaces of 1 yeah and 2 the first thing we need to do to solve this problem is to get the initial scope with slope which we did so that's a 1 and we need to compare if the next slopes are equal to our first slope and if that's the case then we just return true otherwise we return false ok so if this makes sense let's look at the code and I will provide two different solutions that I wrote to solve this problem great so I'm back in the code and I will start off with the solution I wrote first before making this a shorter solution so the run times aren't the same it's just a matter of organization so the first thing I did is grab my first x and y and then the second x and y from the second row in our coordinate so that's why this is a 1 here and then I'm just getting the rise on the run so this is the Delta Y and the Delta X and I wrote a function to get the slope so let's say in its slope gets us our initial slope and then the next thing I'm doing is getting the new X&Y coordinates and I'm just comparing X&Y coordinates and I'm just comparing X&Y coordinates and I'm just comparing if those new coordinates are equal to my initial slope or not so I'm getting the new slow by plugging in the new coordinates and what I'm doing is I'm just returning false if the initial scope slope is not equal to the new slope so that's what is going on here and if everything else passes then just return true and then this is my get slope function and the reason I did this if statement is because I noticed that if you divide by zero you get a runtime error because you can't divide by zero so that's why if the run is zero right so you need to handle that case so this is sort of exception handling okay so this is the second solution that I wrote after looking at some of the other solutions only code and what I realized is instead of dividing the Delta Y and Delta X what we can just do is cross multiply so if this is our slope function what we can do is just multiply our Delta Y with our new X so just using that we can avoid dealing with the exceptions when our denominator is zero in this case and so that's a much shorter solution and that's the second solution that I wrote for this problem so all the other parts are the same so this statement is just comparing again it's the same idea if our slopes are the same or not because to check it's the same thing as checking this as doing the cross multiplication and checking whether they're equal or not so that's the only difference in this solution I hope you enjoyed this video if you like my videos please subscribe to my channel alright happy coding guys | Check If It Is a Straight Line | sum-of-mutated-array-closest-to-target | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coordinates = \[\[1,1\],\[2,2\],\[3,4\],\[4,5\],\[5,6\],\[7,7\]\]
**Output:** false
**Constraints:**
* `2 <= coordinates.length <= 1000`
* `coordinates[i].length == 2`
* `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4`
* `coordinates` contains no duplicate point. | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. | Array,Binary Search,Sorting | Medium | null |
82 | Hello Everyone, today we are going to discuss whose Pran Math problem is Remove Duplicates Transport Play List. There are two problems with this problem that we have been shortlisted and hence we are removing whatever duplicate number is there on it. Like here it is 12345 You can see it here See this and two more times Had to fix It has president similar for breast So what do I have to remove both of them Ok 12512 Udayveer and sewerage connection is fixed And time Talking about Congress, what we have to do is only to admit and space, we do not have to use any express in this proposal, in the arm hole, we have to do this problem, let's see the crunch of MP3 problem, how to do it, okay here. But first of all, what do we do, let's create 19, okay, it corrects zero oil, we add vitamin and stomach to it, okay, we tell him to come quickly, okay, and one more point, okay, this We take a clear bath and this is my love okay this we add to this his name indicates the accused now what do we do ghee now goes to school here we will see this subscribe us this is the first one in your Subscribe the hair and if it is both and the feathers which are not subscribed to both, if it is equal then we have to cook it till both of them are unique. Okay and as these will be recorded, we will bring our previous one and test it. Let's explain it a little more. We need to be arrogant and mysterious. Okay, what did we say, but the game and Let's Play List is 2. Okay, if these two are four, let's see who is there and who is not, then what will we do? Now we will give one more point to, now it will be mine and these two, then we have seen the trees and traffic and what else is equal, so we will click but we will take the bigger one, then we will mix the gas with the cricket and we will mix the same request, okay Now it's mine, we will check it again, we need 6 and it is a tight Mexico, is it okay, let's take a bath, don't touch the previous ones, just by increasing the dough, people have claimed that they should look at it again or it is helpful for hair and this trick for their eyes. If it is not there then what will we do to the previous? Those who are not there will like and comment on it. Where is it? We will see that this is not in the hit list. Okay, so what will we do now? We will qualify the previous and oil. Here once again I give here again that hair and devil are equal, so we will take it till it becomes who, so we have taken it forward, we have taken it on this, now here I one of this one and this one is not equal in terms of vision so what we will do is take it one step further i.e. take it one step further i.e. take it one step further i.e. how do you do reverse up and dynasty has come to this okay coming to this okay so just now we saw here Now who is not there, then what will we do, if you had this pizza bread previous now, then what will we do, free mode, start Bluetooth, scold them till this period, what will we do with the point or shadow also, one strip of iodine, it is okay now. After that, what will we get next, we will get the tap, it is help channel, okay, so it was here, then check that this liquid is not their channel, okay, then we will check this half more, hair and hair tablet, what is this, check in before this movie. If it is not in the hit list to do, then if there is a request, it will be done there, okay, so now let's see how mine is, Jio is there, want is there, and only yours is okay and we were in written, what will we do without Twitter. If there is chilli then Dominica has tested it, we will press this point which will turn it all yours will go to the moon from here. Okay, so come on, if you have the problem of having an accident, then either you have to limit it towards the deposit and move it back. Inch is that little just because see so here there is an organization called attack deleted which is a judgment player to appointed update to Harold okay so here what we make kidney note made okay as I said Redmi Note 3 What is the pass 120 and head is attached with this, what will happen with this, our land and stomach gets filled and the product has created a share i.e. stomach gets filled and the product has created a share i.e. stomach gets filled and the product has created a share i.e. inch pot chamber of such, then he said this and we point, the name is serious which we A which indicates leadership to DAV, it was necessary but this is also clear to me, okay and here I saw health, keep running it till you remove it, now here we are seeing cricket next dot is not installed on the back. There should be and if this is the bell icon thing is needed and the help chart if it has both of these then give us an increase then okay from there the alarm tomorrow until it happens at all so we are seeing if this thing which So, let's increase this video, there will be such a result that there will be no pimples at all, by doing the same, you can do this chart, not with the condition of which department, is it okay, as if I have gone here, I felt that now I am worried, okay? How long can we equal till this point, till the time Amit got both of these, it was lost to me, hence the last condition will stop and here the computer period played equal to test i.e. Safari was my played equal to test i.e. Safari was my played equal to test i.e. Safari was my point, if now we will connect it. With and then we have this closed loop condition of moving our forward now we increased the game here last updated and these two murders are equal while on will remain on then will remain closed till the fog if you quantum enlarge the game then this side is created okay you This check itself has become modern on youth, then it will go to the quarter with free apps, which is now the first previous till the get quantum science chapter, this hour will be free spread, it is okay and this you will come to this okay, so the salary is that when Ours will be equal, okay Jamshed and the website has taken such a turn, so cook them till the time called for and then remove the pin point and mix it, if it does not happen at all in this piece as we will see here. Okay, if this is the end, I am Golu and this is our I call you, then what do we have to do, we have to move the previous quantum worship and the hairs also, okay, time's clear all, today I am delisting you remember. Because I was appointed as a teacher in Delhi, I was representing and you don't remember that you have to recharge the destination. It's a wonder, any doubt has been cleared, we have returned. Please share this side, you will get likes in the comment section, you will see. | 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 |
1,494 | hey everybody this is Larry this is when I'm going to prompt I sell for the PI weekly contest 29 I'm gonna put the explanation in the beginning and then I'm gonna do the live coding of it afterwards let me know what you think about this format I'm still playing with it and here we hey everybody so for this problem I actually ended up be recording it because initially I thought that the greedy solution worked and that's what I did turn the contest I turns out that greeted does not work and there was a case that I'll show later on yeah so well that's kind of a weird constraint I think for this problem because and is you get a 15 so it borderlines does not one fast enough but a Python you have to make a the number of optimizations to get it to work in Python instead and if you watch the contest video I actually go into this incorrectly but and there are a lot of people in which we read the solutions especially in Python they did that they did it with greedy and I'll show the case where their bricks in a bit but basically the idea here is what a correct solution is to use dynamic programming and what can't dynamic programming a sort of a brute-force programming a sort of a brute-force programming a sort of a brute-force bitmask bit said dynamic programming what's a bit said right so bit set is that say you have a number between 1 to n oh yeah and n elements right and you took them I labeled 1 to N and then now for each subset you can just say for example 1 2 5 6 7 maybe just then to represent this numbers of binary well it's the first number in the set yes there's a second I'm on the side yes it's a third I'm gonna set no yes for no for five years for six and semi so this is the binary representation of the set and then now then their explanation on how to solve this is okay well first you start with every number so let's say n is equal to seven again so now you have so now you start with disparate set it can contains every number from one to seven right and now you try let's just say for example this is case you got to wait so then now we start by trying okay this the F of n where or F of the spit mask how many what is the minimum number of semesters that it takes to take all these courses well it is just equal to the minimum number of taking the first two classes one and two plus one right if so this is taking classes one and two if possible in the first semester right and or you can also take maybe one n classes one end to it right no copy and paste no Polizzi and maybe one and four right but again this is only where as possible so this is how we do the big mask one and you do that recursively by saying okay well let's say grab this one and this one is good right let's say we're here and well what is the one is the min of this minimum min semester for this well it's just you go to all of well for K is you go to let you say you know the first two class plus one right which is taking classes two and three if possible in this current semester right and again we thought that dotted and that's how you do the recursion all the way back down to zero is your base case meaning and this is always zero seven zeros no crisis yay and that is just equal to 0 right so f of 0 as you see because when you have normal class of stuff you don't have to take a semester so that's kind of the recurrence but of course that is easier said than done because a lot of the hard time especially with this particular problem was figuring out how to do this effectively and there are a bit of bitmask solutions I have to code here basically what I did was that I have a prerequisite we label this a little bit and it's a pretty tricky actually which is why I found I didn't do it this way during the contest but basically the idea is that okay for each possible subset and I use this is a really hard notation to understand in a sense that like it's not a common thing but it basically it gets a subset of a subset so it allows you to do it 3 to the end times and then for each of these so this is a candidate for four okay that lets know for J it's a bit mask so for example in this case I just go so let's say in the stuff in the beginning right let's just take this one right so let's say we're here i as you go to this thing this is you go to I and J is just okay j-just rise every J is just okay j-just rise every J is just okay j-just rise every possibility that's a subset of T's meaning that no try you know try J goes to you know although one and it tries to do oh one I'm 0 J is equal to Rho 1 0 1 and so forth dot that die and it tries these and then it just checks a couple of things the first one is that well the number of digits that you're trying has to be less than K because that's the number of classes we're taking J is the a bit mask of all the classes we're taking right in this case is 5 so no good this is for no good so far away and now let's say we go to you know some ends on which to there is mask of K is less than two so this time okay it's good but you know you won't can only take classes that does have prerequisites so what I did is okay so I look at for this bit if we wanted to take this class this is what K is we want to take the cave class has a prerequisite yeah so if this is kind of hard that's why I'm struggling a little bit to explain because it also took me a while but if this prerequisite of this class which is a bit mask so here we set up for we set up a bit mask for each K the prerequisite of that class so that means that for example for the probably if for a prereq of GUI yes big it's off by one a little bit depending how you want to count it index let's say put this one it is three and if this three is you go to you know that's let's say it could be any number of things but let's say it requires the first two class well the first two class is good so you're doing and bit on it and they and end up an N bit of it should be zero away but if for whatever reason that's a you have any other cousin in between if the current I has these classes that means we haven't taken those classes yet and if that intersection is greater than one or if the intersection is not zero then you cannot take the I've caused and because you can't take the ID class we just set this as a not real candidate and that's basically the dynamic programming recurrence and then here is just okay if again if the count is less than teed I named it t because I used two K here but if we can take less than T number of classes the semester and all the prerequisites are met we just do the min which is this I mind this xrj just removes the J from the eye and then you do that plus 1 which is the recurrence that we talked about earlier again this is really hard really tricky to get bright and a couple of optimizations here and the counting you could do with some index and in Python you have to make an additional optimization in which instead of doing it this way you pre choose the K so that you only count the case that are possible I don't want to get into it that much but know that is kind of tricky to get right alex has a good solution on that will be select to that and yeah that's what I have for the solution if you're wondering why the greedy doesn't work let me show up show a graph so this is what I drew ah this doesn't work because for a graph like this if you look at the first if you just do greedy then if you do greedy but maybe just do regular greedy by in degree there are a lot of ways that this could be wrong because and death as well because they have the same thing but let's say UK is you go to two way if K is you go to your first two nodes may be here right these two nodes and then your second and your first semester you take those two notes your second semester you take this node and then your third semester you take this node and then the fourth semester you take this node right so that's four but if you do it smartly for example you do first semester you do these two nodes and then the second semester you take I can't do it quite usually but for a second semester you took you take this node and then the third semester you take this node you're you only need to do in three nodes or three semesters let me cover it in so that it's a little bit clearer so these two are the same the yellow ones are the same semester way so in that case open depth and otherwise this is the wrong solution so yeah so that's why query doesn't work and when I did turn the contest to be honest so some of my commentary maybe in Quebec on that but you know you'd learn and you keep growing and that's what I'm trying to do I think the annoying part is knowing that I did it why I had to my idea but I just didn't think that the optimizations would help that much I guess the test cases were very borderline on tasks on timing I think if they said until you go to like 12 or something like this we would make it a lot easier just not even that much easier there compliment ation would have been exactly the same but the whining time complexity would have been much slightly easier to optimize but also you just won't run into all these time limit addition because you could prove with math that these optimizations would make it fit really easily where we're in this case you need to be in C++ or Java or case you need to be in C++ or Java or case you need to be in C++ or Java or something like that to make it fast enough in Python you need another optimization which is kind of is that my I implemented in a couple of ways maybe you could do it in Python if you do a lot of other optimizations but oh yeah but that's what I have with this explanation with this problem let me know what you think I'm going to do the life you know recording of this afterwards but keep the mindless explanation anyway mm-hmm no cost to explanation anyway mm-hmm no cost to explanation anyway mm-hmm no cost to parallel cause to queue for so yeah what is this to say about this one so this one when I first read this I was like okay I think I understand the problem and yeah and I scroll down I was like okay I when I fixed saw this I didn't know I mean I didn't know how to solve it per se I was like okay this makes sense this is just standard you can only take up two K classes a semester okay then when I saw n is equal to 15 frankly I was fooled so well point farm said I thought n is good 15 I thought that I could do proof force so it turns out that there's roughly speaking a tree to the end roof was sorry that well proof works with dynamic programming it masks and there's a three to the end solution or do it to the old way to the end times and or something like that but something that is essentially not fast enough but barely not that or a fuse barely not fast enough so I did that for about an hour and you're watching this there'll be a link below I would skip ahead to the greedy part of the solution and I'll explain the greedy part as well yeah clicked on the button click on the button below you Stillwell bit one in the same time yeah I worry about that let's struggle the libel prevailing today it's fast enough though it still pretty slow touching to toe should be longer young one of those days nice one never go oh wow now he's having a day made the same mistake a couple of times now really that's really tight let's see oh that was the worst case actually good yes that's fair enough how do you do it then oh I must be missing something obvious well a lot of people got sick so I guess I'm just having one of those days we're missing the obvious what do you got this will be fast enough maybe I do need more sleep can you do greedy now let's try greedy I guess I know why would even get a team that's the part I don't get welcome back so for this poem for right now to be honest even for the last five to ten minutes I was just really thinking about it can be really can it well n is equal to 15 like they wouldn't give a greedy problem with and as you go to 15 right so that was my like I was out of ideas I just couldn't think of anything else because I was like okay if it's not brute force it has to be greedy or some sort of greedy but I just couldn't I was like 15 and it's you go to 15 this is you know this has to be before us right so I did really spend a long time convinced that it was not greedy because of any secret of 13 I don't maybe there's some clever 2 to the 15 solution of something but after an hour I'm trying to figure out dynamic programming and booth force and something like that I was like okay look Larry you ran out of ideas you don't I mean it you just don't have anything else right like if greedy doesn't work fine but you should at least try greedy because it might work and then you tried everything right and I already at this point you might not have seen me code everything but I was in my head I tried it like one hour like different things to kind of get it to work and I couldn't get it so after that I did greedy algorithm and I explained this idolater before in the explanation portion but basically the greedy part comes from figuring out that okay given the longest path of a course or like a given the longest path of this graph that will always be at least a minimum length way but we can't like that is the smallest minimum length of minimum semesters so I was like okay well I guess we could just greedy on that because we always want to take the longest path or the node that lot leads to the longest path be that's part of a longest path because why not right because you have to take that class before all the classes that depends on it on this longest path so basically that's what I did help a little bit I am economy on getting the longest path as you see in this function actually maybe I forgot actually I guess there's a depth per search you didn't need to cache it I didn't I think I just forgot to cash it because I thought that I would just cash it so actually I'm glad that uh whoops I only noticed this now so an explanation portion I actually forgot about this but yeah so that actually made it to complexity a lot more expensive but somehow it's still passed so I'm happy about that but yeah so given so I was just thinking a little bit of what do I need to sort it by do I need to sort by the out degrees I was like no I mean I not really because you if the out degree it's like given if a node has multiple or like a lot of out degrees you still have to clear it in some order because the longest path is to think that matters the most so what I do now is that for every class that we can take we sorted by the longest path by putting in a priority queue and then we just take the top K elements every time up to priority queue so that basically we're taking K courses or uptick a courses every time and then every time we take those K courses we free up new courses we can take and this is very sick topological SOI but I actually didn't know that you could do greedy this way so I'm happy to can learn about this today because I really thought that it has to be dynamic programming or good for us maybe I just haven't thought about this farm in a long time topological SOI I'll be on the bare minimum so I'm happy to kind of be reminded about this yeah at this way moment I was like okay do I need another key to figure out what to sort this by I was like now actually put a heap I just need the longest path I think for what I said about the outdegree earlier and then now we take every we just go through the entire list and yeah and we just take K courses at a time yeah but that's pretty much all I but yeah but that's pretty much all I have to be honest yeah because as soon as I did this I click Submit and it worked and I stopped thinking about it I was very sad but yeah still it is what it is yeah let me know what you think how do you did on this problem how do you do on this contest well I guess the other guy is still talking or going to talk so listen to him and | Parallel Courses II | activity-participants | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship between course `prevCoursei` and course `nextCoursei`: course `prevCoursei` has to be taken before course `nextCoursei`. Also, you are given the integer `k`.
In one semester, you can take **at most** `k` courses as long as you have taken all the prerequisites in the **previous** semesters for the courses you are taking.
Return _the **minimum** number of semesters needed to take all courses_. The testcases will be generated such that it is possible to take every course.
**Example 1:**
**Input:** n = 4, relations = \[\[2,1\],\[3,1\],\[1,4\]\], k = 2
**Output:** 3
**Explanation:** The figure above represents the given graph.
In the first semester, you can take courses 2 and 3.
In the second semester, you can take course 1.
In the third semester, you can take course 4.
**Example 2:**
**Input:** n = 5, relations = \[\[2,1\],\[3,1\],\[4,1\],\[1,5\]\], k = 2
**Output:** 4
**Explanation:** The figure above represents the given graph.
In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.
In the second semester, you can take course 4.
In the third semester, you can take course 1.
In the fourth semester, you can take course 5.
**Constraints:**
* `1 <= n <= 15`
* `1 <= k <= n`
* `0 <= relations.length <= n * (n-1) / 2`
* `relations[i].length == 2`
* `1 <= prevCoursei, nextCoursei <= n`
* `prevCoursei != nextCoursei`
* All the pairs `[prevCoursei, nextCoursei]` are **unique**.
* The given graph is a directed acyclic graph. | null | Database | Medium | null |
1,710 | hello all welcome to code hub today let us solve the july's required daily challenge and the question is maximum units on a truck you are assigned to put some amount of boxes onto one truck you are given a 2d array box types where box types of i is number of boxes and number of units per box number of boxes i is the number of boxes of type i and number of units per box i is the number of units in each box of the type i you are also given an integer truck size which is the maximum number of boxes that can be put on the truck okay fine you can choose any boxes to put on the truck as long as the number of boxes does not exceed truck size okay i can put any number of boxes to uh the truck as long as the number of boxes does not exceed the truck size okay fine return the maximum total number of units that can be put on the truck let us take the example and see here uh the example is 1 comma 3 then 2 comma 2 then 3 comma uh this one represents the number of boxes and number of units per box in one new box you can put three units okay the number of boxes of type okay there are explanation as follows one box of the first type that contains three units one box can be put for three units two boxes of second type that contain two units and three boxes of third type that contain one unit maximum we have to see how what is the maximum number of boxes that can be put on the truck you can take all the boxes of the first and second types we can take all the boxes of first and second types one into three plus two into two and one box of third type the total number okay we can take another one box from the third type which is equals to eight so this will be the maximum that they are saying we can take uh okay one box from the type so we will give a dry exam on the second example truck sizes tin so uh basically to maximize the answer we want to take the maximum units per bar box so we can sort the max sort the given box types on the basis of the maximum all the bases of boxes per unit number of units per box we will sort them in that order it is step 5 comma 10 then 3 command 9 then 4 comma 7 then it is 2 comma 5 so obviously 10 into some number of box we are going to choose such that we will add it to our answer so we will add 10 in 2 there are 5 boxes so since uh 8 since the total number of uh truck size is 10 so we since 5 is greater 5 is less than or equal to 10 we are going to take all the whole uh five boxes itself 10 into 5 which is 50. we will go further then the truck size reduces to 10 minus 5 which is 5 truck size is 5 now the remaining truck size is 5 now so let us see how many boxes we can take with the number of per unit box we can take 3 boxes itself so 9 into 3 here then the truck size reduces to two now we will try to take uh this uh number of per unit box as seven uh we can take uh the two uh two boxes alone since two is uh four is greater than r2 we will just take uh the remaining box two into seven and uh we will see the total now two big the remaining truck size becomes zero so we can win the process and we can come out we can now see the total 50 plus the total uh number of boxes is 50 plus nine these are 27 plus 7 14. so what is our total we get 50 70 77 87 91 so this is our answer so basically what we are doing is we are going to sort the array step steps step one we are going to sort the array based on number of per unit box number of per unit boxes and step two after sorting what we are going to do is we are going to traverse till truck size becomes zero and calculate it calculate the total number of boxes that's what we are going to do let us comment this and we can go and code the approach what we are doing is sort the array sort box types dot begin comma box types dot end we should use a custom comparator to sort in uh based on the second value static operator it is a vector in ampersand then it is going to return if a of 1 is greater than or equals to b of 1 so that's what we are going to do here then we can just travel we can have an answer we can have max units as zero and we will just return the max units here now he will traverse the array power auto boxes in my box types here is what we can say is while my size is greater than zero i can go inside i also i have a sorted order if my truck size is what we are doing is if my truck size is greater than or equal to my box types of i always we can traverse the loop itself so that it will be more easier in terms of naming auto boxes of i and box types in my box times if my truck size is zero then i will come out of this slope i will break the slope and come else if my truck size is going to be greater than or equal to my boxes of 0 then what i can do is truck size minus equal to boxes of 0 and i can add it to my answer what i can add is max units plus equals to boxes of 0 star boxes of one yes what i am saying is my track size is not having enough capacity it is lesser so that i can do is max units plus equals to boxes of one star my truck size itself and my truck size becomes zero that's it we can just run the code um oh sorry it is capital t we can just run the code again it gets accepted we will use the example test cases as well here the time complexity will be r of n log n uh since we are sorting the array here the time composition will be our n log n and space complexity will be order of one since i am not going to use any extra space now we will try to submit the code superb it got accepted and consistency is the key to success and let us see in tomorrow's lead daily challenge until then bye you | Maximum Units on a Truck | find-servers-that-handled-most-number-of-requests | You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106` | To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add. | Array,Greedy,Heap (Priority Queue),Ordered Set | Hard | null |
1,340 | Jhaal Hello Guys Welcome To Our Bloody Mary Worth It Will Be Discussed Some Questions Page In This Question Adhir Van Adhikari In Addition To Agree With U Kar Diya Answer Isko Add Ronit 282 subscribe and subscribe the Video then subscribe to the Page and to the Writer Off the indicated rites were performed but because Jai Hind Sporting Nirdaya IF All Hindus Follower of Wisdom Total Fame 1602 Oil Filter Subscribe 90 subscribe And subscribe The Amazing subscribe to subscribe and subscribe the Channel This particular question is indiscriminate Fully developed Exams from James Possible For 10th One Person Plus One Minus One Upon Time Su James David Fatty Acid Not Possible Subscribe To That Marketing That Was Doing Them Directly Benefit Is Well In Dreams With Numbers Pet Songwriting Between Two Idy Subscribe To I To Vikram Jain Ardh Starting Point To Find Out What Is The Number Of Subscribe Must Subscribe To Ka Note Use Loop And To Is Right Facebook Value Only President Is Particular Indic Computing Subscribe Ki Vinod That We Can Join This For Indic Select From Every Individual With Its Roots In Websphere Acid Use Is Particular 2010 2011 2012 Which Index Is Not Let's Move To The Duck To Mein Vriddhi Syndicate Three Android Thank you liked The Video then subscribe to subscribe Sure Withdrawal To that particular person subscribe now to receive I will jumped into it's not possible to android cell what will be the answer to the Page if you liked The Video then subscribe to the Video then subscribe to hai to idioms oneplus one visit undhiyu subscribe viewers ko Subscribe if you liked The Video then subscribe to the Page if you liked The Video then subscribe to the Hai To De Maximum Between 3238 Setting Band St Candidates In The World Will Put In To Interact With President subscribe and subscribe the Channel Hu Is The Maximum WILL RETURN FOR IN THIS PARTICULAR QUOTE ON ALL ISSUES AND SUBSCRIBE TO THE CHANNEL LOOT SUBSCRIBE I HAVE THIS PARTICULAR APPROACH AND A FEW PATNI YOU CAN ALWAYS COME BACK IN TEXT INTENDED TO WIN OVER ALL THE WHAT IS THE NAME OF THE K BUDDHO MAXIMUM DISTANT Traffic Jam In All The Current And 169 Dars Will Simply Returns The Amazing Minus Plus Luvve Jain A Minus One How To In Next Hai - Dhoi N Yadav Vve Hai To Inked A Plus Team Vijay Condition That Has Been Laid Down There Rule - - New Delhi And Tagged Govind Thakur A That Similarly I Will Write Point Hind Is Condition Hold To In Odi How To Result One Minute Continue The Maxim That We Can Get All The Best Result And Here Refill Video Channel CNN Divya For Individual As Well As For Intermediate Result Take Class The Length Of The Year Result Date Ajay Left Value is Already Present and Not Hidden 0ld The Video then subscribe to the Page if you liked The Video then subscribe to the Video then subscribe to Tu Bhi Cut Long Result Loop Against Clear Logic Pure Problems Pindi Album Method To Win Result 2018 Result Will Be Id Am Id Hai Pet Related Successfully Time Complexity Of Ru Fruitive Van Into Being Caused Her Going In Tong Hind Sporting Club Plus And Minus Liked The Video then subscribe to the Page if you liked The Video then | Jump Game V | the-dining-philosophers | Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:
* `i + x` where: `i + x < arr.length` and `0 < x <= d`.
* `i - x` where: `i - x >= 0` and `0 < x <= d`.
In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for all indices `k` between `i` and `j` (More formally `min(i, j) < k < max(i, j)`).
You can choose any index of the array and start jumping. Return _the maximum number of indices_ you can visit.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Input:** arr = \[6,4,14,6,8,13,9,7,10,6,12\], d = 2
**Output:** 4
**Explanation:** You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
Similarly You cannot jump from index 3 to index 2 or index 1.
**Example 2:**
**Input:** arr = \[3,3,3,3,3\], d = 3
**Output:** 1
**Explanation:** You can start at any index. You always cannot jump to any index.
**Example 3:**
**Input:** arr = \[7,6,5,4,3,2,1\], d = 1
**Output:** 7
**Explanation:** Start at index 0. You can visit all the indicies.
**Constraints:**
* `1 <= arr.length <= 1000`
* `1 <= arr[i] <= 105`
* `1 <= d <= arr.length` | null | Concurrency | Medium | null |
309 | hey guys today we will be solving lead for problem 3 0 9 when it's time to buy and sell stock with cool down its it's basically a variation of the normal stock problem stock price problem of buying and selling stocks where you're giving stock prices on different days and you're supposed to gain maximum profit by they're doing one transaction or and in some other cases doing multiple transactions the caveat with this problem is that you can't do multiple transactions but if you sell a stock you can only buy it after one day of cooldown meaning if you buy or if you sell your stock on day six you cannot immediately buy a new stock on day seven you have to wait until day eight to buy a new stock that's the only variation and this is a dynamic programming problem or dynamic programming problem that I like a lot because it's very intuitive it's easy to follow and it the entire problem revolves around two like two lines like two statements that will be the defining that will define the entire solution for this problem okay so you have you've been given a prices array of size n you have to basically create a deep you don't have to create a 2d array but I like working with two 2d arrays which is why I'm gonna be creating an N by two dimensional 2d array basically it will have the same number of rows as the prices array and it will have two columns so for every day so every day for every day in prices we maintain two values and these two are these two statements other ones I was stopped talking about so DP of I comma 0 it basically holds the maximum profit on day I zero stocks in hand and DP of I 1 will be the max profit on day I with one stock in so the entire solution will revolve around these two statements if you understand this you are good to go with the solution with that I think we're ready to code I'll just comment these out I'm going to be coding in Swift if you're not have know it so if it's not a problem it's very readable and I'm going to be explaining the lines of code has that code as I write down the code so he'll be good just putting it on empty prices or a check not exactly empty we are going to only work with the prices array if it has more than two values because otherwise is like there's no way to make a profit right I mean sorry the size of the prices that it has to be greater than one Atlee the size of the prices that it has to be at least two for you to sell just buy the stock and sell it to make some profit at the very least something so just putting in that border condition if the prices the size of the process that is zero or one we simply return as you know profit who are we creating a 2d array now the syntax for creating 2d arrays in Swift is a little convoluted can ignore the syntax it's here I'm only creating a 2d array of size n by two that's all I'm going initializing all values to 0 eating two columns size and crosstalk okay so let's initialize some values for day zero so for day zero if I have zero stocks in my hand it basically means that I have done no transactions at all and the maximum profit I thought I could have made in that case is zero I found a zero I have one stock in my hand it basically means that I have bought a stock on that hand and that negatively impacts the profit because I'm losing money in buying so I'm going to be initializing this with zero this basically means that I bought a stock on zero and this basically means that I did nothing I'll also initialize for day one to five oh if I have zero stocks in hand on day one it could mean two things either I did not buy a stock on days you know and I did not buy a stock on day 1 it basically means that zero profit or it means that I bought a stock on day zero which is represented by this and I sold it today which and selling will add to our profit so I'm going to add this as the prices value on day one or it could mean that if on day one I have one stalking hand it couldn't either mean that I bought at the stock on day zero and did nothing else and I did nothing on day one or I did not buy a stock on day zero which is represented by this but I bought a stock today d bo 0 comma 0 is 0 so let me just remove this yeah cool we are done with the initialization and let me just collapse this okay if so basically we are trying to return the max profit that we can have on the last day right so with zero stocks in hand we want to be done with all our transactions by the last day so this is the final value we will be returning let's start writing the for loop so for we will start processing from day three which is basically to buy our indexing so if we have zero stocks in hand on day I it could either mean two things and you have to take the max are those two things if you have zero stocks in 100 day I it basically could mean that we had zero stocks in 100 day I minus one as well and we did not think no transactions on day I or we did have a stock in hand on day I minus one and we sold it on a and if we sell something it adds to our profit because we are like receiving money and so we added to our profit for the I it could either mean this or if you have one stock in hand on day I it could mean two things and we take the max of that it could either mean that we had one stock on hand on day i minus one as well and we do it and we did no transactions on day i or we had we sold a stock one day i - to had we sold a stock one day i - to had we sold a stock one day i - to respecting the log down constraint and we bought a stock today please note that this is where the cooldown constraint we are bringing the cooldown constraint into the code because by the cooldown constraint we cannot buy a stock today if we have just sold the stock on a previous day meaning if we are buying a stock today it has to it the last transaction of selling the stock would have to be done on day I - - stock would have to be done on day I - - stock would have to be done on day I - - this is the point where we are respecting the hold on constraint and that's it a very beautiful elegant small dynamic programming solution that I really like let's see if it works okay run with this it works awesome please note that this is also an order end solution because we just have one for loop iterating over the prices array it has some space complexity but I think that's like that's kind of avoidable if it is avoidable please let me know in the comments you don't have to work with 2d arrays for this problem you could have two separate Bondi arrays this is just for this just helps me think I think better in this way but there is no hard restrictions on how you should store the values anyway thanks for your time good luck bye | Best Time to Buy and Sell Stock with Cooldown | best-time-to-buy-and-sell-stock-with-cooldown | 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 as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
* After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,2,3,0,2\]
**Output:** 3
**Explanation:** transactions = \[buy, sell, cooldown, buy, sell\]
**Example 2:**
**Input:** prices = \[1\]
**Output:** 0
**Constraints:**
* `1 <= prices.length <= 5000`
* `0 <= prices[i] <= 1000` | null | Array,Dynamic Programming | Medium | 121,122 |
47 | hey everyone this is hope you are doing good so let's start with the first question so the question is permutation two okay so what you have given a collection of numbers uh it's a num array that might contain duplicate what you have to do you have to return all possible unique permutation in any order okay so this question is similar to permutation one but the change in this question and the previous question is that in this array there is no duplicate in permutation one but in permutation two you have duplicate okay so we'll solve both so let's see how we will approach this question okay so first of all understand what is permutation okay so let's say we have given a string one now we have given an array one two three okay so if i can see i have three position okay this is one this is two this is three okay so here how many number i can take okay so let's say i have to fill this position so i have right now three numbers so that means i can fill three okay any one of them i can fill so if i filling this after this i like one of the one of them will be fill and i have like after three minus one i have two option okay similarly after filling this position to this two position i have one option so if i multiply this so this equal to 6 okay so as you can see we have 6 option and if we you do 3 factorial it's basically 3 into 2 into 1 it's a 6. ok let me show you what are the 6 possible outcomes so let's create a graph for this okay so let's start from here we will first fix this okay we fix this so now we have two options so now we have fixed this we have option of two and three okay so this we need to do now here but we have two option either we can fix this or either it can be fixed let's say we will fix this so again we got one two three now at this position there is only one so this is the fixed element now let's say you uh at the second position like if you mark this index 012 you fix this okay so then you have an option of like three will come and then two okay so now you basically roll back from here so basically it's just a back track so you will roll back from here again you will roll back so you will now change the one position now you say like you will fix the position of second okay so if you fix the position so your two will come first then you have two option one and three okay so let's say you fix this one if you fix this so you have 2 1 3 and after this like this is only single element so you just come out so you just backtrack now you will do for this so you have one more option you will take three so you have two three one okay again you backtrack from here and from here also now you say you will fix three okay so we have three here then we have one or two of the option okay so let's say we'll fix one so we will fix so three one two and we backtrack from here and we'll fix this two so for this we have an option of three two one and again we do backtrack and we again do backtrack so now we like all are visited so this is the final six output that you can see so i hope the permutation is clear to you so it's basically an arrangement of elements okay so let's see uh how we will so let's understand this question okay so in this case we have one two okay let's take this so let's create the same graph again same tree so now we will fix this one okay so if we fix this one we have two option one or two so we have two option let's say we'll take this so we have one two and we'll roll back here we again fix this two and we have one two one okay now you roll back like you backtrack from where and now you say you will fix this so if you fix this you again have one and you have the two option this and this so you have one and two okay so now again you will take one or uh one of this so you take one two and let's say you will take this so you have one two one okay now can you see this two output okay so this basically this tree and this tree gave the same output and you know the reason why because you solve the same uh element again like you solve for one now again you have one so if you solve for same uh like if the question is not for duplicate then you can easily like print all but in this motion we don't have to give the same output again we have to give the unique so we will skip this whenever the element is there so we will skip this so we don't do for here okay let's move on okay let's do for two so for two we have like we fixed two and we have one or one option okay let's say you will fix for one so two one okay now you will fix this so you again have two one so here you also can see like at this position it is correct yeah like till it is correct now you again have two same trees because you have like one is also same and one is also same so either one of them you have to take okay so i hope the intuition like the approach of the question is clear to you so let's see how we will basically write the code for this so we'll use the same code that we will write for permutation one and there is one condition that we need to add for one mutation two okay so how we will write it so we'll take uh basically we will take a l pointer from here like from start so let's give it in 0 1 2 and we will start from here every time okay so every time we will let's give me this i okay so every time we will swap this i with this l okay so first step we will swap it okay so this will remain same as it is now your l will move further now here like for this position your 0 1 2 i as this position uh you're sorry your eye will be at this position and your l is also at this position okay now again you move for that again you swap them okay so this become one two three and your l is also there and your eye is at here so again you swab it and you got the final output okay so after this you come back you again swap it so now you will move your eye only and you will swap your i basically this three with l okay so at this position one three will come and two will come at this position so you will come back okay you will again come back now your l will be at only basically this position and your i will be at this okay now you swap it so your two one three your l will be here your eye will be here so it's basically we will write a swap function with one condition okay so i think we can write the code and it will be more clear to you so let me just take a list of integer let's take a list new array list and we just return the list okay so what we have to do uh basically we'll call a function so we'll call the solve we'll pass the nums and we'll give them l basically start position so we'll give them zero okay so let me just write the function let's solve nums and this will be our l so what we have to do for end i start from zero i will num start length i plus okay so first step you just have to swap it sap your i with your l so let me just pass nums i l and you will again call your function so pass nums and this time you will pass l plus one okay because here you fix this position okay so at this position you fix this l so you start from here you fix l now you have to do from here okay so you have to increment url okay so now after this you have to backtrack from here so you will backtrack you just do swap again like roll back my current position again i okay so let me write the swap function okay avoid swap and we'll pass numbers will pass s and let me give e so what we will do will take in a temporary variable and numbers of e it's basically a swap function so after this what you have to do you have to add a base condition so what will your base condition if l is equal to nums dot size so like this is the final output that you need to need in the output so if it is reaches to this you have to create a sub list new arraylist and num sub dot add so i'm basically taking every element from nums and inserting into a sub list and after that i just insert it into my main list so let's start at sub and we just do written okay i think we have 10 with the code so let's run it okay let's see okay so we are getting output two one oh why it is two one first zero l okay so your i will start from l basically so if we run this okay now you can see we are getting output as one two similarly we are getting outputted as one and you can see for two one okay so if you submit this question for permutation one it will be submitted but for volumetricion two you need to add one condition so what will be the condition basically you need to check at that time okay so when you solve for one okay at the same level like when you take one you need to check whether you are taking the same one again or not if you are taking it you just have to skip okay now you can see for this case also for after two we take one but again after that we take one okay so at the internal level we so for permutation two we need to add one condition and this will be the condition so it will be like so condition is pretty simple you just have to take a set okay so this will be your set new hash set okay and but you just have to insert into set dot add nums of i and for the next time you need to check if set dot contains this numsai skip it you don't have to process it okay so let me just yeah so now let's run it now you can see we got our output and let's submit it okay cool our code is submitted the time complexity is basically same for permutation one we are creating uh you can say n factorial per mutation so it's sine factorial and we are taking extra space of set that's uh order of n you can say at a time so yeah hope you like it thank you for watching and do join the telegram group if you haven't doubted any concern thank you | Permutations II | permutations-ii | Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:**
\[\[1,1,2\],
\[1,2,1\],
\[2,1,1\]\]
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Constraints:**
* `1 <= nums.length <= 8`
* `-10 <= nums[i] <= 10` | null | Array,Backtracking | Medium | 31,46,267,1038 |
100 | hello hi everyone welcome back to the channel so today in this video lecture we're going to be solving this problem same tree so this problem in this problem we're given two binary trees the roots of two binary trees p and Q these represent the root nodes of the binary trees we need to write a function to check if they are the same or not basically the binary trees are same or not so when do we consider two binary trees to be the same if they are structurally identical and the nodes have the same value like in this case these two trees given in the example number one are identical because they are structurally identical both of them had three nodes and the values at those roots matches the root node of both of these trees has a value of one the left node for the left sub tree contains two same goes for right sub tree and the right node of the left sub tree contains three also the right node of the right sub tree also contains three so they are identical so what do we have to do in this problem is to return true or false depending upon whether these trees are identical or not right so let's see how we're going to solve this problem so basically the problem is simple if you're given two trees so let's take a tree one let's say we have two we have three here then we have four like this and we have a similar tree 1 2 3 we have four like this so we need to check if they are identical or not so how we're going to do is we basically check we move we start from the root node this is the root node We compare the values here they are same fine we move to the left sub tree of the left tree this one we also move to the left child for the right subt as well which is node number two so here so now we are standing at this point and we are standing at this point so let's say p represent the pointer which basically points to the initially which points to the root node of this left sub tree and Q is the poin of which points to the root node of the right sub tree so now the p is standing at this node and Q is standing at this node so let's match the values are same you can see that two matches with the two we again move to the left side so we move here also we move here so we compare the values so the P comes here and the Q comes here let's compare the values again they are four so let's again let's move to the further let's move to the left one more step we can see that this node that is node number node which contains four do not have any left CH same goes for this node as well that means till this point they are identical so we return to the calling node which is node number two and here we return again we can see that both of these two nodes do not have right child we again move back we move back here now here we can see that we have the right child for this node same goes for this we have the right child for this tree as well so we move to the right child okay so we are here the p is here Q is here let's check the values again we have three here do we have a left child for three no we do not have a left child for this three same goes for this three as well we do not have a left child we also do not have the right child this node also do not have the right child so that means these trees are identical right so what do we have to do is we basically create a function let's see is same tree function which is given in there and this takes in the these pointers p and pointer q and what this returns is true or false depending upon the trees whether they are identical or not right so initially in this function we have p and Q what we're going to do is we're going to check if these nodes p and Q are null so this is the base case When we arrive at a node which is let's say left child of this node four and left child of this node four we can see that we do not have any left child so in that case p is null and Q is n so in that case we return true that means till this that means we have matched the sub tree of node number four for the left sub tree and the sub tree of node number four for the right sub tree so that is the base case otherwise we have to check for any node on which we standing so let's say we standing here initially at this point we need to call the same function is same to recursively for the right child which is node number two and the right child of node number Q which is node number the left child of node number two of node number of node Q right so left child of node p and left child of node Q fine so we'll call the same function recursively for the left child and for the right child if both of the functions returns true that means the left sub tree for P for this tree and the left sub tree for the for this node mode for this tree as well as the right sub tree of this tree and the right sub tree of this tree matches with each other fine so if they match and this node also matches P the value at P matches with the value at Q that means the tree are trees are identical and this holds true for all the nodes of the tree so for every node all we have to do is to check is to recursively check whether the left sub tree of that node and the left sub tree of the same node in the right tree in the in this tree pointed by this pointer Q are identical and the right child of right sub trees of both of these trees are also same or both of these nodes are also same so we have to check for three conditions for any node we need to check if the values are identical so values of the nodes are identical fine the second thing is the left sub trees for both of the nodes must be identical that is left sub trees and the third thing is we need to check if the right sub trees are identical so if these three conditions holds true that means the trees rooted at those uh rooted at the nodes p and Q are identical fine so that's the thing so let's jump to the code implementation part so here we can see that all we have to check is same so let's check for the right sub tree let's check for the left sub tree left subtree for node number P and left sub tree for node number q left if it returns false then that means the left sub trees of these two nodes are not identical or also check the condition if this is same tree same function is same t for right and Q right if it is false then we're going to return false from here otherwise return true also here initially check if p is same as Q in that case if p is null and Q is null then we're going to return true why because this is the base condition when we let's say here for this case let's say four we recursively call the same function for its left child and we pass null okay and also we recursively call the same function for the left child of this node which is also null so both of these sub trees are matching why because both of them do not have any node right so that's why we have to return true for this case fine so other base cases if let's say one of the child is null maybe there's a case that P is null and Q is not null this may be the case or there can be a case that P is not null and Q is null right or there can be a case that the values at these nodes Q value is not equal to the value for the right sub tree if it is the case then we're going to return false so I hope I covered all of the test edge cases the base cases okay it's not capital Q it's small q so I hope you got the idea let's try to submit it what me a wrong answer it's not me Q is now okay it's all if one of them returns if one of these two conditions is true then we're going to return false why because we can see that if the left sub tree for the left tree and the left sub tree for the right tree are not the same then we return false or the right sub tree of the left tree or the right sub tree of the right tree are not s then we return are not same then we return false fine so okay so that's all for this was a recursive approach although there are other approaches which we'll discuss in other videos so that's all for this video if you like the video then hit the like button and make sure to subscribe to the channel and we'll see you soon in my next video till then take care bye-bye | Same Tree | same-tree | Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
**Example 1:**
**Input:** p = \[1,2,3\], q = \[1,2,3\]
**Output:** true
**Example 2:**
**Input:** p = \[1,2\], q = \[1,null,2\]
**Output:** false
**Example 3:**
**Input:** p = \[1,2,1\], q = \[1,1,2\]
**Output:** false
**Constraints:**
* The number of nodes in both trees is in the range `[0, 100]`.
* `-104 <= Node.val <= 104` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | null |
1,601 | this is a column called maximum number of achievable transfer requests that is you have and buildings number from 0 to n minus one okay each building has a number of employees yes transfer season Transformers want to change the building reside in you're given an array request the request type also from two representing employees request to transfer from building okay so some employee will put in a request he will say I want to move from this to this all buildings are full so a list of workers is achievable only if for each building the net change in numbers multiply 0 okay so if x employees Lee building one then uh x members have to also come into building one all right this means the number of Employees leaving is equal to the number of employees moving in for example if n equals to 3 and the two ampers are leaving building zero and one is even building one and one is in building two there should be two employees going to building zero one employee building one and one of them right so number of levers should be equal to number of incomers within the maximum number of achievable requests right so for some examples so here this is given from many zero we are employees uh so here what you can do is XM I want to reach building leave building one so for X you could just do B comes to building one so X and B can meet each other so y goes to building one somebody has to leave building one a leads to building two and somebody is from submarine so this cycle yes that's what it says here like we can achieve the request of X and B by stopping their places right X and we will just snap each other which is a cycle uh in the three building makes sense so we have to where uh could consider like number of Cycles make a graph and figure out numbers like this that could be one way but like which path to choose here once you choose a path you have to choose every option so for every request you'll either choose it or not choose it right so how many requests are there so the number of requests are quite Limited uh the number of requests are limited I think we have to use that fact foreign so let's consider all possible combinations of uh accepting requests like you accept the request you don't accept the requests right so for every request are you either acceptable don't accept it and then you keep doing that you consider all the combinations and then for every combination uh you see that's a valid combination yes for example you didn't accept any request that's fair it's a valid combination and uh it's a valid combination and it is the number of requests require zero let's say you request these two accepts only again it's a valid combination so number equals except there are two you accept only these three requests why to one a two and uh Z to zero even that is a valid request of three so if you consider one two three four five all of these five requests if you consider that's valid this request count if you consider then it's an invalid combination so let's do this uh try on combination of requests how many of these would be there so it's 2 to the power R for every request you know you have to do that for each combination okay let's check if it's valid if valid update Max I think that's not right so Albert is how do you try all the combinations I guess Okay so now do it recursively okay and how do you check valid well you maintain so that's another thing right how do you check on it maintain in Commerce and outgoers for building for each combination right so maybe save like out minus in for each building should be zero for each building Okay so we have to define a building States you have a building state equals to new index size and for each building yeah okay fine for each building maintain out minus n right I will start from the first request so you return the maximum requests so however what is this change to this and this so you're saying in maximum requests we start with this start index and we go with okay so you go with this building state and then you go with this request array Maybe so you want to talk uh so you wanna update on maybe okay let's do we don't know how to return first so you do maximum requests let's make it white so you do maximum request of starting index is zero building State initially everything is valid and then you do uh request sorry and every time when you complete a combination that would be the case when would be equals to you have shared each and every request let's also maintain an accepted requests foreign let's return this guy so now what you want to do is how do you do that you check the building state so is valid is let's say you say true and go through each building so for each building in building state if B is not equal zero if out minus is not equals to zero then well then is valid as false when you break out of this Loop and if is valid then you do the Max acceptance request as math Dot Max of Universe comma whatever these accepted requests are right and then you return and if that's not the case then you look at this next need to draw you take two options option one don't accept the request so in that case you do just call this function with index plus one same buildings it doesn't change whatever States the buildings were in the array of liquids and whatever accepted requests were there so far okay and what is option two is accept the request that you accept the request the building state will change so first change the building state of which building well request start index zero which is for the building that you're moving out from so minus and this will show the building you are moving into so you change the building state and then you call this guy with just this and accepted request plus one right and you want to backtrack as well so let's get back to the original state that you were on so you will do plus here and minus Mass here does that sound here all right let's run the code and check any compilation errors there are few line number seven you wanna add a semicolon uh you want to return it okay wait a few seconds sorry again traffic small compilation errors yeah the last all right so basically you've tried all combinations and for each commission check if it's valid then you see how many requests are accepted in that combination and Implement your total Max so that's all | Maximum Number of Achievable Transfer Requests | maximum-number-of-achievable-transfer-requests | We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`.
**All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`.
Return _the maximum number of achievable requests_.
**Example 1:**
**Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\]
**Output:** 5
**Explantion:** Let's see the requests:
From building 0 we have employees x and y and both want to move to building 1.
From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
From building 2 we have employee z and they want to move to building 0.
From building 3 we have employee c and they want to move to building 4.
From building 4 we don't have any requests.
We can achieve the requests of users x and b by swapping their places.
We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
**Example 2:**
**Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\]
**Output:** 3
**Explantion:** Let's see the requests:
From building 0 we have employee x and they want to stay in the same building 0.
From building 1 we have employee y and they want to move to building 2.
From building 2 we have employee z and they want to move to building 1.
We can achieve all the requests.
**Example 3:**
**Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 20`
* `1 <= requests.length <= 16`
* `requests[i].length == 2`
* `0 <= fromi, toi < n` | null | null | Hard | null |
617 | hi guys hope you're doing great our today's question is much to binary trees given to binary trees and imagine that when you put one on top 100 of them to cover the other some nodes of the two trees are overlapped while the others are not you need to merge them into a new binary tree the merge rule is that if two nodes overlap then some node values up as the new value of the merge node otherwise the not null node will be used as the node of the new tree so for example here this is the 3 1 & 2 and if we basically this is the 3 1 & 2 and if we basically this is the 3 1 & 2 and if we basically place the tree 2 on top of 3 1 right so whenever there are or wherever there are positions where there is an overlap between two nodes so that new node will be the sum of the two nodes that are being merged and if there's only a single node then just that node comes out as the value of the Basri so if you see here when what 2 is placed on top of 1 the sum is 3 when 3 & 1 are combined 1 the sum is 3 when 3 & 1 are combined 1 the sum is 3 when 3 & 1 are combined the sum is 4 here 2 plus 3 is 5 but for example since here the right child of 3 is none whereas the right child of 1 is 4 so the final value is 4 right the merging process must start from the root nodes of both trees okay so here clearly we need to if you think about the approach that we should take to solve this question so for trees we have either recursion or we do some sort of a traversal the naive approach would be that we traverse both the nodes create maybe a level order traversal keeping nuns in place and then just using those two areas summing then up them up and then creating a tree out of that but that would definitely not be a very good solution so let's think about how we can solve it recursively so for every node we just need to understand that the other tree has a node at this point right at it at this position if yes then we create a new node with some value of those other nodes those two nodes and then the left of that new node would be the sum of the left of both these current nodes like we're processing and the right would be the sum of the right nodes right if both of them are done then it's a null if either of them is a null then we have to basically just return the normal for the merge tree right so keeping that in mind we can just apply a very simple recursive algorithm to solve this question so let's get started okay all right so we just implement the function let's say we just have don't even need to initialize we'll just return let's call it merge and we provided T 1 and T 2 okay now let's implement this so this will be 3 node 3 1 power 3 node T 2 ok fine so as I was saying if let's have some base conditions taken care of first of all so if T 1 is equal to null and T 2 is equal to null as well then we just have to return a null right if T 1 is equal to null and T 2 is not equal to null then we just have to return T 2 because that's not null and that will be the only merged object similarly if T 1 is not equal to null but T 2 is right then we just return P 1 ok so if none of these conditions is true it means that we have two valid nodes which have got some values in them so what we will do is we just create an new node called sum which will be the which will have value equal to the sum of the values in both T 1 and T 2 so we will just do a summation here yeah right and talking about the left and the right so the left child of this node would be the merged value of P 1 dot left and T 2 dot left and similarly the right child of this would be a merged value of T 1 dot right and T 2 dot right okay and we just have to return some after this yes looks good so let's try to run this okay fine it works so the time complexity is o of n because we are just traversing both the trees once and the space complexity is o of n is when because of recursion so the recursion stack has space complexity equal to the number of objects or elements that we are working on so it's go of n as well so I hope you guys find this when you're helpful if you do please like share and subscribe keep pouring antiquey guys | Merge Two Binary Trees | merge-two-binary-trees | You are given two binary trees `root1` and `root2`.
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Return _the merged tree_.
**Note:** The merging process must start from the root nodes of both trees.
**Example 1:**
**Input:** root1 = \[1,3,2,5\], root2 = \[2,1,3,null,4,null,7\]
**Output:** \[3,4,5,5,4,null,7\]
**Example 2:**
**Input:** root1 = \[1\], root2 = \[1,2\]
**Output:** \[2,2\]
**Constraints:**
* The number of nodes in both trees is in the range `[0, 2000]`.
* `-104 <= Node.val <= 104` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | null |
199 | Hello Hi Guys ready today video seven I in this we will see the second approach of binary tree right side view earlier in that we had decided which level ROI and in this approach in this video we will fold this question by preorder traversal i.e. David Okay, so input it, they have done the i.e. David Okay, so input it, they have done the i.e. David Okay, so input it, they have done the footwear is broken, I told here in the last video, so if you stand on the right side and look, you will see the rate 1314, so how to solve this problem, so this is a bit interesting solution and quite helpful to me. The solution seems good, it is okay, it happened in an interview in 10th I plant discus settlements and interview that both the projects were asked, okay, can it evolve into it is difficult for the face, okay, it is important to know even the dad, so let's see how can solve it. Okay, so first of all think this one thing yourself and then the duty is that whatever level of the track is okay, whatever level and how many labels are there in it, one to three is okay, then whatever level the track will be in the output. There will be so many elements that now if you are watching Ayodhya Brightside OK, then you will see one element of each level, this level of top level is number one, tight, this is level number two, this is level number three, so you will see the first lemon of each level. If it is visible then it is okay then look at the level one saw level two cash also saw the level is okay for saw then how many levels are there in total is free and here my answer is also three elements of the set max Samsung j11 is romantic from you, from the right side then you Think for yourself, elements should come on the day of your resort. Okay, and girls' level-3 add Okay, and girls' level-3 add Okay, and girls' level-3 add top, why do this that as you travel in each level, when you travel, on matters, either this inverter judge orbit and now this one cross. Now if you are doing so, then enter the level which will be the first element of that level. Okay, let's assume that now you are on the first level, the phone is fine. Let's understand this from a good gram. I have given a diagram in which by hitting the level. Okay, level is zero, level one is 514, in 2002, okay, so look, we still do strange traversal experiments, okay, right now I am here, okay, I am here right now, and right now, I have not cast a single vote in my element. If I have not put it, then mine will be the output which will be the response, so it is okay, I have not put it in the back because its size is zero, okay, what is its size now and how many levels have I charted, I am one to two. Three, I consider the level to be good, it is fine, level Vansh, is this level-2 or is it good, it is fine, level Vansh, is this level-2 or is it good, it is fine, level Vansh, is this level-2 or is it level 3? So now see, you are level-1, you started from your place, your route is right, is level-1, you started from your place, your route is right, is level-1, you started from your place, your route is right, is n't it, your anger is this, so from your place. You have just started the phone at level-1. Now check the You have just started the phone at level-1. Now check the You have just started the phone at level-1. Now check the size of your output. Now it has reached 0411. Your phone is at level-1. The phone is fine. 0411. Your phone is at level-1. The phone is fine. 0411. Your phone is at level-1. The phone is fine. This means that there should be an inverter in your output so that you are also at one level. Yes, you are at level-1, so there Yes, you are at level-1, so there Yes, you are at level-1, so there should have been a building element in your output also, so I saw that the size of the output and the size of feet is London level, which means I have to put an element in the output, then level. So right now where is my root, put one fruit, callu, put it blindly, okay, I have put one, okay, now what did I do, what did they do in the reactor, first they used to check the root, then in the dear. Then used to print and then go to the right side and go after f4 or you will go to the left foot first and then go to the right so I am going to the right side first or the right side only, now see the right side will get it. I will get food only on the right side, so I answer, now I know, I went to the right side first, it's okay, so level two here, this level two food is okay, so now I see the size of my feet and my feet, I have reached puberty and How much is our level, one laddu is still ok so as I have checked my output is weak size is one and that is smaller than the label so I will put the element ok so that I can match with the level so right now I am upset here. It's the turn of the root, it's free, so I have put free in the response. Okay, let's remove it. Then I'll go right. Okay, verification is going on. On the right side, this is the level happy here and what is the size of the output? Kitna mere tu hai. Na see this and totka is cb2 na now music is 183 got it ok so here I saw that there is another 262 and this is less money level woman or right so what should I do I will do element for I have added it here But okay, now the request will go back, okay, the regression has gone back, after the return of the pass three, you will go to the spread of the free, otherwise there is nothing in the left leg of the free, otherwise it should be returned, okay, now the extra session has gone back. I went near there, it's okay, now if I go to their lifestyle, then I am going to the left side, see, it is level-2, here on the right, I came here, it is level-2, here on the right, I came here, it is level-2, here on the right, I came here, it is level-2, now I will check again, is level-2, now I will check again, is level-2, now I will check again, what is the size of the output? And what is the trick, what is there ever, it has become three, is n't it, what is there besides that is laddu, is it not like that even if the level is Meerut, so I will not talk about any more food and move, ok village answer is not working for you, now I am on two. You are there because I will go to the right side, you have gone to the carat channel, it is level 3, it is right, now I will check mine and only the trick is free, what say, day is level is useless, if it is not so, then I will not do anything else, okay Felt channel has come near 5, there is nothing on the right side, I went back to Tu, I have to go to the left side of you, there is no one in the lab, then I came back to reaction one, our story is over, you see your answer too. I have taken it out, okay, it is quite simple, but I like the left way, the solution is okay, so let's fold it and see. Okay, now let's start courting. Questions have a right side. It is taken out. Host Retrika. Okay, so what did I say? I will do preorder traversal ok and will also keep checking the level so first I had to create my result in which I have to send the result then send it from this and I will return the result in the last ok but now I call this that the root level Start where learn from seven and I send the result okay now let's call it there da hands free mode on the root and level vector and different sell the result so that in this every task wallpaper of answer cod that last one is angry so App is the biggest fruit educational, if it brings anger then this pattern when you can't do anything is fine, after that you will check the level here whether the size of my result is national level, if it is London then give Pushkar current route in the result. Okay, okay, made happy and we have to call pre-order Okay, call pre-order Okay, call pre-order Okay, now I will first go to the right side, in the right channel and level plus one because the result is going to the next level, after that in the left leg. I will go to A level plus Vansh result is good ok lassie now that tweet of running all the test cases I have call details to you how presidents of years will pass all it's A stay in grade health positive cases commission you understand there would be any doubt If yes, then please comment, ok friend, happy note, thank you bye-bye. | Binary Tree Right Side View | binary-tree-right-side-view | Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_.
**Example 1:**
**Input:** root = \[1,2,3,null,5,null,4\]
**Output:** \[1,3,4\]
**Example 2:**
**Input:** root = \[1,null,3\]
**Output:** \[1,3\]
**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 | Medium | 116,545 |
1,672 | hello friends welcome to coding host youtube channel in this video i will explain you a lead code problem recharged customer wealth so in this question we will get a m into an integer grade accounts where accounts i and j is the amount of money is customer has in the jth bank return the wealth that the just customer has so in the example one you can see that we have a 2d array and in this 2d array we have two rows this first row and the second row this first row is for the first customer and the second row is the second customer inside this rows we have this values and this values are the wealth of the customer having in different bank so this is the wealth of the first customer which is having in three bank so we have to find that whose wealth is the highest so now let's write the program so in the program first i will take two variables end max 1 equal to 0 and max 2 equal to 0 then i will take for loop for into i equal to zero and i less than accounts dot length and after that i plus now inside this for loop i will take one more for loop for end j equal to zero and j less than accounts of zero dot length and j plus now in this for loop in this max one variable i will add the element which is at index i and j then i will take if statement if j is equal to accounts of 0 total length minus 1 then in this if statement we will check that if max 1 is larger than max 2 then in the max 2 variable we will store max 1 and in the last we will return our max 2 variable and after this if statement we also have to make this max1 variable equal to 0 now let's run this program so you can see that this program is working fine now let's see how this program is working so you can see that in the program we will get a 2d array so this first row is for the first customer this second row is for the second customer so this all elements in the first row is the wealth of the first customer and elements in the second row is the wealth of the second customer so we have to find that whose wealth is the highest so we have to add the element of each row and then we have to compare them so i have taken these two variables max 1 and max 2 so in this both variables value is 0 and then i have taken two nested for loops so this outside for loop is for rows and this inside for loop is for columns so i is starting from 0 i is less than accounts dot length so in this 2d array total rows is 2 so i is less than 2 yes then it will check in this next for loop for into j equal to 0 so j is starting from index is 0 so then it will check that if j is less than accounts 0 dot length so here it will check the number of columns total column is 3 so j is less than 3 yes then we will go inside this for loop and in the max1 variable it will add the element which is at index i and j so at index 0 and 0 element is 1 so in the max1 variable we will get 1 then it will check that if j is equal to accounts of 0 dot length minus one so here we are checking that if the index of j is equal to the last index of this row so last index of this row is two and right now j is zero so it is not equal to 2 so this if condition will not execute then j plus so j will become 1 now in the max 1 variable we will add the element at index 0 and 1 so at index 0 and 1 we have 2 so we will add 2 in the max 1 variable so now in the maximum variable we will get 3 after that again it will check here if j is equal to accounts of 0 dot length minus 1 so no j is 1 and it is not equal to 2 then j plus so now j will become 2 now it will add the element from index 0 and 2 in the max1 variable so at index 0 and 2 element is 3 so now in the max1 variable we will get 6 after that it will check here if j is equal to accounts 0.9 minus 1 yes equal to accounts 0.9 minus 1 yes equal to accounts 0.9 minus 1 yes so j is at last index of this row yes it is 2 so this if condition is true then it will check this inside if statement if max 1 is larger than max 2 yes max 2 is 0 and max 1 is 6 though in the max 2 variable now we have 6 then we will make our maximum variable as 0 so max 1 will become 0 because now we have to check the values of next row and we have to add them in the maximum variable so now i plus so i will become 1 so it will add the element of the next row in this max1 variable so first it will add 3 so in the maximum variable we will get 3 then it will add 2 so it will become 5 then it will add 1 so it will become 6 so when the value of j will become 2 then in this if statement it will check if max 1 is larger than max 2 so you can see that max 1 is 6 and max 2 is also 6 so value of max 2 will remain 6 and then max 1 will become 0 then j will increment so j will become 3 so j for loop will break then i plus so i will become 2 then this i for loop will also break and in the last we will return our max 2 variable in which we have max wealth of the customer which is six so now let's submit our program so you can see that our program has submitted successfully and the time complexity of this program is big of n square because here we are using two nested for loops and the space complexity of this program is big o of one because here we are using two variables thanks for watching | Richest Customer Wealth | find-the-index-of-the-large-integer | You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `ith` customer has in the `jth` bank. Return _the **wealth** that the richest customer has._
A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**.
**Example 1:**
**Input:** accounts = \[\[1,2,3\],\[3,2,1\]\]
**Output:** 6
**Explanation****:**
`1st customer has wealth = 1 + 2 + 3 = 6`
`2nd customer has wealth = 3 + 2 + 1 = 6`
Both customers are considered the richest with a wealth of 6 each, so return 6.
**Example 2:**
**Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\]
**Output:** 10
**Explanation**:
1st customer has wealth = 6
2nd customer has wealth = 10
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.
**Example 3:**
**Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\]
**Output:** 17
**Constraints:**
* `m == accounts.length`
* `n == accounts[i].length`
* `1 <= m, n <= 50`
* `1 <= accounts[i][j] <= 100` | Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer. | Array,Binary Search,Interactive | Medium | 786 |
1,091 | hi everyone today we are here with the new problem and the problem is shortest path in a binary matrix so it is a medium type of problem and uh yes it is between the easy and medium and first we see what is the problem and then we see how we can solve it right so basically in this problem we have a given n cross and binary matrix why binary matrix because it consists of two values which is zero and one so what we have to do we have to return the length of the shortest player path in the matrix if there is no clear path then we have to return minus one here what is clear path so clear path in a binary matrix is from top left which is 0 index to the bottom right which means the last n crop minus 1 and then minus 1 index so all the visited cells of the path are 0 and we can move in the a directions but uh what we mean by this let's understand this with this example so basically let me give the induction 0 1 2 and 0 1 2 so basically in this starting we are at this point and we have to go at this point right you can consider that zero is a clear path and one is obstacle it means where zero is present we can go to that cell but where one is present we can't move to that side okay the another thing is let's suppose we are at this position or we are at this position we can move to the a direction which means this direction this so basically we can move in this direction okay i hope you get it now what we have to do now to go from this position to this position one path is we can go there then there and there in this how many cells we have to go through one two three four five right and we have to find the shortest path right we have to find the shortest player path so this is not the shortest clear path because we can move from there then directly there so how many cells we have to iterate we have to address the four cells which is one two three and four now basically how we can solve this problem so you can try different approach to solve this you can pause this video and try it once and if you are not able to solve it let's see how we can solve these problems so basically in this type of problems where we have a given cell and we have to move through uh from some index to some index with some constants like this in that case we have to always think about some recursive okay or some iterative approach okay we're actually what we have to do basically let's suppose in this problem we have uh given that we can move in a direction so let's suppose we are at the zeroth index so what do you mean by a direction it means we can go at one zero right we can go at minus one zero we can go at 0 1 then we get go at 0 1 right not 0 1 we can go like minus 1 0 if we go to this direction which is 1 and 1 if we go to this direction so it is a minus 1 0 if you go to this direction so it is like a if we move to this uh direction right so what it is a minus one and if we move to this direction then it is uh minus one and uh so let's suppose this is the zero through it is minus one and uh we are at this so basically it is also minus one and here in that case it is 0 1 it is minus 1 so basically these are the directions right if we are at 0 direction we can move to this a direction now this is good after that the third thing that we have to take here is a boundary condition okay what it is a boundary condition means for this you know if you are at 0 index if you move to this side so there is no cell so this is a boundary condition where we don't have to check if we move to upside this is a boundary condition because there is no cell if we go to this there is no sun but there is cell there is a cell so the another thing is in these type of problems we have to understand the boundary condition and that's it now what we do basically let's suppose we are at the zeroth index and for that we basically take uh we basically take a stack and push this zero the index and the cost is initially one right because we are at this cell so this is one cost now for this how many cells we can iterate we can act at only this function right because one is not a clear path you know this one is not a clear path this is the powdering addition this is about the conditioner this is also about the conditions right so we can only consider this one path so let me write indexing one two so for this we only have zero one index and what is the cost now zero one and two so the cost is two if we move from there to there now we are at the zeroth one index now from there uh where we can move to this and we can move to this other than that this is not a good case and other one is boundary so what we do we can simply and also let's suppose we visit this one and if we are at this so if we move back so we all already hydrated so the cell which we hydrate before we have to convert their value to one such that we can understood okay this one is already processed so we don't process it again right otherwise uh this cell is again uh processed and this cell is again processed this cell and we get the tl error now so we uh we have two things this one which is 0 2 and this one which is 1 2 so if we remove this so what is the inner cell which is 0 2 and cost is 3 and for this we have let me clear it little bit which is 1 and 2 1 2 and cost is 3 now you can see we remove this one cell right and this is 0 2 for this we have to first make this one so that we don't hydrate it again for this we can take it again the only thing we can take it again so we all again put this out we again put this out and make it one and write one two and four right because here the cost is three now the cost is four right let me clear some make some more space okay now we remove one two which is this side right and we make it one after we move out from it and then what we push this so we have one two four already we have to push 2 to and what is the cost this is 3 the cost is 4 right now we uh pop this from the stack and when we pop we can see that 2 is the index where we have to go so this is the destination and when we reach at the destination we have to start stop and return this 4 and this 4 is the length right and that is what we have to return now there is one question in your mind what is it obvious that every time we get the shortest path yes it is why because when we go from there to there and when we reach there we have two things this thing and this thing right and where we have to stop when we reach at this index right so let's suppose we reach at this index and we reach at this index now you can understand from there this cell reaches fast then this cell right and if this cell reaches there it will go through two more cells right till there the cost is three until there the cost is three if we come from there right so it reach fast then this and when it moves from there to there it increment by one which is four and we can simply return four i hope you understand this otherwise uh we will see the code and understand from there so let's see the code uh we simply check one more thing let's suppose if our starting position which is this zero if it is one we are not able to start or if this is one we are not able to reach in that condition we simply return minus one because we are not able to find a clear path other than that we simply take a stack and in that stack what we do so basically it works as a queue how it works let me show you so we basically push 0 and the cost is 1 so 0 is the index means the first cell we are at right and you know the cell where we are at we make it 1 so that we are not process it again now we loop this q which is i j is the index and d is the cost if we reach at the last index we simply have to return the cost other than that we have to go through all these eight positions and for this x and y we need to check the boundary conditions and we also have to check the new cell should not contain value one in that case we first make this thing as one so that we not process it again and again push it in the queue and this process goes on until and unless we reach at the last cell if we reach if we are able to reach at the last cell we have to return the cost and if we are not able to reach after this loop we can simply return minus 1. let me submit this i hope it works yes it works and i hope you get the problem how we can solve it thank you | Shortest Path in Binary Matrix | maximum-average-subtree | Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that:
* All the visited cells of the path are `0`.
* All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner).
The **length of a clear path** is the number of visited cells of this path.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** -1
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1` | Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution. | Tree,Depth-First Search,Binary Tree | Medium | 2126 |
981 | in this video we have to design a key Value Store so let's understand the problem it says that we have to implement this class Time map and here we have to define the Constructor the setter method where you pass the key value so in a typical key Value Store like any hash map or any other map you just need key and value but here there is this additional parameter time stamp so uh this timestamp enables you to have a multiple values corresponding to the same key so we have let us say key one then it can have more than one value so well one at timestamp T1 then the same key has let's say value 2 with timestamp T2 and it can have more so you can think here the value is a vector or a list in itself and each list each element of the list is another Tuple with two values one is a string value and another is integer time stamp and then we have this getter method where you just pass the key and timestamp so in typical key Value Store you would pass key and you would like to fetch the unique value here you are passing key along with this additional timestamp so if there are multiple values along with timestamp what we should return so it may be possible that this timestamp does not exist then in that case it does not mean that we will return empty string these values are strings so if timestamp is not found it does not mean that we have to return empty if it's found let's say and one more thing is that there will not be any duplicates so if all of the timestamps T I will not be equal to T I plus 1 or I minus 1 or 2 for any pair so these are unique and these are strictly in increasing order so whenever we insert any value or set any key value along with timestamp next time we call the set the next timestamp will be higher than previous so this way it guarantees there is no duplicates so uh but the thing is that if you let's say the query was for timestamp T2 then you see that so the query was key one we will see a concrete example then it will be even more clear so let's say we once we have set a few values few keys and values and time stamps let's say for key one we had these two values value one value two well one half times time of t one well two hat timestamp of T2 and we query for key one and timestamp T2 then we will return this Val to so let's take concrete time stamp let us say this is 3 and this is 5 this T2 and let us say the strings are well one while two so if we query for key one and five then we return value two but let's say we query for 4 instead of 5. then we have to return this valve one so time stamp should be less or equal to so if it is equal to good and great if it's not equal to then we look for immediate lower value so it may be possible that we had V1 at time stamp one V2 at times to M2 V3 at timestamp 4 and we queried for let's say V timestamp 3. so 3 is not present here but we see that 3 should come here between two and four so we will return the lower one not four but lower in the lower also we will have multiple values but we will return the immediate lower the maximum among the lower values so this is the problem statement now let's work through a concrete example so this is the input set so Time map is the Constructor so it will not take any parameter so these are the one-to-one mapping this so these are the one-to-one mapping this so these are the one-to-one mapping this first call First parameter so Time map is empty so it constructs the time map then first set is called so it sets this first parameter is the key second is the value and then time stamp so key is Foo so Foo has bar with timestamp 1. then we've called get key is for well time stamp is one so we exactly find this value so we will return bar so you see bar is the output here so for Constructor and Setter there is no return value for this gate we have this bar then again we call get but we call timestamp 3. so 3 is not present in this key Value Store so we look what is the immediate lower value it may be possible that there is no value let us say we called for four one then that key does not exist Also let's say we called for uh times time zero so there is no value with timestamp less than or equal to zero so in that case both the cases we return empty string either the key is not found or key is found but there is no value with timestamp lower than or equal to the query time stamp so in both cases empty string so here we call get and we call Foo with timestamp of three is not present so we look for immediate lower we found one times time one so again it will return bar then we call set so set does not return anything and we set Foo same key this time the value is bar two it's a string you can enclose in quotes time this time is 4. so this will be in increasing order next we query forget with key of 4 times temp four so it should return exactly bar 2 then we query for Foo key with timestamp 5 so 5 would have come here but 5 is not present so we look for immediate lower that is bar 2 so it will return bar two now hope this problem statement is clear and all the cases are clear now let's see how we can approach it so for Constructor we don't need to do anything so the name of the class is Time map so we have class Time map and then we have we can store uh so this is a key value store so the keys are unique so we can have unordered map in C plus or in Java you can have hash map or unordered map where the key is string so these are string so unordered map I am writing in sort of type string and each key you can have a list of different values along with timestamp so the value is a vector of pair of int so this is the timestamp and string this is the actual value so let's call it map so Constructor we don't know to need to do anything so it will remain as it is then we need to Define Setter so Setter is also trivial so we have this key we have value we have timestamp so this map is underscore map k and our timestamp is the first value here so we can have this uh sorry uh we cannot have this so this map K will give you this vector this Vector so this will be initially empty so we can push into it whatever is the timestamp and value so we will push a new pair and that pair will have this timestamp and value so get set function is done it's trivial next we have to Define getter and it should return string so this is the main function so the main function where we will have the code logic so git will have one key and timestamp so we can do a binary search so first we have to check whether this key exists or not so that will be of one because this is unordered map or a hash map so if this key is not present no point in checking so if key is not present so if key not in this map then we have to Simply return empty string if key is present then that means there is a vector with a few pairs having timestamp one well one time stamp 2 while 2 but which one we should pick that will depend on this timestamp so we will do a binary search so we have in our vector first element of each element first value of each element in this Vector is a timestamp so we are looking for so we have you can think of a series of integer values also of course we have a string associated with each of those but if you have a set of string values and you are looking for some time stamp which exactly matches this or is immediate lower than this value so we can you can do a linear search also that will work but that will not be very efficient so we will do a binary search here based on the first value of the pair or the second value depending on how you store it so initially left will be zero right will be whatever is the size of this vector so first we will have let's say we store the size in this n map and then key Dot size so this is n so R is n minus 1 the last element and we do simple binary search while less than equal to R we find the mid L plus r minus L by 2 you can do this way or you can do L plus r by 2 but this has this overflow problem if L plus r goes beyond the limit of integer so this is the suggest recommended way of doing it and then we do our standard binary search thing so if this map key and then this m mid DOT first value if it's less than timestamp so this is the mid and it's less than timestamp so we are not bothered about these values because these will be further less we are interested in equal value or lower but largest among lower so we ignore this part so we can move our left pointer from here to here or it may be possible that ah let us say take a case where so it will have two cases one is that time stamp exactly exists in that case we will return that timestamp once we find it other case is that timestamp does not exist let's say time stamps are like three five and there are timestamps to the left of it and right of it and let's say the mid is here and the query timestamp is 4. so of course we ignore everything to the left of it but can we ignore this three so if we have to exactly find the element we will ignore it but if we this is not that case so we cannot ignore the mid only if it's less we will not ignore it we have to check whether the next value is more than it or not so query timestamp is 4 this mid is less than 4 but the next two mid is more than four that means we have to return this value so if this map again key M plus 1 is more than timestamp so mid is less but next is more so we can return this the same thing uh Dot you can add whatever is this value dot second and here you are comparing against first is the timestamp second is the value so we will return here if that is not the case then L equal to mid plus one if that is not the case that means it was less or equal to then we can ignore this mid also so L will come here complete left part is ignored other case will be this mid is more than four let's say mid was 6 and then we have eight and so on so if mid itself is more then these value will also be more so we will ignore everything including the mid so in the other case R will be mid minus 1 and finally if it's equal the third case in that case we will return that again second so let's write the code for this so let's also analyze the time complexity first so uh this Constructor it's not taking any time of one this Setter it's again of one then getter so getter we go to this Vector in O of 1 because there is a unique key s Are Not Duplicate only values are there so this part takes over one time then we have a vector of length n and in the worst case this n may be of the order of number of total values in the this key values to so n values are there so log of n because we are doing binary search so overall get can be o of log n or set and Constructor of one now let's write the code so we don't need to touch this timestamp set also is trivial then we need to Define this structure here on ordered map of string and the value is a vector of pair of string and int or rather let's take the first value as a string it doesn't make much of a difference and we are calling it map Constructor no need to do anything Etc we will set map key Dot push back a pair having time stamp and value so you see that we did not sort it but we are using binary search that is because it's given that timestamps are strictly increasing so while we are doing this pushback this map and within for a particular key the elements are already sorted now let's define the getter function so the size we can store in ah this map in and then we have this left equal to zero right equal to n minus 1 while L less than equal to R int mid equal to l Plus R minus L divided by 2 and now if map key and mid DOT first so this is the timestamp of mid element is less than the given timestamp then the two cases that we discussed if mid plus 1 that is next element is more then this is the value midi is the value that we need to return but we need to have a check here maybe that mid was the last element mid is same as r it's possible so mid plus 1 will be non-existent so we can add a check here non-existent so we can add a check here non-existent so we can add a check here so if mid is the last element and uh that is less though so that is the value we will return so either mid is equal to r or this so this we had in the beginning so that there is no problem here else if this is not the case then we ignore the left part so midi L now becomes mid Plus 1. else if the same condition but this time for larger then we can safely ignore the right part so right comes to Mid minus one else is the case where it's exactly equal then we can return uh the same thing and finally return empty string if none of these cases are found let's try uh so this would be first because it's a pair mid key mid plus one so first part is timestamp first element so it works for this case let's submit the solution and the solution is accepted so I hope you understand this problem uh see you in the next problem | Time Based Key-Value Store | delete-columns-to-make-sorted | Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the `TimeMap` class:
* `TimeMap()` Initializes the object of the data structure.
* `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`.
* `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `" "`.
**Example 1:**
**Input**
\[ "TimeMap ", "set ", "get ", "get ", "set ", "get ", "get "\]
\[\[\], \[ "foo ", "bar ", 1\], \[ "foo ", 1\], \[ "foo ", 3\], \[ "foo ", "bar2 ", 4\], \[ "foo ", 4\], \[ "foo ", 5\]\]
**Output**
\[null, null, "bar ", "bar ", null, "bar2 ", "bar2 "\]
**Explanation**
TimeMap timeMap = new TimeMap();
timeMap.set( "foo ", "bar ", 1); // store the key "foo " and value "bar " along with timestamp = 1.
timeMap.get( "foo ", 1); // return "bar "
timeMap.get( "foo ", 3); // return "bar ", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar ".
timeMap.set( "foo ", "bar2 ", 4); // store the key "foo " and value "bar2 " along with timestamp = 4.
timeMap.get( "foo ", 4); // return "bar2 "
timeMap.get( "foo ", 5); // return "bar2 "
**Constraints:**
* `1 <= key.length, value.length <= 100`
* `key` and `value` consist of lowercase English letters and digits.
* `1 <= timestamp <= 107`
* All the timestamps `timestamp` of `set` are strictly increasing.
* At most `2 * 105` calls will be made to `set` and `get`. | null | Array,String | Easy | null |
767 | hey guys how's everything going this is jeiza who is not good algorithms in this video I'm going to take a look at seven six seven reorganized string we're giving us rain check if your letters can be rearranged so that two characters that are adjacent to each other and not the same okay if possible output any possible result if not return the empty string so like maybe we could put B in the middle and a B a and as a be a B so if we could only put one be among this a or these a so either way to adjust an a will occur so it's empty well the naive idea is something like bubble sort right we loop through the string from left to right and if we found adjacent string we need to find a letter that is not this a and insert into it right so for the for case like this we go to this a and find this double a are saying so we insert this B in it right and then we can go to next letter and for this case we insert B into here and we can move to this a and find there is nothing we can insert so fail so we return empty right cool they try to do it so first we will split s split into array and swap when found adjacent how the just adjacent just and same letters so for great i/o because we letters so for great i/o because we letters so for great i/o because we compare the previous one so sorry from one if it's the same as previous one we need to swap right so up what so well swap the next letters which is not itself right so we need to do it okay because I plus 8i plus one case where did that character stuff and if we just swap okay bye-bye but even we cannot swap then we need to return the force return empty so we net that is we know we need to keep a flag right let is swapped cause force if you found it we swap it and in swap said - - found it we swap it and in swap said - - found it we swap it and in swap said - - he who if it is not a swapped if we should swap but is not what will return empty right it's false and at last we return characters joy so now let's implement this swap method it's pretty simple so it's done let's run a code cool we got a B we insert the speeding to a ABA yeah let's see if a B work cool let's submit oh we got run answer a baa it should be we it should be organized but we returned empty why ok baa we met this a and then we insert be right so there are two a left they are to a left but there is no most range so we return false but it actually we could insert this B uh-huh so there we could insert this B uh-huh so there we could insert this B uh-huh so there is a case so actually our assumption is not it's not good like we met like this string we rather than we do baa because you wish what we should do is actually a ba right so rather than picking a letter from right you should do something from left but what if but-but-but what if it's uh if we do the but-but-but what if it's uh if we do the but-but-but what if it's uh if we do the swap its wannabe if we do a swap it would be a b a.i now a be a would be a b a.i now a be a would be a b a.i now a be a oh no the swap with the second a so a b a hmm which how should we solve this problem what's the problem what if just we search from left if we search from left it'll be a right and then okay and then if we go to B and we wall swap a again I'm not gonna work so what's the problem he probably said when we were searched the possibilities of the letters like align the two left part are not used right that's the problem so what we've what if we reorganize again from right like for a be okay now we all go to be a oh no be a and then we got a be a right huh looks like we could do two round of swapping Wow okay let's do it so I cannot find the evidence that how why this should work it's just that just like let's assume that there is something case like we could use the letter stuffs of the latter one - ah yeah latter one - ah yeah latter one - ah yeah so suppose we do it a while round and find some letters that cannot be swapped anymore there's must be but it could be there must be some letters could be used to - how to say separate the Jasin to - how to say separate the Jasin to - how to say separate the Jasin numbers right letters right so we could do one round from right so each one definitely solve the problem if you cannot solve then returned empty right yeah let's do it so we go one round rather than we return is what is not swapped we should do break right at the flag is we or we organize a pull over that's right reorganize yeah true if it is not swap we break but we said to force right and then if recognizable we just returned if not we will do this again in another direction so it's recognizable false and then we said it well the code becomes very ugly we said true and then I should be cow stagnant - - you get that - one - - if I caused - - you get that - one - - if I caused - - you get that - one - - if I caused by plus one swapped K equals I minus one yeah and then we swap it okay swap your gospel and then we check it again at the case we return empty so this should work right let's trap the error case would be baa to err is not defined sure oh there's no tool it's true cool actually yay we are accepted and let's try to analyze the time and space complexity okay for we traverse through all the letters and then for each for that the rest letters we find one the worst case is that we will find we won't find one right we won't find one then we return but so ask the worst case other than that would be gets the letters go in last one last letter and then we can continue this for loop right so generally it should be a 2 square space well in your time all right we all do need is 4 2 times so - so it's a need is 4 2 times so - so it's a need is 4 2 times so - so it's a quadratic okay could we do better let's analyze the input we're told that the s will consist of lowercase only so it's finite cases right I have an anything wrench like 500 well fine and so one characteristic of this problem is that actually the original order doesn't matter because we can reorganize them as we want like for this input for us actually is the same as a TV right if we have something like this we could see you can know that like there's a drawer theory like we have two drawers like three letters we must have at least two letters that are different from a right for B this definitely not gonna work because there at least needs to so if a BB we can insert b and b in here right cool if there's not a B yeah like you could be here if it BCC still we could put it here and this actually would generate a more a place where we can put numbers right if you have three C's any new numbers will not break the spaces so no matter what letters are we could definitely put them in it a little if the amount of them is smaller right but a if we put if we say that a has the most occurrence so the BC will not surpass them and most it will be equal to two the count of a like three bees we could put it like this 4c yeah we can put as we want like see here right so it is obvious to us that we could just to count all the letters and then find the biggest one find the most letters and the second to it if they are valid we could just collect them one by one right collector or ABC yeah cool so let's try to do that the first we need to count them so we create that counts new array 26 and then we need to find the max and the second right max and the next one so we'll create a ray called top - hmm this top - I think we were just how hmm this top - I think we were just how hmm this top - I think we were just how should we get top - it could use click should we get top - it could use click should we get top - it could use click select averagely where we lock in or we can just sort them we don't need to sort them okay we can just do it mean you're in your time yeah we let me use linear time to find the top most all right cool top - okay let's do the count code for a lowercase letters so character code had zero counts the filled with them with zero counts s character code at I - code for a plus character code at I - code for a plus character code at I - code for a plus equals one so this will get all the counts and now we find the top two right let's say it's zero four left count of counts this one is the largest one if count is bigger or equal to top-20 top two shift on shift top-2 tongue shift count and then top to top-2 tongue shift count and then top to top-2 tongue shift count and then top to pop right we put it at in the first position and if not if it is bigger or equal to equal is not okay we just put if you see eager that top to one we set top to 1 equals come well again top to right top to count now as we said if top to one is smaller than what smoother than top to zero minus 1/4 what smoother than top to zero minus 1/4 what smoother than top to zero minus 1/4 3/8 there my man there must be oh 3/8 there my man there must be oh 3/8 there my man there must be oh it's not top - it should be the sum of it's not top - it should be the sum of it's not top - it should be the sum of two all the extra sum of all the extra string sum of all the rest characters so actually we don't need top - my bad actually we don't need top - my bad actually we don't need top - my bad we can you only need top count so top count cool math max actually we accept array right allow me to use console max one two three not a number oh but can you spread three okay that's your spread max cuts cool now this is top count the rest would be a statment - top count if it is smaller than what smoother than the table counts minus 1 then it is invalid we return empty the other cases it will be cool so how we collect the rest right-click the result what if it is a DC of course we need to eat needed to be a BAC a right so actually we need to we just create the bucket and a sign assign the rest to them right how would that be sufficient how would that be efficient how would that be sufficient how would that be okay how just to create the bucket cast a bucket it's cool new array top count minus one and then push the rest characters into bucket one by one why so let I equals 0 like J equals 0 while I is smaller than 26 okay I and if we need to also not only keep the account count but I need also to keep the captor to know the character right yeah so this is not the let most letter be defined for Lent account mate hi if counts I is bigger than most cancels most letter equals string character calm string from tactical pi+ calm string from tactical pi+ calm string from tactical pi+ code for a so it gets the most letter and most count if most count most time okay while we do through all the contactor the most letter uh-huh I think not just the most letter uh-huh I think not just the most letter uh-huh I think not just a strings sense they coat store the code that's you know code for okay if I plus equals most letter code now we just continue right if not the most if not most one let market index equals zero so this one will be the bucket the first bucket then let count equals count I so this will be this kind of not this count of letters of specific letter code right cost letter will be the string from factor code I plus code for a cash it with code okay and then we walk Wow count is bigger than 0 yeah count well there's still letters we put them into the bucket right bucket index current bucket I'll push old letter and then move to the next bucket would be +1 marked by the next bucket would be +1 marked by the next bucket would be +1 marked by buckets there move to next bucket and then push it and then we have other buckets so finally returned new array most count feel cost most lighter equals most letter code the video is both letter and weird read what do it naively result must be most matter for left bucket of buckets result plus equals bucket enjoin this right and then we plus ol slab return result so I think we've done let's take a look of course invalid array net most count house can zero most counts I you got it away tenant what's the most count zero what ba coach after you will a so okay doctor go for a okay counts this is right so you're all men I plus close there seems to be some hmm there seems to be some infinite loop 3 0 so all 0 why I why we started with 3 ah we continue oh my god continue but we forgot to plus I so music musical mistake still we i we gostrey mm-hmm one push up still we i we gostrey mm-hmm one push up still we i we gostrey mm-hmm one push up on define current bucket zero new array three and one right told equals this you continue so we need to come back it zero undefined - right ah-ah we should not use I see the this is not a ray of elements but a ray of array so we mat feel map oh yeah and then we get B be like 26 B okay remove the console cool now let's submit we got vvv but you know 8a we got two buckets right two buckets and actually we will insert a with yeah two buckets and then check letter with count we see because b8 where's 8 where he is a man a phone too i plus equals one zero ah well this I'm a little confused ah I see because when this is called I is already said to one oh I will say if it's not and then I will put the logic here and then finally I will plus 1 this should work right yeah ah forgive me I'm stupid submit hey you're not right push up on define like this I see actually it is not if there is only one ah there's no need to put the bucket here if all our different Wow if most count equals one if we get to return this there's no need to do the check let's submit oh why okay EQ let's lock the account and bucket buckets so lock letter and zero it will be in one bucket so we will just put into this bucket the most letters most letter would be G II you have to G have G has to ah I see who so the pocket should be the bucket hat should be a three bucket right yeah it's not minus one but it's itself with the extra bucket at the end and then when we map actually it would be something like this yeah while this approach seems too complicated cool finally we're accepted now let's try to see the time complexity first this will be linear this would be 26 so linear constant but for here we actually checked all text all the letters right the count so linear this a bucket linear yes so it's actually linear time and space we use a account array and a bucket which the bucket will hold linear right so the account way will be 26 constant plus the buckets will be linear time in here so space would also be at last will be another linear time so it's linear we have improved the improve the performance of all we improved our solution from quadratic to linear time good sort by count so let's see the solution if an oh this is very short what it's not right with accent letter now something is possible for the string okay so all kind of letters of carina continuous pop right in the final three the intestinal letters never touch exception deliveries then in his art I think we were trying like this right find the Academy chapter yeah we do use it to soar the string by account ok interleave the characters count cool sort yeah then for its code Plus to worry what is this guy doing why are you going to talk four lines while we use what why we use 58.50 lines while we use what why we use 58.50 lines while we use what why we use 58.50 here 678 59 just twice as the amount now what does he do Tector we generate a new answer okay 14 for each code count okay for it and what he's in then 50 what is TP plus 2 tea was one it gets the character if we disfigured honest we return Joshua then we do through all the cool huh I don't understand what does I don't understand what this means oh let's see and it's the net right counts okay so it's loop through all the characters count it cool until here we're actually doing the same now but it had sort okay we didn't do that and then we created the raised end with a result or a start from one for each counts we get a character okay if count is this yes and for each letter we put aa I see rather than we create pockets rather than we create the pocket actually he will this solution just to put each chapter into the bucket back into the right position just separated by one right yeah t plus two right we could put it there and this will say if two is bigger then set it to zero well actually we are doing the same but much complicated are we right here I rewrite this now collect the result Wow this is I think this is genius because the result equals this okay let's say that current position equals zero let's say and this will be well this is much easier yeah let's say array estimate for each count right for that count of counts by we need to sort yeah this actually depends on the sort oh okay then we first put the biggest one first put the most letter most count right okay so for let i0 us more than those count I plus results power position we started with zero the current position it cools cause the most bladder and cool string from contr coat like this set it too low sweater I plus auto correct position plus equals one right sure and now for the rest right if for that I stop meant letter equals F counts I continue letter equals VI code for a plus I write string Carta code for a this is the letter for each this kind of letter we will let J equals counts I while Jay speaker then what 0 we will push it right and of course we need to check this so here it is bigger than a start then minus 1 should be said to 1 we start out with zero with the even right even positions now we set it to odd positions o plus two my bad and we said it said set it with the letter and then we're clustered and then finally we return resolved to joy wow this is genius ah j- why we get evey ye PE q g accepted ah j- why we get evey ye PE q g accepted ah j- why we get evey ye PE q g accepted e v y4 e yes why we get 4e the most count ah my bad or i + code for e count ah my bad or i + code for e count ah my bad or i + code for e equals to most letter code continue cool yes I met hmm or accept it and comparing to the Java solution we are little longer we actually still using 50 lines could we do better so if this could be removed right yeah and this could actually be this actually could be put into this photo right and yeah okay this is special case we could remove yeah and the rest actually will be very clear let me add more comments count each letter will get the most letter put yeah first push the most letter and then put the rest leather cord in me cool and yeah that's all for this one hope it helps see you next time bye | Reorganize String | prime-number-of-set-bits-in-binary-representation | Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same.
Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_.
**Example 1:**
**Input:** s = "aab"
**Output:** "aba"
**Example 2:**
**Input:** s = "aaab"
**Output:** ""
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters. | Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19. | Math,Bit Manipulation | Easy | 191 |