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
485
Hello guys welcome to new video I hope you all are well. In the last lecture we had found out the missing number in an array. If you have not seen that video then you can check it out by going to the link description in today's video. We are solving a new problem. It is easy level, it is a good problem, it is a simple problem, it has maximum competitor, we will understand what has to be done, we will see its approach, we will understand its time and cost complexity, so let us first understand the question, what to do? It is okay in this question, so this havoc must have been given to us by non- so this havoc must have been given to us by non- so this havoc must have been given to us by non- sorted unsorted. Okay, so we have to find out in it that how many maximum number of correct ones are there, that is, the number of correct ones is where the maximum time has come, as if we understand. Given this array, let's say it's okay, what are the concubines in this array? Okay, so the maximum one is that there are two concubines in this, there are three concubines in it, meaning close by, now if these two concubines cannot be in the middle of this. Zero has come, ok, so what is the maximum concurrency in it, what is its output, ok, now let's find out in it, the concurrency is 2a, there is only one in it, then there is only one in it, ok, so what is the maximum concurrency, what is your question? Let us understand what needs to be done in this, it is okay, the first approach is simple, what is our root force, we will run a loop from here till the end, okay and inside the loop, we will run another loop, we will also run a nested loop for loop and that. Where will we run from where this upper loop will start, okay, the upper loop is pointing here, then the second one will run from here, okay, wherever it is pointing from, that too till the end, now we will keep finding that all the points next to it. One will come next to it and we will keep adding it and as soon as zero comes, the N loop of the second is the inner loop, we will break it and go out and show the value of that number, then again when this thing happens again, we will We will compare it with the code, if it is maximum then we will show the new value and if it is not then it will simply continue. Okay, let's see its code. You will understand better than that. Okay, let's see its code. What will be the code? First of all, let us assume. We will return the answer ok let's take it as a variable and a s one let's say we will store the answer in it ok now what to do is run the for loop a for end a e from 0 to all then numbers dot size numbers are names ok If I want to run another loop inside it, then I have to run F int J from where this loop will be pointing, which means we will run from A to J, smaller than non dot size and J plus Ps. Okay, now what? What we had to do now is to compare the values, so it is the name of the names, if equal is equal to one, that is, if v is becoming one, then what do we have to do? Now is it necessary to store something to store the code? If we want, then let's say int will store the concatenation. If it is gone then what do I have to break, the break is ok, after this, what to check after that, if it is bigger than the pebble, our answer will come later, if it is bigger than the pebble, then what will we do, we will change it and keep it cut. Okay, so what we do is answer to max of, whatever is the max from these, we will store the cute message and answer message, whatever is the maximum, we will store it in the answer. Okay, this is over, this loop is also over, now this The loop will break or not, right? What to do after this? Simply return answer. Return answer. This thing was ok. Its time complexity is how long the loop is running. The loop which is the first loop is running till the size of the array and the second one. There is a loop, this is also going on till the size of the array and this is the next loop, so the velocity of a is the size of the array multiplied by a. Okay, so this is the velocity of n square this e time complex t end space complexity no space usage. If you don't do it then the constant is ok, this thing is understood, let's see its new approach, we will try to reduce the time, let's understand the second approach, what will we do in the second approach, what can we do, wave off the level complexity of the previous approach. N square, if it is not better then we will have to bug it, so what to do for this means we have to change it, we have to do the loop once, what we can do is that we take a pointer to a column in which we will store the answer and the same code in which We will store whatever number comes, initially zero, okay, now let's run the loop and delete it. Got the first one, okay, if we got one, then make the [ __ ] plus. okay, if we got one, then make the [ __ ] plus. okay, if we got one, then make the [ __ ] plus. Okay, let's move ahead. Again, if we got one, do the [ __ ], then move ahead. We keep increasing, we got one, we turn the number into do the [ __ ], then move ahead. We keep increasing, we got one, we turn the number into do the [ __ ], then move ahead. We keep increasing, we got one, we turn the number into plus, we move ahead, we got zero, now as soon as we get zero, what we do is store the value of the number in the answer, okay, it is stored, now what to do is to return it to zero. Do it, okay now let's hydrate again, plus, hydrate, plus oh, sorry, hydrate, plus, okay, and this is the loop name, okay, now when the loop ends. So what will we check after that? We will have to check the loop end also. What will we check in the loop end? Whichever of these two is maximum, we will store it in the answer. Which one is this four maximum? So this We will force it on y and return it. Okay, let's see its code. This code will remain the same. It is also okay. First of all, a variable in which we will store mass. 0, now a code in conjecture in which we will store our code. What to do now? Have to run the loop for and aa e from 0 to i slur then ns dot size nam ses nam are noms ok and aa plus ps now what to do after this what to do if nams ka i equal to ev e if one is there then what to do Have to cut P Have to get Plus done Okay Else Have to do Else I had to do that first of all we will get the maximum value shown in the answer so first they do Answer Itu Max of Answer Kama Kankut Ok What to do after this After reducing our contig to zero, ok S part tam and loop terminate Now even after loop termination, we were checking once whether the answer has increased or if the contig is big then the answer is e to max between answer and contig conj cute ok Now what to do in return then simply return after seeing the time complexity of it's time commit loop else if it fails then the time complexity is two of n space complexity no extra space given big of time complexity you must have understood thank you so much and have a nice day
Max Consecutive Ones
max-consecutive-ones
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = \[1,0,1,1,0,1\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
Array
Easy
487,1046,1542,1999
1,499
hey what's up guys this is chung here so uh today i would like to talk about this uh 1499 max value of equation this is a hard problem but i think this is a good one okay so let's take a look you're given like an array a list of points containing the coordinates of a point on a 2d point plane here which is the x i and y i here okay this is okay this one is sorted by the x uh by the x values okay and so that i mean the x i is always smaller than the x j okay whenever when the index is it's like this okay and then you're also given like an integer k here and the problem is asking you to find the maximum value of the equation so this equation y i plus y j plus the absolute difference between the x i and x j where the uh where the x i and x j is smaller than k okay and it's guaranteeing that there exists at least one pair of points that satisfy the other constraints x i x j okay cool so and then it gives give you some examples here i mean any i think it's not that hard to realize this problem is actually a sliding window problem right basically you know we have a point we have points okay basically there's a point here but the i think the difficulty for this problem is that not only because the sliding window is not just like 1d sliding window i mean it's kind of like a 2d but still it's like 1d sliding window on the x axis here right basically we have x here and we have y here so what we're so first thing we need to understand is that this problem is like a sliding window right basically it's the sliding window the size of a sliding window is k okay and the sliding window is like moving towards this uh direction okay and then during this the moving of the sliding windows and we need to find out like the maximum value of this equation while the sliding window is moving okay so that's the first thing we need to know that here we need to know and then the problem comes down to how can we calculate this the max value of these things here while the sliding window is moving okay so i think two things when the next time when you guys see this kind of like a sliding window related problem you know i think the nature of the sliding window what's the nature of the sliding window is like since the sliding window is always moving right and every time when we have like a new basically the height of the sliding window will keep moving to the uh to the to a new lo location to a new locations right and then based on the size we're gonna shrink the sliding windows here okay and then the nature of sliding window is every time when we have like a new sliding windows right here so we are at like these new numbers here we're gonna use utilize this new number to basically to get what we want right in this case is the can we get like a better a bigger number for this equation here basically this is the j right because as you guys can see so the j is like this is the it's a bigger index here right and now the question is that with the current uh item j here how can we quickly calculate the maximum value of this equation i mean of course a brutal force way is like we could we can always loop through everything between the sliding window here right and for each of the number uh like i here right we calculate these equations again right but obviously that will tle because the uh the length of the point is like 10 to the power of 5 which means if we do that the brutal force weight the time complexity is o n square which i will definitely time out okay and then how can we know that right so obviously sorry so how can we calculate uh effectively we calculate this equation okay one thing to notice here so this is j here right so the j here what do we have xj and yj okay so this thing is fixed okay which means every time when we have like an a new j here we have xj and yj okay and so what's the other part so the other parts is based on this based on the this equation what's the other part since we have this absolute uh signal uh sign here we need to remove it because the xj and yj are inside uh x i are inside this absolute uh sign here we need to remove it since the x i is smaller than the x j here so now we can transform this one to like y i plus y j uh minus okay minus x i plus xj okay cool so now we have x j and y j here right so which is the plus here now know what's next so here this is going to be y i minus x i okay plus x j plus y a y j here okay so as you guys can see here so every time we have a new number which is j here uh the x j and y j is fixed okay so now we have x j and y j so what's n then we just need to find what's the biggest value of the y i and x i right so for this part i mean we have to loop through all the eyes basically that's going to be the all the outer eyes i number which is before j of course it has to be within the case size sliding window right the biggest number of that okay but like i said we don't want to do it in a brutal force way so what's the a better option you know remember this guys so to track the maximum number or minimum number in a sliding window there are always two ways of doing it up the first one is the using the heap and second one is the monotonic q i mean the heap time complexity is n log n and the mono the monotonic q is even better it has like a space time complexity of o of n it's a linear space complex at time complexity yeah so if you guys can analyze the problem until this point right and then the next one is just to you to utilize the either the priority queue or the monotonic queue to get to efficiently get the maximum value of this because in this problem it's asking us to find the max value that's why we're going to use like the max q okay to find the max value of this one within the sliding window okay so and okay so first priority queue okay so i mean since we are going to maintain like the uh the two things right the two things of this element right the first thing is that we need to know like the what's the index right basically the position of the of this point so that we can like move that the point out of the sliding window that's why we have to uh store not only this value the y minus x but also the x itself so that we can uh pop remove pop that thing okay so the first solution is by using the uh the priority queue so the priority queue we're gonna maintain like a max q in this case because you know we are we need to find the maximum value right of the y i minus x i so in this case i mean we're going to have like the max q here the max q priority q okay max priority q here and our solution is that you know every time right and the item in here is going to be the first one is the y i minus x i and then the sec the second element is like the x itself x i basically we're restoring a tuple inside of this queue here so every time when we have like new numbers here right we check if the first element in the in this priority queue if the x is inside of the uh it's like it's still within the range of our sliding window right if not then we just pop the first one so why we only need to check the first one because the first one the value is always the maximum value okay i mean even though there are like some other values right inside of the let's say we have a priority queue here let's say the top one is like uh top one let's say it's like uh it's 10 and the x is 3. okay and let's say that i mean the second one is like is eight and the x is one let's say the x is one uh okay and now let's say the our current x is like uh is it like four something like this and the xj is four and the k is equal to two okay so if that's the case right i mean if that's okay since uh we don't care you know even though like currently that the one here the second element which is the which has x equals one has already been moved outside of the sliding window but we don't care right because we have a bigger values here above that and all we care is that what's the current what's the card what's the valid like biggest number between the sliding window i mean as for this one here let me later on when this thing's moving out of the windows here i mean when this one is popped out right and let's say this one is the second biggest one and of course and we will and by that time we also pop these things out basically by doing this like we are using that like product priority queue to always store the uh the biggest value the valid biggest value right within the current sliding window and then so that every time we can just use that to uh to update our answer here okay so that's the first approach okay let me try to implement this real quick here and okay so we have n equals to a length here probably q okay so an answer is like minimum the smallest number okay in the system and for x y in range sorry in points okay so first thing here we have to uh update our sliding window okay to make sure sorry the updates are the priority queue to make sure the uh the first one is still the valid it's the first the biggest one is still within the sliding window okay so the first one is going to be a while the priority queue is still uh has values and the priority queue dot at zero right remember the first one is always is the biggest one okay and then the one right because the second element is the x uh it's smaller right than the then x minus k is the current one right so with we do a push hip q dot heap pop okay now we have a now the prior q contains the biggest value the biggest values right uh we for this for the current for updated sliding window now we can simply update our answer here and remember okay so one more thing here since in python there's the product q there's only like a mini q mini priority q here there's no built-in max q here so we have to built-in max q here so we have to built-in max q here so we have to reverse number inside here so to get our basically whenever we try to use the values or push the values into the product queue we have to push its negative version of it so that we can maybe tweak this one to be a max q okay so uh priority q dot zero okay dot zero remember that zero is the is that a y minus x okay it's the y i minus x i okay so this is zero this is one okay and plus okay x plus one right that's the uh basically the equation here okay and now we have to uh update the current one we have to push the current one into the priority queue okay hip q dot keep push okay uh priority q dot uh okay like i said i mean normally we need to do a y minus x but since we're going to revert it so okay let's do a reverse here okay so obviously this one becomes so x minus one x minus y but i'm just doing this so that you it's clear right x okay and then we simply return the answer cool i think that should just do it if i didn't make any stupid mistake here um what's going on here yeah i don't know what happened something just weird happened it seems like the website just stopped working uh index out of the range oh sorry okay so of course if the prior queue there's something in there then we do it we do this cool so submit all right cool i mean yeah so this one works right i mean the time complexity for this one it's like i mean we have a owen in here right and then we have a we have like a few uh hip-hop right he a few uh hip-hop right he a few uh hip-hop right he pushed or he popped this like a login i mean it's pretty straightforward right that's the basically the priority queue to maintain that and an even better solution is by using the like the mono monotonic queue in this case we're gonna use like the increase q okay sorry we're gonna use like the decrease q sorry not increase q for those who don't know what the monotonic q is that i mean it's like a either increasing q or decreasing q in this case we're using like a decrease decreasing q basically let's say we have like a q here we have a array here and we have a uh 10 like eight right and let's say uh three two and one okay and so this is like the decreasing q right basically it's similar like the priority queue basically we're storing we're always keeping the uh the biggest number on at index zero here and every time uh when we have like uh because the priority queue here since we're doing the heap push here i mean it automatically can update us like what's the current uh biggest number uh for us right basically we're relying on the priority queue to tell us okay what's the current biggest number here but if we're not using if we don't use a priority queue we use like the monotonic like the decreasing q here let's say now we have like uh a six here let's see then the card number is six so what do we do here we uh basically we just uh we just pop everything that is smaller than six in this case the one is gone two is gone three is gone now the basically the uh the cube becomes two ten eight and six okay so that's that and still right still the first one is also the uh it's also the ones that basically the first one is always the uh the ones that has the uh the biggest number here and similar as the prior queue here so whenever we have a numbers here we have new numbers here we also need to uh basically try to pop those invalid ones invalid like uh those numbers we who's like index is out of the sliding window basically we're doing the same thing here right we're let's say if the 10 is out of the sliding window then we just move the 10 from the from we do a pop left okay we are removing from the tail of the q here and because the index here right so sorry the x here is increasing here x is always increasing that's why it's safe for us to remove the element from left okay because if the 10 is not is out outside of the window here then the next one is the second largest one okay similar like this one similar like the product the hip pop here basically the heap of pop is doing the same thing here basically every time when the turn is out it will automatically elect the second largest one on the uh to the like to the first position okay and in our case it's already sorted basically so it's already sorted like from the biggest to the smallest so that we can just simply rely on the on this on the zero here to tell us who is the next of the biggest one biggest number here so yeah so the main structure is it's the same basically we're doing like a queue here uh since we're going to remove from the tail we're going to have like dq here and system dot max size okay and then same thing here x and y in points so while q okay i'm going to use q here actually this one is like a decreasing q right decreasing the decrease q and uh same as the above one same the decrease q dot zero dot one okay dot one it's smaller than x minus k we do the same thing basically instead of a hip pop here we know that i mean the zero one is the first one is always the biggest one okay and we can simply do this right do uh like uh decrease q dot pop left okay because we know once we pop this one here the next one the next zero one is the second largest one so that we can simply pop keep popping just like as if like what we did uh in the priority queue here okay and then same thing here right if decrease q it's not empty we can just copy this one so we can just simply copy this instead oh but remember here since we're we don't use a prior queue here and we can just simply use its original value here okay and then okay so here a little bit here so a little bit difference here like variations here because here at the priority queue here we can simply do a one push here so that i mean the priority queue can automatically adjust whoever what uh what's the current the biggest one but here we have to manually maintain that's the decreasing order here basically what we need to do here we have to do this right decrease q and uh if the decrease q dot zero sorry not zero okay so at this moment it has to be the on the right on the last one the end of the q here if this zero is like what it's equal or smaller than the current of y minus x okay then we uh we decrease q dot we do pop we pop it okay and then in the end we simply append it q dot append y minus x and x with an answer okay so let's try to run this code here okay cool submit yeah this is weird i mean okay yeah actually i'm expecting the second solution will be faster than the first one i mean um i'm not i don't know i'm not sure because maybe it's because of the uh of the testing cases okay so again so i mean here is the same thing we are like trying to maintain the current sliding windows and then and after the updated sliding windows i mean the first one is the biggest number and here is the little difference uh comparing with the priority queue here basically we need to manually maintain this decreasing q the way we're maintaining it is that basically we pop everything from the end whose value is smaller than the current values and after doing this the first one the first like element the first element here is still is guaranteed to be the biggest number okay because like let's say we have a three two one here in the priority queue now let's say that this next number is like is six okay right it's six and then okay of course right we have to uh we have to none of them none of those is like is none of those matters okay none of those matters b why is that because uh because six has the biggest x right all those numbers has the smaller x compared to six we which means later on let's say we have a j somewhere after i here i mean since the six has the biggest number among all those numbers and of course and it has like the x so it always gonna be six comparing to those numbers because by the time six i mean before six was moving out of the sliding windows all those numbers they have already gone okay so as long as six exists in our like in the sliding window those numbers four to one they're all useless okay that's why i mean we can simply remove those and that's the beauty of the monotonic queue here so that the next time when we have a different numbers here we can simply ignore those numbers here because they are useless and that's why we can that's why the uh the space complexity for this thing is it's actually o off of n here because you know no even though we have o n here right so here's o n but here we're doing like uh since we're like we're maintaining we're like maintaining like the monotonic like this i mean here we can treat all these things like close to o1 because each of the elements will always will only be pushed into this queue once and it will only be compared once yeah i'm hoping i can explain this one clear so that you guys can understand okay cool and yeah i think that's pretty much for this problem i mean it's a very it's a good problem i mean especially for the uh for you guys to practice how can you maintain like the uh the biggest number uh in the sliding window this is a good one but before doing that i mean you have to be able to come to realize that how can you what numbers you need to keep what numbers you are tracking in the sliding window okay in this case you need to basically need to do some like transformation transformations right uh to this like equation so that you can get this uh y minus x and after that you just need to know how you can use the uh priority queue okay to maintain the uh use the priority queue and the mono the monotonic uh decreasing q to maintain the uh the biggest number like uh in the sliding window i mean so both of these can also be used into uh into a smallest uh the minimum number right because this one is like happens to be a like the biggest the maximum numbers i mean if it's asking you to get to maintain to get the smallest number in the sliding windows so for the priority queues we simply just uh remove this uh negative signal here and here yeah when it comes to the monotonic queue here in instead of using a decreasing cube we're going to use the increasing q because we're increasing q the first element the zero one is always the smallest okay so here we have to make the change accordingly but the ideas the idea is the same okay and i hope i'm hoping you guys can remember like when to use this like a monotonic queue to degrade to reduce the time complexity uh while maintaining like either the biggest or smallest number in the sliding window all right thank you so much uh for watching the videos guys uh stay tuned like see you guys soon bye
Max Value of Equation
maximum-performance-of-a-team
You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`. Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`. It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`. **Example 1:** **Input:** points = \[\[1,3\],\[2,0\],\[5,10\],\[6,-10\]\], k = 1 **Output:** 4 **Explanation:** The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1. No other pairs satisfy the condition, so we return the max of 4 and 1. **Example 2:** **Input:** points = \[\[0,0\],\[3,0\],\[9,2\]\], k = 3 **Output:** 3 **Explanation:** Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3. **Constraints:** * `2 <= points.length <= 105` * `points[i].length == 2` * `-108 <= xi, yi <= 108` * `0 <= k <= 2 * 108` * `xi < xj` for all `1 <= i < j <= points.length` * `xi` form a strictly increasing sequence.
Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds.
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
2229
424
hello welcome to my Channel today we are going to solve lead code problem 424 longest repeating character replacement so this means we are giving us 3s and we are also giving a integral T this key means we can exchange K integers for example this is a b we can exchange the B to a another B to a and then we're going to 4A or we can also get four bits so this means the length will be 4 and let's see this example this means if we can change this B and we get Four A's so the length is four maybe we can also set this A to B and there will be four bits and the maximum less is four and we cannot find a lens even longer than this let us see the value of s so the s maximum of the length is 10 to the power of 5. and S consists of only upper English letters yeah so the K is maximum to less like this kind of a problem normally we will use the sliding windows but house will be used as sliding Windows let's go to the Whiteboard first and after that I will go to the code Editor to finish the coding so I'm going to use the second example so here okay equals to one this means that we can exchange one character B to a or a to B of course inside the character it is not only a or b it may be other uppercase English letters it doesn't matter so how should we find and how should we fit our sliding window for example if we use a sliding window normally we have a left pointer and there will also be a right portal it will start from the beginning from the first index so here is L Porter and here is our reporter and then the iporter will save so if the Airporter goes to the displays this place and go to the next place but how should the window shift yeah the window have to slide if the window cannot slide we can not solve it using sliding windows yeah so if we know the maximum of the characters for example here the maximum character I mean how many numbers the maximum value of the character if a is K and the value is 3 it's the value if B how many B's there's only one B but up to here there are three a so what is the maximum of the character it means a it's a three it has a three yeah so according to the maximum of the numbers of the counter we can design our sliding window because if we know this maximum is 3 but up to here this is R so the length of the sliding window is always R minus this is R minus L plus one so up to here what is the length so the length is 3 minus 0 Plus F1 yeah so 3 minus 0 it is three minus one it is four so up to here the length of the sliding window is 4. if this is 4 minus the maximum kind of maximum number of the characters it is the three it is a one yeah and here we still have a k equals to 1. it means we can shift this number this character B to a or any other characters yeah to this maximum character it means we can still use it yeah so what if the r quarter goes to here goes to the next point so the r minus L plus one it becomes five yeah and what about the maximum character it is 0 a and there are three A's so five minus three it equals two so this 2 is more than this k is one yeah if this number is more than this K it means we cannot use this K this number to exchange it because we have to change the two characters it's impossible yeah because the maximum we got 3 8 we have to since it's not possible this means we have to skip to the sliding window so the L Potter have to shift it to the next position yeah after it is shifted to the next position we're gonna check if it is possible of course here isn't not possible because it's this L shifted to here is the r reporter we know that a b yes it's not possible if we only since one character and then the L Potter will continually shift and the airport is shifted to here so what is the maximum yes yeah I mean after shift to the airport would also shift we have to attack what is the maximum for example if the sliding window is here the Airporter goes to and this position and we're gonna talk we can since this A to B so the r minus L plus 1 is 4 and what is the maximum it's a character B it's a three so four minus three equals to one so it means it's still a possible answer yeah because it is 1 equals to K yes otherwise if we shift it means it's not possible because the sliding window becomes a 5 the length of the window and the maximum character yeah and it's a sliding window goes to this place the maximum calculator B is a three so five minus three equals two is more than 10 it means this window is not possible we have to shift the window so the L Potter have to shift it to this place yeah so this is a basically the idea of how to use the sliding window but how to check the maximum characters for example here is a here is B so we have to use a dictionary because inside the dictionary there will be character like a how many is for example a is three and how many B's inside the inside of the dictionary maybe B for example with here go aaba here b equals to one yeah and for the dictionary we can easily to check the maximum values without need to use a Max D dot values yeah because it in dictionary we can get the values and then we can calculate the maximum so in this way we can calculate the maximum so what are we going to do we're going to use the sliding window and the dictionary after that we can cut our result so let me go to the code Editor to finish the coding if you didn't understand anything let me explain it inside the code so I'm going to design a left border and a dictionary here I use the advantage summary and result so the air filter will start from 0 and the dictionary will be at default text because I will use calculations for the dictionary so I'm going to give a default text it just save it many lines of code several lines of code and then I'm gonna Define my result because the S is at least one so I'm going to define the result as one first yeah and I'm going to return the layout and then I'm going to write the sliding window template yeah so I'm going to use four for our say in enumerate s yeah so here is basically the template for sliding windows and the result should be the max without R minus L plus one but what happened just up this result yeah because this is basically a template but what we're going to do we're going to first put this character inside the dictionary yeah and we check the values how many of these characters so here use the DC plus 1 we get to the it's we get is we get our K value pair so K is the character that value is the number of the characters yeah because we will use the max to calculate what is the max characters and how many yeah and how many characters of the max yeah and here we're going to use attack while so this is the template so the sliding window will be r minus L plus 1 through the minus this dictionary the max of the D dot values yeah this means for example if I go like here so this is on the left side this is the right side so inside of the dictionary the max value is the three because there are three A's yeah if there are three is so the max is three and the sliding window is a four so it means it's still possible otherwise if it is more than K so we need to skip to the sliding window but before shift we needed to update the dictionary yes so d s l to the minus one that because if we were to shift the left pointer we need to add the update the dictionary before there are three A's no it will be two A's and after the dictionary so the L can plus one yeah and then save to the airport so yes this way the time complexity is o n yes maybe you think here need some actual calculation yeah because there are 26 uppercase English letters so it is 26 times 10 to the power of 5 it means 2.6 times 10 to the power of 5 it means 2.6 times 10 to the power of 5 it means 2.6 times 10 to the power of 6 it can still pass the lead code yes now let me submit it to attack if everything is okay yeah now let me submit it to attack if it can pass all the testing cases yeah so the basic idea is about this line so this line is taking for the sliding window yes as you can see it's pretty fast it's nearly 60 percent thank you for watching if you think this is a helpful please like And subscribe I will upload more it could problems like this see you next time thank you
Longest Repeating Character Replacement
longest-repeating-character-replacement
You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times. Return _the length of the longest substring containing the same letter you can get after performing the above operations_. **Example 1:** **Input:** s = "ABAB ", k = 2 **Output:** 4 **Explanation:** Replace the two 'A's with two 'B's or vice versa. **Example 2:** **Input:** s = "AABABBA ", k = 1 **Output:** 4 **Explanation:** Replace the one 'A' in the middle with 'B' and form "AABBBBA ". The substring "BBBB " has the longest repeating letters, which is 4. **Constraints:** * `1 <= s.length <= 105` * `s` consists of only uppercase English letters. * `0 <= k <= s.length`
null
Hash Table,String,Sliding Window
Medium
340,1046,2119,2134,2319
3
let's take a look at leap code question three longest substring without repeating characters and this is a great question to practice your string algorithms even a string s find the length of the longest substring without repeating characters and then we have this note a substring is a contiguous non-empty a substring is a contiguous non-empty a substring is a contiguous non-empty sequence of characters within a string so we have an example here we have the string here a b c b and then we want to look for the longest substring without repeating characters so we can see that the first three characters here A B C they're non-repeating non-repeating non-repeating and then when we go to the next character there's an A so that's repeating so that's a b c with the length three so then we have the string BBB so the longest non-repeating character so the longest non-repeating character so the longest non-repeating character is just the letter b so let's go ahead and actually dive into the code here so we want to work out the length of the longest substring so let's start by defining a variable here longest substring length and we're going to initialize that equal to zero and then we're going to go ahead and return the longest substring length and we're going to have an intermediate step between the that so what we want to do is we need to Loop through every character of our string so let's say we have let character of s Loop through each of the characters we're given in the string that we're given what we can do is we can get the index of the character because we'll need to keep track of the index to know whether or not to splice it from the current substring array so basically what we can say here is we can say let's have a variable for the character index and that's just going to be well firstly let's go ahead and have a variable here called the substring array and this is going to be a string array which we're going to initialize to an empty array and what this is going to do is this is going to keep track of our substring and it might not necessarily be the longest substring but it's just the substring which isn't repeating for the current iteration we're on so we can take we can find the index of that and we can say actually before I do that I think it will make more sense if we say well as We're looping through this so let me just comment this out for just a second we need to Loop through our array here and as We're looping through our array we can say we can simply just push the character to the array so initially it's empty and then we going to push characters to the array so we don't necessarily want to do that if the character repeats though and if the character repeats we need to track the index such that if it does repeat we can splice out the characters before that so let's just take the index by taking that array and using the index of method which is all of n and so if our character is in the substring array that means we've hit a repeated character so if that's the case well let's say that if the character index if that's going to be less than oh sorry greater than or equal to zero meaning that an index was found meaning there's a repeated character we'll need to remove that so what we can do and then we'll also need to remove all of the characters before that so what we can do is we can take the substring array and we can say well we want to splice out um here we've got zero and then what we want to delete is we want to delete the character index plus one so what we want to do is we want to take our substring array and if we find a repeated character we want to remove all the characters up until that repeated character so this first element will splice it mutates substring array and we don't want to insert anything but we do want to delete the number of um characters that are after the index and then we can just add one to that because we don't want to delete that new number itself we want to keep that because we're going to remove the ones before so basically what we can say is we can take the longest substring length and we can say well the longest substring length it's either going to be the length of the longest substring length that we already have or it's going to be the length of the new substring array that we've found and whichever one is greater that's what we'll use so we can use this math method here the mathemax and we can just pass in this here and then we can go ahead and we can pass in the substring array and then we can just get the length of that so basically this is a for Loop but we got this substring array index of which is an old n operation so that'll make the time complexity of N squared and we need to assign potentially all of the characters to an array if none of them are duplicated so they'll be all of n there so let's go ahead and submit this and we see that beats 71 so that's not too bad
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
43
foreign list multiply strings you will be given with two non-native you will be given with two non-native you will be given with two non-native integers M1 and M2 representing as strings and return the product of these two numbers also represented as a string so here you can see that here number one is two number two is three what is the product of these two things is six it must be also a stream and here another one is it so here number one and number two one two three and four five six it must be product of these two things how 1 4 and 123 into Force 56 the product will be fifty six thousand eighty eight so that is the answer for this how to do it first of all now here we are taking two strings even their number we are taking in the form of strings only here every time I am taking the length of uh first of all we need to take the length of two strings M and N the result will become these digits some right so six digit cities three digits result will be in six digits we have two days two years is the open maximum it will be like that so I am taking that uh integer time integer type and ending index is M plus n minus 1 okay and I is equals to M minus 1 I is greater than or equal to 0 I minus result index is equals to ending index carries zero if you are taking two things the carry will be forwarded right so like that here this is the operation what we are doing now J is equals to n minus 1 G is greater than zero J minus in the same order and after that current value is equals to result index result of result index plus carry plus character dot get number value I am taking the number value of the character num at character I position we are taking the last one how means 6 plus 3 it is 9 right like that so here onwards we need to take uh combinations and add together and add it to the total sum so here 6 3 the 18 means one will go carry 8 will come here isn't it and Phi pi to the and six twos are something like 12. in a in the same way in the mathematical formulas it will be multiplied in the formats so here every time we are taking this carry and adding that remaining things and if the carry is greater than 0 only you are going like this otherwise we'll directly add to that so the after taking that all the values current values the indexes will be like this here the result dot length and result index is equal to zero this index will be increased and finally we need to use a string Builder class and adding to each and everything appending to each and everything if it is 0 like this the symbol for length is equal to 0 will be adding zero otherwise swing buffer two strings we need to add to that so this is the final but here actual thing what happening how we are getting the string we are adding to the stream there is a one more important topic we need to understand here so just I'm running this code this observed yeah it is accepting two text cases it is accepting okay I guess I'm running this submitting this is successfully accepted to this okay thank you
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
20
in this video we'll be going over Elite code question number 20. valid parentheses we're given a string that consists of six different characters the opening and closing parentheses square brackets and curly braces given this string we have to return true if the string is valid and false if it's invalid now the problem defines a string to be valid if it meets three conditions Open brackets must be closed by the same type of brackets Open brackets must be closed in the correct order and every closed bracket must have a corresponding Open Bracket of the same type so for example something like this would be valid but this would be invalid since the open parenthesis is being closed by a square bracket so how would you approach this type of problem well another way of phrasing this problem is that the last type of bracket that is opened must also be the first one to be closed before any others so our strategy for keeping track of brackets should be a last in first out approach also known as lifo so now we ask what data structure uses the lifo principle and the answer is a stack so this is a pretty good hint that we should use a stack to keep track and manage all the brackets now let's look at the code and see how we can implement this in Python let's say this is the input string we are given the first step is to create a stack which I'll also represent with this diagram here you'll notice that I'm actually declaring a list here but we can use a list as a stack as long as we only operate from one end so for this problem I'll only use the append and pop methods to interact with the list in the diagram this side represents the top of the stack in other words the end of the list next we'll create a dictionary called pairs that Maps each type of opening bracket to its corresponding closing bracket this is how we'll check that the brackets match up we then enter a loop and use a variable called bracket to Traverse it so here's the big picture idea if the bracket is an opening bracket then this part will push it onto the stack otherwise it's a closing bracket so this part will check if it's the correct type of closing bracket if it's not then we exit early and return false if we get to the end and all brackets have been properly closed then the stack should be empty okay now let's look at the example first this line checks if bracket is a key in the pairs dictionary in other words we're asking is it an opening bracket this is true here so we'll just push it onto our stack using the append method like this next let's move on to the second bracket is this square bracket and opening bracket it is so we'll push that onto the stack too moving on is this bracket an opening bracket this one is not a key in the dictionary so it must be a closing bracket so we jump to the else block we'll check for two conditions here and if either of them are true we'll return false first we'll check if the stack is empty this is because since we just encountered a closing bracket if the stack is already empty at this point then that means there are no more opening brackets left to close which means that there is a mismatch and a string is invalid if we look at this stack it's not empty so let's check the second condition so first we'll pop the stack which removes and Returns the bracket at the top of the stack which is the opening score bracket we'll then use this opening bracket to look up the corresponding closing bracket in the pairs dictionary which is this one we'll compare that closing bracket to the bracket that we're currently on in the loop if it matches like it does here then this statement will be false which means we just continue on with the loop in other words it means that this was the correct type of closing bracket so the next bracket is an opening curly bracket so we'll just push it onto the stack next is a closing parenthesis so let's pop the curly bracket off the stack and find the corresponding closing bracket now we compare the two and we find that they are not the same that makes this statement true and so since we have detected a mismatch we can return false immediately the string is invalid now let's try a different example where we'll be able to get all the way to the end we'll start off the same way by creating the stack and the dictionary the first bracket is the open parenthesis so we'll push that onto the stack next is an open square bracket so we'll push that on and next we have an open curly bracket so let's push that on as well next we have a closing curly bracket so let's pop off the opening curly bracket off the stack and compare it with the current bracket we're on it's a match so we can move on next is another closing bracket so again we'll pop the stack and compare the closing brackets this is also a match so now we're done with a loop now for the last line of code if all the Open brackets have been closed the stack should be empty and the length should be zero but here since there's still one parenthesis left over the length of the stack is 1 which makes this false so the algorithm returns false if this last line is confusing to you could also write it like this if the length of the stack is zero return true else return false it's the same thing but the way I wrote it here saves you three lines of code now what if this string had a closing parenthesis at the end which then would have made it valid well if we rewind a bit at this point of the loop we would have had to do one more iteration for the last parentheses we'd pop the opening parentheses off the stack confirm that it matches the closing parentheses then exit the loop now when we get to the last line this expression evaluates to true so the algorithm returns true the string is valid and we are done
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
1,201
coat fell you're one ugly number three the problem is that write a program to find an ugly number ugly numbers are defined as positive integers which are due to rise above by a party or see here's an example of help and you could a threeway you have a pc he would to signify how to find those sweet number the right iran divided by this shri numbers so the regular numbers are two three four five six eight nine ten the sir number is four and the weekend can you see another examples and you would fall and this sir a Lambo is his fall so now angle number is six and here on Fox faces a number is ten and we have this range attempt hot knife this is very large so it tells us we cannot use a linear program to solve this problem and that deposit ten thousand nine so he which will because seriously or n time complexity so for the life of messages doesn't work out Niedermayer is to try to generate all the numbers from 1 to M and then is bigger than and which had a number that is divisive or prizes if you're sitting infinities the way put into the answer and caraway father and sample the taste om OM time Oh cause it's it is what we are called hear ye seven solution that we have founded we have found the numbers divided by EPC we can generate the numbers 1 times a 1 2 3 a times 8 and then until n numbers here n times a another hold it one time three time T totality straight Amethi and comedy and one time see to Tennessee say Tennessee until M Thomas C and you this is natural we have generated trees such it missed but it is needed and Caesar n so yet I will fetch you the first numbers from this you see element of this just this so we are first we have fashion ABC and every day with then check out which one is smaller is for the disc is smaller than when you're sick Freddy second at what update so it's not the voice in a case sorry mr. Montero in finance numbers so these problems also taste and take us oh okay or end times time probably toe and loriann time you've really find a girl and centavos so it also will cause tea tre and danced with soda meso do we have to consider the optimizer can so how do we organize it and with and you for we can create of frivolity of salty and for example ways social numbers M inflame he's / the in social numbers M inflame he's / the in social numbers M inflame he's / the in faculty body by the AP and say you families we have found out how many numbers that is to be 2 divided by PI and PC recall function and the finding the counter and even the counter you to bigger than and I mean that we have a go to left to final again so if we smaller and visual culture right mmm in the war so is this a ways that her reminds me of your final research so for you know use binary search is a critical idea is how to read need of hardware founders noms your number of the numbers the number of the and valuable that could toward different divided by a B and C and we have for example how to find every am never number and you for the number of a even with the water number away this means the number of our values that could be given to rise the Papa a that is smaller than small and smaller than nom and lastly we could also check on the number of noms that divided by a and also to worry about see when we get all this process we togethers we have some overlap on here it snappy that form of this is in this circle here we have num own to our deep is the number of my level 30 when I could utilize about pi and this is the divisor or pass see and say Mississippi you say well yeah my way I found a number that could be divisible by a or P or C minus C of them tell me that we have the fun this common although numbers that is and over here is over here and the pass here and here so of course the puzzle here as a part of when we carry the numbers Commodore oh hey and also number o P but never always and I'm gonna be when we passed together we all have with the whatever calculation so we have to carry their numbers and their could do it and divide by copy and also if we had a number of to oversee we're here to tear on to our divisor EP LC - no more the P and C peril here is LC - no more the P and C peril here is LC - no more the P and C peril here is that we have cause we have divided us we times divided once more time passes the common area here no cameras over here it's coming real so we hope to pass this one common area here so and so this is basically the functions what happened and this is a function that have none you could this means the number of the rally was that the TV's WAPA a or P or see here and another is that how do we calculate to this a and be visible by ronnapee make fortifying or used to common divisor then least common divisor the DISA common divisor is that mean that the numbers and is it a and P that means that numbers could be the result of pi and also could be the result apart party so it can calculate the forms or an acidic from catheter no the great a common divisors create common divisors this is very common to loss of guys if we can notice a thomas Beatie idea by the creative common divisor where common divisor is yes we can just elaborate or we can amend about ourselves and so after we figure house then we use a logic of this binary search tree illogical for here so I didn't know Zika and to find out harder so quickly and quickly so is it time comparing city should be published or local log M times how that M is that a lot of the largest right Riley was Lindsay we need to search and you know this examples where um because at all times 10 power 9 that's there is enough and the Swiss commercial is basically over here so then we got a color here and we can define the create a comment and it says divider and I can use a common we've had at least a comment divide Oh a city for any to never return humpy to re-create a common divisor IEP humpy to re-create a common divisor IEP humpy to re-create a common divisor IEP and when your pan research so I'm even Canada is she two numbers and used to comment about the first we start here from 1 to an honesty is the temp pause 9 so when will your sister because she returned my man is a panelist oh yeah canta pickle and we go to the left and I love a good foot height so when you turn no I feel Oh yeah I made it
Ugly Number III
delete-tree-nodes
An **ugly number** is a positive integer that is divisible by `a`, `b`, or `c`. Given four integers `n`, `a`, `b`, and `c`, return the `nth` **ugly number**. **Example 1:** **Input:** n = 3, a = 2, b = 3, c = 5 **Output:** 4 **Explanation:** The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4. **Example 2:** **Input:** n = 4, a = 2, b = 3, c = 4 **Output:** 6 **Explanation:** The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6. **Example 3:** **Input:** n = 5, a = 2, b = 11, c = 13 **Output:** 10 **Explanation:** The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10. **Constraints:** * `1 <= n, a, b, c <= 109` * `1 <= a * b * c <= 1018` * It is guaranteed that the result will be in range `[1, 2 * 109]`.
Traverse the tree using depth first search. Find for every node the sum of values of its sub-tree. Traverse the tree again from the root and return once you reach a node with zero sum of values in its sub-tree.
Tree,Depth-First Search,Breadth-First Search
Medium
null
1,751
hi folks let's stop maximum number of events that can be attended too it's actually a hard problem so we are given an array of events the event has a study and an ending the value and we can choose at most k events and they cannot be overlapped it asks us to give the maximum value we can get so there are some examples in the first example we can attend event 0 and event 1 so we can get 7. in second event we can attend event 2 so we can get 10 in the third example since k is 3 so we can attend three events event one two and three and we can get nine so some constraints the study and ending can be pretty large so if we do dp the dimension cannot be the absolute value of study or end date the value should be the index so we can use dynamic programming here first we can search events by end date and we have dpij means the maximum value i can get when attending at most three events with previous i events so i can choose the previous i events and i can choose at most three events then dp event lens k is the final answer here okay let's take a look at example and its implementation so we have three events here four is the value of the first event three is the value of the second event one is the value of the last event okay so first we need to start it by the end date it becomes this and the event two event when the name is uh not that meaningful we can reverse them yeah okay now we can initial guys our two dimensional dp array and we add one dimensions and it's very convenient when coding so the first row and the first column is always zero okay now let's take a look at this follow first we for loop every new event in the outer for loop we have an inner for loop the first inner for loop is used to calculate the non-overlap calculate the non-overlap calculate the non-overlap index for example if i is three the count of events is this event two and for this event we for loop every element before it and we find the closest event that is not overlapped with the counter event so if it's event 2 the non-overlapped index it's event 2 the non-overlapped index it's event 2 the non-overlapped index will be 1 which means it's event 0. note this index starts from 1 so for event two the closest non-overlapped event is the closest non-overlapped event is the closest non-overlapped event is the event zero for the event zero and the event one there's no non-overlap one there's no non-overlap one there's no non-overlap events before so the non-overlapped events before so the non-overlapped events before so the non-overlapped index will be zero here okay so what's the value of dp11 we know for a dpij if we use i which means i attended event i so the value should plus events i minus 1 2 this is a value of the current event and what's the previous dp state we can come from so it's dp9 overlap index then j minus one since we already use one event here so for the country event if i don't use it then the previous state is dp i minus one three so for dp 1 if the value is 4 here then for dp 1 2 the value is also 4 here ok now what's the value of dp 2 1 we can do the same so now overlap index is still zero okay for dp2 the same okay one is three so now overlap index is one and db3 one is four but dp32 we know db32 can become four plus three and let's say so tp32 can be dp11 plus event two so it will become seven okay so this is for implementation first we sort the events by the end date then we initialize our two-dimensional then we initialize our two-dimensional then we initialize our two-dimensional dp array then we have auto for loop which is where every new events for every new event we calculate the non-overlapping non-overlapping non-overlapping index okay then we follow j from 1 to k we calculate dpij here so what's the time complexity in the sorting it's unlocked on any length of the event then for this alter for loop with for loop and times in this uniform first we use linear search to find this non-overlapping index so to find this non-overlapping index so to find this non-overlapping index so it's on and we also uh has an inner for loop which iterate k times plus o and k so this is time complexity actually we can improve it a little bit since we are using the linear search to find the non-overlapping index the non-overlapping index the non-overlapping index we can also use binary search here so it will become old log and if we use binary search to find non-overlapping binary search to find non-overlapping binary search to find non-overlapping index and we can improve the time complexity to o and log n plus o and k okay that's it so it's actually a not easy problem and there are some tricks we need to sort it um by the end date and we need to have a two-dimensional dp two-dimensional dp two-dimensional dp array and the two-dimensional is based array and the two-dimensional is based array and the two-dimensional is based on the index not the absolute value of the day also um it's enough to just compare by end dates we don't need to do that if end date is same without five started it's not necessary assuming we have two events one study is three and a five one study is once and then five it doesn't matter who comes for first since the latter one will always include the state of the previous one yeah thanks so much
Maximum Number of Events That Can Be Attended II
slowest-key
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Array,String
Easy
null
835
in this problem we are given two binary images so by binary we mean that their pixels are either zero or one values and these are square images so uh width is same as height and we have two images so you can see one of them is a one of them is b and uh you are allowed to shift one image over other you can also keep it exactly here so if that will be the initial step so a b is imposed over a and there will be some zero values there will be some one values so if you overlap this one over this you see if one and one overlap or not so we have to count what is the maximum such possible overlap and what operations you are allowed to do so initially you overlap a and b together you count how many of the ones are overlapping on top of each other that is if there is a one in zero one position in a and uh without doing any shift if there was a one in zero one of b also then you would count that as one uh but you are also allowed to shift it so you can shift it uh in the direction of down right up and left so that again here this part is overlapping so whatever is not overlapping you don't consider that but here let us say we have four ones and in b also at this position we have one and so you see that here we have four overlaps so maybe for this case four was the maximum so you will return four so you are allowed to do as many translations as possible so you can slide it left as many times as possible obviously once it goes out of this image there is no point in trying further it will always be zero so you will slide to the right by at max n minus one step similarly you can slide in the bottom by at max n minus one step or top y n minus one steps and left by n minus 1 steps and you have to find the maximum among all those overlaps so overlap only means one and one overlapping so that is you multiply you do element y multiply multiplication of the overlapping region so obviously zero will become zero overlapping will with one will also become zero so only if both are one then the result will be one so let's see so uh in this example uh i will represent image a by this light blue color and image b by this transparent image with yellow boundaries and let's say we have 4 cross 4 for this example in general it will be n cross n so what we will do uh we can uh keep one of them as fixed so that is the problem statement and you will overlap b on top of it and then slide b as much right as possible and as bottom as possible similarly left and up so let's see so here we have so we will first take the overlap with a and b exactly overlapped that is if let's say we have one here so these are ones and others are zero and in b we have let's say one is here it's zero here it's one so you see the overlap will be just this one this is at the same position and this one so without doing any shift the max overlap is 2 now this is our initial state next what we will do we will keep we will only shift in the x direction so this is for y shift equal to zero so you can think of it as y safety zero and x is varying from zero to three we will not shift more than three there is no point in that so here we shift by one so what will happen so let's see these one will remain same and here it was one so it goes out of scope and here it was one so this is after x equal to 1 y equal to 0 this is after x equal to 2 y equal to 0 x equal to 3 y equal to 0 and by x we mean x shift next y is 1 we shift in the this direction also and x is 1 this is y equal to 1 x equal to 2 and this is y equal to 1 x equal to 3 and the next one will be this will come here y equal to 2 then y equal to 3 so all possible shifts we have made and in the last one what will happen this will be like this just one cell will be overlapping this is 4 cross 4 this one after that if we make any further shift none of the cells will overlap so we see in all these configurations what was the overlap that is one and one matching in this region so here this is just the only reason here this is the only overlap so let's understand how we will write this code understanding this is trivial you can do all the shifts so we have done x and y direction what will be the other two possibilities left and right left and up that will be equivalent to keeping this image stationary and moving this bottom and right so those are four cases next let's understand so let's say we have this uh and there is one here in both of them so let's say black denotes the one in this one and we will write in red or not so visible let's write in green so this green denotes one in this b and black one is in a so now uh a what is this row this is 2 and this is 3 assuming we are starting from 0 so a 2 3 is 1 right and we have shifted in x direction by 2 so x is 2 and in y we have shifted by 1 so you can take any general x and y here we are taking 2 and 1 so here b this value is a 1 is equal to 1 so when these are satisfied then there is a count of count will increase by 1. so what are these values let's say these are general so now let's generalized we are looking at a i j when a i j is 1 and shift is let's say x and y in the x direction by x y direction by y then b what is this is nothing but this value minus x minus y why because uh we have if we put it back we will have to move it left by two units and up by one unit so this is a b i minus y and j minus x so when we are shifting in x direction rho is not changing for example you see first second and third here x is not changing x is uh y is zero so when y is constant columns are changing so when we are changing in x direction columns are changing and when we change in y direction for example in these two then row will change because we are shifting in this direction so it will go to the next row so that's why uh here in i we are subtracting y because changing y changes in the row first one is row and here x so this is the general case so this we have to use in our code so for shifts how to take all the cases x will be from 0 to n minus 1 then in the next loop we will have y equal to 0 to n minus 1 so these are all possible shifts and then here what we will check we will iterate through all the pixels of a and b you can iterate through one of them other one we can get from this relationship x and y we already have so let's write it again so x equal to 0 to n minus 1 this is our first loop y equal to 0 to n minus 1 second loop and what was this loop for this was for shift all possible shifts so you will see that we are only shifting in right and bottom and we are not shifting left and up because that is equivalent to fixing second image and doing the same shift in a so either you shift a and b are overlapping and let's say we shift b in this direction right direction this is equivalent to shifting in left direction the overlapped region will remain same in both the cases so we have just defined shift in right and bottom direction for simplicity and in one case we will keep a fixed and shift b in other case we will keep b fixed and shift a so we will account for the other two cases so these and these loops are for shift in x and y direction then we have to iterate through all the pixels of one of the images a is fixed so let's i equal to 0 to n minus 1 this is the all the rows of a then j equal to 0 to n minus 1 these are the columns so here we are iterating through pixels of the image binary image and here what we will check a i a when whenever aij is 1 then only there is a possibility of overlap otherwise why would there be overlap so now we find a i j equal to 1 then what we will need to check so if this is the case then if b i minus y and j minus x is also 1 then increment the count so we will keep a temporary count here for this shift for each shift we will have a count so we will define a variable here temp equal to zero so we will do temp plus you can merge these two conditions into one if this and this then temp plus now this is the overlap for one shift x and y and we will have a global counter so after this one shift we will check count equal to max of count and this temp that way we will check all the shifts and the global maximum and we will need to call this function whatever we have defined two times once passing a and b next time passing bna to account for all the four shifts so let's write the code for this if you understand this then you can write it very easily so we will define a function called shift and count so these are the loops for shifts now this is the temporary counter corresponding to this x and y pair x and y shifts now we are we will iterate through this image and uh no need to iterate this complete thing we can only start iteration from here to here from this point so from this point till this point we are looking at image a no need to look at these pixels which are not in the overlapping region only this part overlaps and what is this value is exactly x and y so this coordinate is xy and this coordinate is as usual n minus 1. so this is one optimization so if you start from here anywhere this i minus y will go out of bound so you will need another bound check so better start from here so we will start from x and y will start from j will start from y so in one case we are keeping a fixed and shifting b in right and bottom direction all possible values and in other case we are keeping b fixed and shifting a in the right and bottom direction so shifting a in right and bottom means shifting b in up and left so that's why it these are equivalent cases uh so there is some error in unsigned offset overflow so i is the row number and we have made some mistake here so here row number is this y okay so this is the error here so you see this is the shift in y direction so this will be y so this coordinate is not x y but y x so you have to very careful here so shifting in y changes the row so it's slightly opposite so this we need to change here x i starts from y and j starts from x now it works so let's submit and the solution is accepted and we are right here around 94 of the submissions so it's good so what is the time complexity overall let's analyze so we have four loops this is from 1 to n and these are also not exactly and slightly lower but it's of the order of n square only so overall it's n raised to the power 4. if n is the width one of the dimensions not the number of pixels but just width so it's of the order of n raised to the power four time complexity and space is o of 1 we are not using any extra variable apart from some small variables so it's one now let's write the same thing in java and python and the java solution is also accepted and here also it's good 88 percent of the submissions now finally let's write it in python so let's name it a to differentiate from this so that there is no confusion so here we are unnecessarily making some copy here so we can try to avoid that by modifying this code but let's keep it for simplicity and the python solution is also accepted
Image Overlap
linked-list-components
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values. We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the **overlap** by counting the number of positions that have a `1` in **both** images. Note also that a translation does **not** include any kind of rotation. Any `1` bits that are translated outside of the matrix borders are erased. Return _the largest possible overlap_. **Example 1:** **Input:** img1 = \[\[1,1,0\],\[0,1,0\],\[0,1,0\]\], img2 = \[\[0,0,0\],\[0,1,1\],\[0,0,1\]\] **Output:** 3 **Explanation:** We translate img1 to right by 1 unit and down by 1 unit. The number of positions that have a 1 in both images is 3 (shown in red). **Example 2:** **Input:** img1 = \[\[1\]\], img2 = \[\[1\]\] **Output:** 1 **Example 3:** **Input:** img1 = \[\[0\]\], img2 = \[\[0\]\] **Output:** 0 **Constraints:** * `n == img1.length == img1[i].length` * `n == img2.length == img2[i].length` * `1 <= n <= 30` * `img1[i][j]` is either `0` or `1`. * `img2[i][j]` is either `0` or `1`.
null
Hash Table,Linked List
Medium
2299
93
video I will be discussing about lead code problem number 93 that is restore IP addresses in this problem you are given a string and you have to produce all the strings that have a valid IP address so you have to insert three dots in the string and it will form IP address you have to check whether it is valid or not for example this is a valid string but this is not a valid IP address why because it has to range from only 0 to 2 Double 5 for example this is a valid string but this is not a valid string similarly anything greater than this that is 2 Double Phi is also not a valid string so you have to produce all the valid strings and you have to Output that in an array list so let's though it looks like a complicated problem let's not complicate this what are we doing here we are just inserting Three Dots and we are forming the strings and checking whether it is valid or not let's dive into the problem what are the two quick observations that we'll be drawing from this one thing is wherever you place the dot the length of the string can only be one 2 or it can be 3 it can never go greater than 3 right why because if you go greater than 3 it will already be greater than two double five so that is not happening so wherever you insert the dot you have only three options that is length one length 2 and length 3. the only thing that you have to do is verify whether this is valid or not say for example let's just insert one dot in the beginning so we can insert after length one length 2 length 3 so what it does is it will insert at one it will say this is valid and it will insert as 2 it will say this is valid it will insert at this point and it is immediately says it is invalid but if you look here this is not a valid string right three point triple five so what we can do is do we are inserting one dot we can also verify the ending string by thinking that we are inserting one more Dot and we can say that this is invalid what we are just doing is we are also verifying the last part of the string right so let's think it like this we have a magical function where we pass the string into the magical function and it will insert a DOT and it will give it back to you all the valid strings until that point okay so we will pass this to the next say for example I will explain with the entire problem so for example if you think like this so this will give you three possible outputs fortunately all of these three are valid but I will just explain you the last one again it will give you all the possible outputs again all the three are valid here then again I will explain just the last one again you give the string to the function what the function will give you it will give you back all the valid results these are the valid results that it will give you but if you check here this is invalid but the other two are the valid ones so let's dive into the code and like I will explain you so in this magical function what are we giving we are giving the string and we are also passing one more thing that is index why we have to pass index so once I have inserted one dot right forget about this string don't even think of that string forget that it exists right so you will just be passing this part of the string and you will be asking it to insert one more dot so just to forget that string we are using the index what does it stay say so anything before this you forget it and you just insert me a DOT and give it back so what we do so we pass the string we will just say to insert a DOT and give it back to us but while giving back to us what this does is it will recall itself again and it will insert one more Mouse similarly we will insert it until the dots are greater than 4 we will just return it because that is not a valid scenario however if the dots equals to 4 this though we are inserting three dots since we want to verify the last part also we are adding this additional condition okay so this is a valid condition where we have inserted all the four dots and all of these are valid and also this string is empty say for example in this point say there was one more thing so that will not be valid case right say for example the string is still not empty you have four digits remaining so that is not a valid scenario so this will check for the valid scenario that is the index should either be at the end or it should be greater than that so if it is in the range it will add it to the answer that we are required that is the first thing what it will do again from length 1 to length 3 it will generate the strings it will insert the dot and it will verify if that is valid or not and then it will insert the number say for example in this particular scenario what it will do is it will check here where I want to insert the dot and it will verify if I am inserting the dot at the correct position or not and that is valid or not then it will go to the next thing so let me run this program and also submit this thank you for watching the video please do like and subscribe but before that one more additional uh thing that you can add here is that you can also add if you look in the same problem itself so one more thing that you will be able to add here is that if the length of the string is itself greater than 12 you can just return an empty string or the remaining dots remaining string if it is greater than the required dots length into 3 you can just return empty string you can or you can just disqualify at that point say you have already inserted two dots and the remaining string is actually eight it won't be possible right we cannot form a valid with the other part of the string so one additional logic that you can add here is that logic so once you add that it will actually reduce the time complexity thank you for watching the video
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
1,880
That welcome back to my channel so today we are going to discuss the problem of elite contest 243 in the morning the problem is this check in wordy total summation of two words so this is easy problem Meena so what to do in this why do we need the first word you like friend Rickshaw convert is a string and a target is given, there is a lion, basically what is to be done in it, whatever letter is there, it appoints the opposite, just like it appoints the Gujjars, whoever consumes, seats like this, they do it man fight. Then what we have to do is that for every letter that is corresponding to it, we will take its corresponding digit and make a number and then we will find out its corresponding number which is 021, if we take it directly in a similar manner then seeker 2 will come to B's promise place 10 210. It will be done, then we have calculated the second wait for the first word, then if we sum these two, then one plus two hours, if we sum them, then if we have a target of 5 minutes in German, it comes, then we have to return two, let's see. So, like what have we given, we have a torn urine, so if we keep it as this trick, then whatever it is, it appoints zero at one place which was yours, if instead of two celery or else, otherwise. If it goes, then it becomes 2021, then if you give it, convert it into clay, shine, then it will become, then A, convert it from us or fear, then replace C with hot, then replace B with grams, one is hard and one if you mix it. Give from this zero that the sun will be killed in this teacher there is 210 and this is our target convert that target to hot, two will come in place of c, this will be done in the place of the middle and if one goes in place of b then this will become our 231 if If we see, if we add hot one and 2010, then this will be our 231. So, after adding these, we have the target word, so we will retail how to. Now the question is that whenever we add this, which is How do we create this, like if we have given here CBE then what will we do to convert it, we need husband's June 1974, its value is on small as it is its value is original note so because here which is Also, there is chocolate lying here, if we increase its value to 197, then its correspondence will be drowned, like a big 11 character whose skin value is not there, if we increase it to 1970, then Tomar Parshu has to come. So we will write at one place similarly, whatever its value is - 97 61 whatever its value is - 97 61 whatever its value is - 97 61 A photo. Which place will we write? So Sidhi, what are you doing, whatever Maratha character is there, whatever kind of character is there - So this is what Maratha character is there, whatever kind of character is there - So this is what Maratha character is there, whatever kind of character is there - So this is what we have and then The marking that will be made later, for example, I have given its recipe that 24 kissing will be made from zero to one, we will convert it into Assam interior, we will subtract this row as 214 and we will return the quantity, so we used to live in the court, handed over both the codes in the file, but Before thinking about the record, we will make three rings, one which will be made of post, this one and this one, if only one team will be formed, then for 3 MP Singh, we will go to this dynasty two and woman and first word, whatever will be ours which will be that. Also the festival which will be read by taking out the sky of the character and getting its value from the audio function will take out its value and note down from it like we will do here when we are on C-90 then learn whatever is its value which is on C-90 then learn whatever is its value which is on C-90 then learn whatever is its value which is C because If there is no, then that - If you were doing it, then by taking out the that - If you were doing it, then by taking out the that - If you were doing it, then by taking out the stuck value, you will make it 97 - stuck value, you will make it 97 - stuck value, you will make it 97 - then we will have access to the interior. If I have a senior actor, then now we have to put him in this trick. To put him in the mud, we will have to convert him. In Spring, that's why we have used Spring Function here, so we will do the same procedure to convert it will come in a team or they will go Amazing that they were getting my posting that we are doing this in the interior. So to do these things, we will give you a simple function brick and put stuffing inside it, which we will make a lion, we will give all our numbers in these 120 and in the last, how to do these, this was our Android and * I swear do these, this was our Android and * I swear do these, this was our Android and * I swear if this is the sequel of our entry. Tone to return, do solitaire, do annual record entry from this, if this will start it, otherwise this, now let's run it and see, first of all, cutting suit is arm hole that its which of length of cost word and Convert your data to If there was a group of data, then basically there is a solution and time and space complexity of Vansh-Kul, we are some of us, we are space complexity of Vansh-Kul, we are some of us, we are space complexity of Vansh-Kul, we are some of us, we are using all the vegetables. A Swag is your approach and code. If there is any problem, then you can write in the comment section. Thanks for watching
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
338
all right so this is lead code 338 counting bits um so it says given an integer n return the array uh return an array answer of length n plus 1 such that for each I uh I is going to be uh greater than or equal to zero and it's also going to be less than or equal to n um in that instance every basically every value is the number of ones in its binary representation of I so what does that actually mean let's look at this example um let me make this black so uh we look at example one so our input is 2 right and our n is two what they want us to do is basically return an array of n plus one where basically we're gonna um count up to two starting from zero so zero one two so this isn't base this is in base 10. or non-binary this is kind of like or non-binary this is kind of like or non-binary this is kind of like you know numbers like that you would learn in math like just one counting by one two three four and then what they want us to do is return an array with where each value is converted to Binary so what's um what's zero converted to Binary let's go ahead and write our basis of two so that I can make um be a little bit easier so basis of two so to convert to Binary we're going to do start with base 2 to the power of 0 2 to the power of one two to the power of three I think for this instance we only need these bits um basically uh we're gonna look here so 2 to the power of zero or two to the power of zero is equal to one right so we want to see how many we want to see in these positions if it's a one then it means that bit is on or represented by this base of power of 2. so uh in this instance it zero in binary would just be zero however for one we would use this bit here we would use um let me use my mouse so you can actually see we would use this bit here to represent one in binary because 2 to the power of zero is one you can watch a video on find converting from base 10 to Binary but um yeah and then for to click to represent two in binary we're going to use this bit here so it's going to be uh zero one actually not zero one is going to be I believe one zero right because we're going to use this bit here because 2 to the one is two and then we're going to have a trailing zero because this bit's gonna be off okay so now that we've converted it in binary our values to Binary right Euro rise what they want us to do is return an array where we count the number of ones in each of these uh base 10 values in binary like the number of ones in their binary representation so in this position 0 there's 0 1 so that's why we would have a zero there and then here we have one right so that's why we'd have a one here and then here we would have one also so that's why we have a one here let's say that this was one oh one then we would have two in this position because there would be two ones but for this instance it's not that but I'm just trying to Showcase what we're actually returning so we're just returning the number of ones in the binary representation okay so um yeah so uh how would we actually do this so um you could do this multiple ways you could do this like um the kind of naive solution would be to get every value um convert it to Binary and then uh count the number of ones so let's say that we were we had one zero one in binary right and we wanted to count the number of ones where we could have like a count variable and then we could modulo this by two and do some math to see if this is one or not and then we can just truncate it by using integer division that's the naive solution that solution would come out to being at o of n log n because you're doing you're constantly dividing or n or number by two which is a logarithmic time complexity and then we're doing it for up to n numbers so it'd be n log n so that would be the time complexity if we scroll down that's for the naive solution so they said that it's very easy to come up with that solution and then they want to see if we can come up with a solution that uses linear time and possibly a singular a sing Single pass so uh it might not be as intuitive as it seems but we're actually going to do a we're going to use a uh something called dynamic programming so we're gonna um we're gonna start with sub problems and we're going to use those sub problems to build up our solutions to getting the actual output so and that's going to give us a it's going to give us a faster uh run time so instead of n log n we're going to have um o of n which is much faster this is much faster than this okay we uh we may we might sacrifice on some space so our space complexity might go up but we're gonna um still be faster in the time okay um to visualize this I made this little chart this little uh table I guess um Okay so uh you can see I labeled the column so on the top left there's the input in base 10 and then in the middle is the input in binary so these numbers let me use my mouse so you can see these numbers here are the input is basically this value converted to Binary and then just for help I added the basis of two and then what their value comes out to so 2 to the base of to the power of 0 is 1 to the power of one is two to the power of two is four and so on to the power of three is eight and then the output for our function is going to be here Okay so uh let's see let's walk through so um here right uh like we did in our first example zero and base 10 is this in binary and there's zero ones here so that's what our output would be one we would have one two in binary we would have one because we're utilizing this bit right here we're turning this bit on and nothing else because that represents two and base two right so we'd have a one here three we would utilize this bit here and this bit we would have them both turned on so that's why it's one here let me um use this color that's why it's one here because we're representing a three so we'd have two okay and then four um four has one bit uh one actually on so we would output one right and then five has two six has two three has three and so on right so uh what I'm trying to get at here is that there's uh we're doing some repeated work that we could optimize our solution to um basically be to gain that over n time complexity so um as you can see it might not be as apparent but um realistically uh I'm gonna box it in yellow this is pretty much the same as this right these two sections are identical right it starts with let me get my mouse again it starts with zero one which is the same here zero one so they're identical right the only difference between these values is that there's a one in this place in the two to the power of two place right so what we could do is basically um what we could do is store the uh we could store the output of these previous values and what we can do is just basically do one plus we look back at whatever this output was right because this is these zero zeros match with the zero so there's a difference the positioning would be difference of four right so we're looking back at zero the zero input so we're going to say one Plus however many ones uh zero ahead right however many one zero had and what about for five we're gonna do one because this new bit here this 2 to the power of two is one uh plus however many bits however many ones one had this one here so you could see let me do this here you can see that again there's an offset of four right we're looking back four positions here to look at one okay um so what we're gonna do is we're gonna actually we're gonna as I said earlier we're gonna sacrifice on our space to make the time complexity faster so we're gonna create a uh an array and let's just call it DP Ray right and then this DP array is going to store the uh outputs of our previous values so uh this 0 is going to go here my Pen's kind of bugging out the zero is going to go here right and then this one is going to go here and so on we're just going to tack on these values let's just tack on the first four okay and then uh let's try to instead of having this in words let's actually write out what it would be like an equate in an equation so um what this would come out to be would be basically we're doing this one we're Counting this most this greatest power of two currently our greatest power of two is this position right the third position the two to the power of two so we're doing one plus whatever we had at um whatever we had at four positions beforehand so we're gonna do the equation is going to be one plus we're going to look at our DP array right we're going to look at our DP right because this is what's going to have our values our previous outputted values we're going to look at our DP array and we're going to say we want to off we want to get we want to look at the zero value right we want to look at this zero value so how can we do that well we can do the current n that we're at which is 4 minus 4 basically right so we get at zero so we do 4 minus four right so that would give us a this would come out to be in one plus what does DP a rate of 4 minus 4 goes out to be in zero right so this zero this is the zeroth position so there would be one plus zero which comes out to be in one right so that gives us that checks out with this output here right okay uh because we're not going to have these strict values here we're going to have to use some variables let's try to deduce what these variables actually are so this value here that my mouse is going over right here this is going to be our current n value so let me do it in yellow this is going to be n right and then this is going to be what is it going to be right now we can't right now we don't really know actually it seems like it could just be whatever the maybe it's the same value maybe it's N2 but let's go a little further and let's see um let's see if we can uh figure out what that's going to be so let's see uh let me scroll down slightly so what if we're gonna try to let's try to see what um it's gonna be trying to like basically do exactly what we're doing here with the equation for eight right so let's do let's bring this down here Okay so a is going to be one counting this one here right Plus is that going to be an offset of four let's see uh what would be if we look back four positions at four that would be um that would give us another one zero but as you can see eight in binary does not have two ones in it only has one so realistically what does the remaining zeros what do these zeros represent what are what is this in binary or in base zero or in binary this is zero right so realistically this let me do it in uh it's orange realistically we want to do one plus looking back all the way back to this starting zero right so we're gonna do one plus uh DP array of um of n minus what would it be minus uh let's just actually fill them in with numbers first would be 8 minus eight right because uh in this previous example we said that this first value is going to be n which is going to this is n right this column is n so all these values are n so 8 this is our n and then because we want to look at we want to basically what I'm this is kind of hard to explain so sorry if I'm starting it a lot but instead of looking at this here what I those three zeros and trying to count however many ones there are basically what we can do is just look back at the previous one of the previous Solutions which is all the way back at um our first solution which is of uh of input zero right so it's 8 minus eight okay so off of this um let's see if we can actually deduce what this second value is going to be with this how does is this four always going to be the matching number here um it's not always going to be the case I don't believe uh I think let's test it out with five Let's test it out with this test case of actually to do with that six so let's put this all over here so what's this gonna be it's gonna be one plus DP array of hopefully you guys are getting the pattern already but so what does uh we're using this one right plus so what does this one zero look like it looks like this two right so it's we're looking six going back to two that's four positions so it's six minus four in our DP array so this is basically the index that we're going to look at right um and we can write out the indexes here if it helps out zero one two three so we would look back at the what is it going to be the second index so we're going to look at this index here and we're going to do one plus one which gives us our two so uh back to deducing what these values actually are this is n right the left values n in our brackets but what's the right value so it's we know that it's for this example we know that it's not going to just be six it's not going to be whatever n is as well it looks like it's whatever is the greatest power of two right in this example the right value here where my mouse is going over this 4 is the current greatest Power of Two that we have on right that is set to one here is the current greatest Power of Two which is why we do subtract by four and then at eight this example down here if you can see my mouse circling it this example we're doing eight which is the n value which is this value here minus uh an offset which is basically the offset is the current greatest value of two which is um which is eight here so the whole formula is going to be uh one plus DP array of n so the current value that we're trying to calculate minus greatest power Power of Two right okay and then that's in the bracket because this is going to come out to be in a an index right I'm just gonna get rid of that it's horrible so um Okay so yeah this is what we're gonna do this is uh our equation for our DP um solution and let's try to deduce this time complexity so um right so off the bat uh we are going to have to calculate we're always going to have to calculate n values right we're always going to have to calculate whatever the input is n so like say that we count say that input was um actually we might have to calculate n plus one but say that the input was eight right we'd have to calculate 0 through 8 so it's actually nine values and then we're going to have to say that input was nine we're going to do 0 through 9 which is actually ten values and because we include zero right um so our time complexity uh yeah so as I was saying the time I don't know where my Pen's not working time oh my pen or my laptop is lagging the time I think it's because I was so zoomed out the time is going to be o of um of N and then the space so automatically this is way better than the O uh o of n log n this is significantly better and then if you don't believe me you could look up at the bigger cheat sheet and see the different performances of these time complexities um so for space this one we were sacrificing on space we're using a little bit more space to get our time down right so this space we're going to use we have to store a DP array an array of our previous values so that we could use those values to calculate our new ones in a fast way right and then what's this DP array going to get up to the size of well it's going to get up to the size of um oh it's going to get up to the size of uh and plus one I believe right and then technically this is really n o of n plus one but I think in uh in Big O notation you just drop this plus one I believe you might not I'm not too familiar with that I kind of forgot that concept but it's either Big O N or Big O of n plus one but realistically I think this plus one is negligible so uh because that I'm just going to call the space of n it also might be o of n plus one but I think that plus one is negligible we're here on the code um and I kept the Whiteboard over on the left so it's easier to just kind of reference her our algorithm so as I said we're going to utilize a DP array right or it's just an array right but it's just a normal array but the values in it are using the principles of dynamic programming so basically we're starting with smaller problems and we're using those small problems the solution to the small problems to build up our solutions to the other problems so that we don't have to recalculate previous Solutions if that makes sense basically we're optimizing it by not here if you can see here what I have box and yellow were not recalculating this because we're utilizing our DP array but we're sacrificing by using some space okay so we're going to uh we're gonna start our DP array and it's going to just be I just gonna have one value in it just gonna start with zero um I chose zero because uh in our constraints the uh lowest n can be is zero right and we know that uh we know that zero and base are zero in binary is just as zero ones right the output is going to be zero so we know that this starting value can just be zero it's just like our base case if that makes sense hopefully uh over the explanation made some sense um so we're going to start off with zero to start off our dynamic programming um you know uh solution and then we're going to have a value that's called greatest power of 2 and that's just going to start at what is it going to start at well if we zoom in back in our oops it's going way too much let me use my mouse I think it's a lot easier oops if we look back up here what's our what's the first greatest part of two it's one right because one is a power of two it's two to the power of zero so we're going to start this at one right greatest power of 2 is going to start at 1. okay and then we're going to do our for Loop because we have to calculate n plus one values right so we're going to do 4 I in range uh well what's uh as you know range can take you can message you could uh give it different types of parameters so we're going to give it a starting uh starting value and an ending value right so that this is just a comment the starting value is going to be what are we going to start at since we've already initialized our TP array with uh zero meaning we've already calculated this first value we can just start our I at one and then what do we want to go to as I said we want to calculate n plus 1 values because in this case in this situation n was um and was what it was uh eight I believe yeah it was eight so we calculated nine values because it's zero through eight including zero so that's nine values so we would do one and then the end ending values and be n plus one okay um and then what we're gonna do is um here we need to decide uh we need to decide when we're gonna change our greatest power of two uh variable basically um what we're gonna do is uh at each value right so right now greatest power of 2 is 1 right and then what we're going to say is uh n is in this situation where our Mouse is at n is zero right so uh one times two does not equal zero so that's not uh that's not our greatest Power of Two two times one does not equal one two times one does equal two so that means that we've found a new greatest power of two meaning that there's a new um most uh you know biggest power of two right here this value here so the condition is going to be if greatest power of 2 uh times two is equal to um is equal to we're using n so I'm going to change this value I'm going to change it from I to n so if it's equal to n then that means that we found the new greatest power of two so we can just reset raised to the power of two to be I are to be in okay um so that's how we're gonna reset our greatest power of two and then now we're just gonna uh now realistically we just have one more kind of line of code to write and that's basically what we've deduced to be our uh dynamic programming kind of equation we're going to do um before we get ahead of ourselves what are we actually returning we're returning an array right so we're going to return this DP array right we're going to return after we've populated all the values we're going to return DP array right so what we need to do is we need to append to the DP rate after we've you know calculated our values using this um using this formula so we're going to say DP array dot append which is basically a pen to the end of the array right here DP dot append um one plus and I'm just copying what we have here on the left 1 plus DP array of n minus greatest power of two and I just spelled out two instead of using the actual 2 value but this is what I have for the variable um yeah and then we just return the DP array so that should uh come out to be in solution unless I've made a mistake uh let's see uh I made a syntax here I didn't add the colon so oh I actually made an errors so um okay so I made another dumb error it's basically this uh it's Python's indenting that basically this append this pen appending operation was in the if statement um we want it to be untapped so it's underneath the if statement right here so it's not inside of the if statement but it's outside of it so we want this to happen on each iteration of the loop okay so now let's run it yeah so that works okay so here's the Big O cheat sheet so as you can see uh these time complexities are these Big O values down here the fastest so over log n and o one is are the fastest and then o of N and then o n log n so we made a sweet sacrificed on space but we got our time complexity to be faster than what our root force or our naive so this one was in the beginning which was oh and log in yeah so uh thank you for watching
Counting Bits
counting-bits
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:** \[0,1,1\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 **Example 2:** **Input:** n = 5 **Output:** \[0,1,1,2,1,2\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 **Constraints:** * `0 <= n <= 105` **Follow up:** * It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? * Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
Dynamic Programming,Bit Manipulation
Easy
191
1,750
Hello Hi Friends Welcome Back Today We Are Going To Solve Their Problems 1715 Minimum Balance Offspring After Deleting Similar Lines Subha Purvi Gurudev Description And Through The Examples For I Just Want To Mention That My Channel Focus Is On Helping People While Preparing For Coding In Service And Jawa Interview Sun My Channel Radhe-Radhe WhatsApp Interview Sun My Channel Radhe-Radhe WhatsApp Interview Sun My Channel Radhe-Radhe WhatsApp Good Videos Saaf Aur Yeh Daat Will Help You Are Interview Preparation Tips You Are Like A Preparing For Job Interviews And Code Interviews Object Simply Turning Claim Which Is This Please subscribe to the Channel So Let's Go Through The Description given string gas consisting of only characters abc your host to apply for glowing algorithm string in number of times pick not empty prefix from string gas where all the characters in the prefix are equal show you how to select a prefix means left pen drive traffic from Distinct Where All The Characters Should Be Recovery Tank Frustrated Subsections From String Is Where All The Characters Hindi Suffix Required And Will Have To Select The Officer Of The States Where All The Characters Should Be Equal Right The Prefix And Suffix Should Not Be Interested In Index Shuddhi Se Parata Bichha and suffix be separate the character from prefix and suffix send new year characters who have selected in graphics suite match to the character ring sufficient exporter senior and after you have done this day have to sacrifice of Delhi at both prefix and suffix from the word spring Tide And Who Have To Keep Doing This Operation In Benefits Fennel 5 Minute Times As Possible And They Have To Keep Reduce Industrial Credit And Debit The Inheritance Minimum Balance Of The Free Disk From The Original Screen Light Of Performing Operation In Number Four Times Possibilities Hero Times Professional Sphere of Organization So let's take a few second example over and will the go through this example and will you know propose our solution is they are going from the problem solve this is equal to what means is basically is seat first to like select left side effects Can Be Subscribe Electricity And Share And Subscribe Pratibha Se Character Have Selected Character Vyagra This Is The Meaning Of This Is The Field That Reddy Are Is The Suffix Should Have Selected This Prefix And Suffix And Over Again Selected Dost Prefix And suffix that you want again that as you can see name baby is the evening spring fennel and the remaining spelling be is the prefix and share 2010 affair side so both are doing so they can delete friend both mother and child after that agree meaning of being So for a drink we can select this post and prefix and second exam 10th from this cream and when did this bothered to enter and you will be left with interesting read nothing will wither industry and show but why we have to returns a yadav minimum link after The remaining spring after like performing this delete operation tight don't like selecting prefix indicating suffix and electing air tight of the same characters shopping discus will be left with zero length stingray evolved some delete all the characters by appealing 2019 right handed over then update Please actually minimum lifting after deleting similar and character of lights of this is not the problem is show how they are going to solve this problem solving different problems are there about spring right the basically prostate comes into the mind is music 2.81 is later starting and left music 2.81 is later starting and left music 2.81 is later starting and left End one is inside right side Uday Singh and 5000 flats for details of start and end points Solid system Previous one is the worst point Per latest end One is our end Appointed for this point to use To war Character Festivities and the start point 899 points Mintu Character Se Zindagi AB Point Rule Book The Point To The End Of The Spirit Sudhir Va 12345 6 Is The Sea Inside Powers Character Show Will Use This Character Sea Android Compare With This Character Match S8 Such Many Times Matching So What We Will Do In Rate Cases will basically issue pointer tooth next point start free mode to the next point a and will be reduced rates for this is start plus and minus so friends welcome two years ago software basically left with a string na ho rahi toh there hey similarity With To You Are Deleting C And They Have Created This New String Pujya White Highlighting Light Off Then Go To Sleep Good Deleted The Prefix And Suffix Rate C Basically Deleted Growth In Love With A String Swarna Again Will Perform The Same Operation Sabzi Again Have No Fear In the start and share and the internet and start and end points for solving lagna udaya to your friend of deleting bluetooth of birth of the match in recent visit to think and this is our leftover string tie thisavar leftover swing time highlighting right after deleting both ascribed Saugandh Point Arvind Moonlight Axiom Start Point Up And Sister And Pointer Show Will Again From Your Palms Sidewalk Editing Both Prefix B And Suffix Bhi Typing And Matching Too 20 Years On Key End General Subheg Sambhodan Matching Software And Stimulating That Were Delighted By Moving The Phone After That Will See Minute Baad Bind Pointer To Aap Ravindra Points The Point Picture Point He Arnav Right Short For Interview Point To Special Endpoint Arvind Ko * Member From Other Side 3 Arvind Ko * Member From Other Side 3 Arvind Ko * Member From Other Side 3 Start This Is The End To Interpret So After The Gagan Vihar Mind Of Using Your Like This a prefix and suffix and give them a chance to win again in this year and it is air tight and in this case such s victims greater than its so they can stop basically loot-loot will keep they can stop basically loot-loot will keep they can stop basically loot-loot will keep checking gift s b coming return hiten Hui Already Have Enough Process The Whole Spring And Whatever String Decided To U Will Keep Sharing Agree During It's First The Reduced Ring Will Be Like You And It Will Come Back After Crossing Like Removing Secret A Baby This Is Reduced In Greater Noida Easy Veg Chief Tehsildars Distic for the first operation Very Moustached Distic Will Now Comes Up B.Ed This Seat Show Hosting After Removing K Kupit Amused E Will Keep Reading Cigarette Removed After Removing Comes After Removing System Testing And They Calculate Percentage And Weaknesses This point and the cockroach people cold sleep but with little thought and in free mode start on thursday deputy director and they will reduce the mid point removing subscribe to the minimum after deleting similar problems solid one to implementation already explained in detail common sycamore going to implement it So let's look better implementation is created for start point 201 point is the last character of the standard and is creative work char chords selected candidate and was initially date fixed initialization is required to just her character diary attributes rings solid isms the best results in the beginning This Means The Beginning Spring Ise Maida Worshiping At Reduced Rates And Will Keep Reducing Of Indore Files Ko Sunavai Video Yaar Ko * Loot Lo India Sunavai Video Yaar Ko * Loot Lo India Sunavai Video Yaar Ko * Loot Lo India Health Tips Parties And 500 Ad That Welcomes More Than Android To Till Happen With Keep Reducing Saunf Worst Thing Will Do Places will take every district president and will check the start character and links alarm set that many more matching train will just amused and selected character revealed into the character moral match for example in this case I will make the first 100 we click may just removed his Wife And Use This Production Na And Kya Sunaun S You Can See The Series Matching Its Object Junior Associate Director Vikram Singh And Who Viewers Break From This Right Left Not Matching With Both Started In Character Shoot Merit Otherwise They Can Reduce That Spring Minimum And Basically Of soil food and want to give back out of wild adverse choice former and point and tried to consume the character time than possible even more special consideration for example tips servi all the best all doing and interact with moving ahead and in case of Winter Will Keep Creating Apps Long Acid Same Character For Example Meanwhile MP3 C Website Beautiful Beatings And Will Appoint Clear And Will Consume All This Character Of Deposits Of Wild Is Superhit Hai Network We Ine Jangid Finding C Basically Should Not The Child Will Do And Will Give Reduce Mother in Law and Right and Left at Which Unites to This Great Content and You'll Get 300 Midnight Others Wise Who Will Just Develop Calculator and Reduce Spring Tide Tribute to Worship's Complete Have Consumed S E Right Day Quarter Consuming Sewer Spring Is god like water due to this trick basically correct show will just removed his characters from distic this point characters that they have consumed and last characters that you have consumed the prefix and suffix from this meeting to have removed by pushing actors aishwarya doing clear switch tag in Sub string from start to end in plus one request pointer moved ahead and ponder decrement and so when you are taking a substance from distic and they are really initial eisenhower started in point using rate reduced spring night development boat 10 start for interview you want start point Appoint 2008 Location of the reduced in its own this is 2003 Location of the dating and sister and location of three do stringer 833 What do you do in here and we're going to keep doing but in parties 200 g job tool used same process and will Consider This Is The Stringer Right Diet Will Remove A Grand Villa In Excretion It Will Consider This Is The Spelling Of Good Spring And It Will Start Point Clear And Will Point Clear Shot Fool's Complete Dating Site End Saint To You Will Find The Singh Vikram Centigrade Will Consume Death Benefit Consumer End After Dhan Extra Internet Stationary And Will Return Reduced To Land In The End Suez Treatment Minimum Length Of The Giver So Let's Go Ahead And Rather Test Cases On 500 To 1000 * Run All The Test Cases But This Is 500 To 1000 * Run All The Test Cases But This Is 500 To 1000 * Run All The Test Cases But This Is Given To Off Side This Shoulder Test Cases In Software Testing The Correct Answer 11 2010 And 30 2013 Light Saudi Arabia Cutting Correct Answer Clear So Let's Submit And Solution That Is You Haven't Already Subscribed Police Channel Please subscribe The Channel Nav Swar Solution Ko Text Valid Point S You Can See And Here And This Is The Way You Can Approach The Problem Solving Minimal Link-Ups Pinups Deleting Similar And Link-Ups Pinups Deleting Similar And Link-Ups Pinups Deleting Similar And Using Two Point Approach After 120 subscribe To My Channel Please subscribe The Channel How To Solve Problems By Company Apple Facebook Google Microsoft And Other Companies And Problem and Problems of Previous Interview in Winter Problems Programming Binary Search Tree Related Problems Related Interview subscribe The Video then subscribe to the Page if you liked The Playlist subscribe The Channel and your Most Important Is Illegal Video Cantharis To Make People But Also Watch these videos and developed in the interview preparation 100 thanks for watching this Video Please subscribe our
Minimum Length of String After Deleting Similar Ends
check-if-two-expression-trees-are-equivalent
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Tree,Depth-First Search,Binary Tree
Medium
1736
498
hey everybody this is larry this is december 25th under uh so happy holidays of christmas whatever you like to celebrate uh hit the like button hit the subscribe button join me on discord let me know what you think about today's prom diagonal traverse i do solve this live so it may be a little bit slow on the solution but i go for my dot processor so let me know what you think okay so basically you're given um a matrix which is m by n which is a little bit messy we're trying to get it in some order which is okay um so the key thing to note which is something that um you get practice with or like you've done similar problems uh you may notice maybe it's something that you can also notice from practice in general um or just like working on this problem but that's how i'm able to figure it this part out is just that um it's just that uh it's there is a problem which i will mention obviously that i get from practice which is that the diagonal um you could kind of re order the diagonal um such and you can renumber them in a specific way and the way that i would renumber it is and there are a couple of ways that you can do it for this problem i think you can definitely go you know just diagnose that diet you know you could do for loops you can put things in a queue and a hash table and stuff like that but the thing that i would think about is just numbering these um diagonals and for example this is diagonal one and two and four will form the diagonal two and so forth and the way that i would think about it is just um if you have if you want to call this x y for rows and columns then x plus y would define the column number um and then the what i want to say is the mod you know the parity of that number will determine which direction you go and from that it becomes very straightforward um in terms of understanding once you're able to understand that the easy way to do it there are harder ways to do it as well um but that's what i would think about um yeah okay so i they're definitely very ever prone ways and for interviews you know you might think about different ways as well for me i think what i'm going to do is try to implement it like i would do it in a competitive nature which means i'm going to optimize first um solving speed right uh and everything is going to be you know ideally linear time and linear space uh just to kind of be and you cannot do better than linear time or linear space because well you have to read the input so that's gonna be linear time and output which is also linear time and the sp the output space is also gonna be linear so you can definitely use multiple of that um and that's basically what i'm going to do uh there are definitely a lot of different ways to solve this as i mentioned i'm going to just do a funky way just for fun and it's christmas so maybe it's festive i should find a chris uh ascent to that i have a center head that i haven't won that much this year because well i haven't gone outside that much this year but yeah well maybe next year um okay and it's very hot in my apartment so okay so now let's set up for i guess n m but i like to ignore uh m and n because it's confusing sometimes i use r and c for rows and columns sometimes i use just the word row and the word column or cars which is similar i suppose um just double checking if there's any constraints because in some cases um if rose is equal to zero uh then just return an emptiness i suppose um don't know if that's the right answer to return to be honest but uh but it's sometimes not defined anyway so yeah so then now the way that i would do about it's just very hacky which is uh d is you go to um d is terrible but basically um diagonals is equal to i'm going to use a default dictionary in python and what that does is just gives you a dictionary that if it doesn't exist or create whatever is in the function afterwards inside and in this case i want uh a deck inside so then that'll be uh easier for me too do i need a deck yeah i mean i could either do a deck or um in a way so maybe this is actually a little bit so yeah let's actually do list yeah actually let's use that so because you could with a list is the same idea in this case you just reverse the thing afterwards but let's use a deck so that it is um so we don't have to do any reversing so okay so then now we just do something like for x is in range of rows for y in range of cars um and we could do diagonals of okay so actually um let's just say diagonal is equal to x plus y uh and then we could do maybe if something like a diagonal mod two zero so if it's even we want to go from a large number to small number if it's um yeah so and if we're going from row by row then we actually want to for even rows or even diagonals we want to increase the number in the front and otherwise we don't return in the back and the way that i'm explaining it isn't just like some reading of the thing i'm actually looking at this thing this diagram and then i go okay for a given diagonal uh well an odd diagonal i look at every row and what changes well in this case uh in our diagonal when you get a new like on a row that's underneath when you add a new number you want to add it to the back and then so forth to the other direction right um so okay so what did i say even was so for even diagonals we want to insert it to the front uh a pen left i think uh oh matrix of x y else diagonals and of course you can actually do this in the list and as i said you could just invert the diagonal afterwards on either other even diagonals um yeah but either way it's gonna be the same as you look at each cell constant number of times so okay so then now we just have to group them back together and for that um yeah and also note that in this case actually one i use a default dictionary because i was a little bit lazy but actually we can actually do a list where the number of diagonals is just m plus n or rows plus columns so actually let me do it that way because uh it feels like the right thing to do um so we want one for each diagonal so it's rows plus columns so yeah so this is slightly better i think and what this also led us to do is that now we can get just concat them all together um there's still a joint no join doesn't do that right uh i think i'm just thinking if you're in a functional language you can do something really quickly but the idea is just have an answer uh for diagonal array in diagonals answer dot i think extent i'll just do it this way to append and then just return enter um let's run it real quick yeah so this looks good uh let's submit it and of course as i mentioned uh there's a lot of linear algorithm uh you can actually just you know based on this mapping you could for an x of y you can do some mapping with respect to um the position that it would be in it's just a lot more and so then in that case it'll be oh one extra space extra on top of the output um but as i said i'm trying to like speed one this a little bit it is the holidays so uh and i try to think about in a way where like um where i make the fewest off by one errors as much as possible not even fewest off by ones but fewest potential four or five ones and here it should it looks pretty straightforward in terms of one by one the only place that i might have enough by one is if i do this backwards in terms of risk so that makes it easier to debug because i'm wrong then i just flip the signs or something like that right um yeah that's all i have for this problem like i said it's gonna be linear time linear space no matter what and in this case linear is this in the size of the input which is the number of elements which is rows times columns um yeah and it's linear times in terms of in uh time and space that's why i have this problem again uh merry christmas hope everyone has a great time uh as i always say you know stay good stay healthy and i will see you all soon bye
Diagonal Traverse
diagonal-traverse
Given an `m x n` matrix `mat`, return _an array of all the elements of the array in a diagonal order_. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,4,7,5,3,6,8,9\] **Example 2:** **Input:** mat = \[\[1,2\],\[3,4\]\] **Output:** \[1,2,3,4\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `-105 <= mat[i][j] <= 105`
null
Array,Matrix,Simulation
Medium
2197
91
hey what's up guys this is chung here so um let's take a look at today's daily challenge problem number 91 d called waze so i mean this one is one of those very classic dp problem you know okay basically you're given like uh a string of digits okay and each letter each digit represents might represent one of the uh the characters right the letters from a to z so a is one and g is 26. and it asks you to what to uh to find the total number of ways to decode it right so for example right so the first for example this one uh one two right basically there are two ways to decode it because you know we could decode it to a and b right that's one way the other one is 12 in total which is 12. that's this l so that's two ways and two to six similar right so we have two six and then we have 22 six and then we have uh two and twenty six that's three ways to decode it and yeah so i think the reason this one got a lot of downwards is because of this leading this zero special corner case which is zero which means that anyone anything that's have if as long as this uh string has a leading zero then we always return zero because you know if zero one that's not a valid basically valid uh string here even zero one two three so basically as long as the first letter is zero we always return zero so that's that so this one is like you know if you guys remember there's like problem cause uh the ways you can reach the uh a certain stairs uh the stairs right let's say there's like in stairs and steps and at each time you can either climb one or two stairs okay right and then ask you to calculate how many ways you can reach the ends stairs so actually this problem is almost the same but the only difference is that you know so for this one you can every time you can either do a one or two but for this one there are some conditions you need to check before making this one or two move so what we do it we just define like a dpi here right so which means that you know uh so it means that by for the first ice digits how many ways we can decode and then it's going to be the what's going to be the total of the dp i minus 1 plus the dp i minus 2 because the biggest number we have is 26 so we which means that we can only go back to one or two steps but so for this problem you know the dpi and i minus one dpi minus two so each of them will have like conditions we need to check so first one is the dpi minus one so this one means that we're gonna use the current i to be the single ladders to be decoded so which means that you know so to do to be able to decode from this one so the current eyesight s i or s i minus 1 right cannot be zero so that's the condition we need to track we need to check for this i for this dpi minus one because if the current one is zero let's say we have uh one two zero and three so for example this one okay let's forget about this one and let's say we are at this location here you know so i minus one means data we're gonna decode this one the current one as a single ladders right and then we're gonna use the dpi minus one to get the current one but zero is not a valid mapping here but that's why we cannot do this uh accumulate dpi minus one if the i is zero and same similar for this dpi minus two so to be able to decode i minor two it means that we want to make uh use this two digits as the uh as one of the letters right so which means that what is the letters for that so it's going to be from 10 to 20 26 right because a is one so and a 10 to be so the first letters that can give us uh two digits is the uh it's 10 right and then the last one is 26. yeah that's it so basically we just need to check if this s i minus 2 to i if this one is between the uh 0 to 20 to 26 then we can use this dpi minus i managed to yep i think that's it so let's do the coding here so and always right we have an uh as and then we have dp right the dp at the beginning right everything is zero right and we have a it goes to n plus one i guess right so and then for dp zero right it's one so it means that so for this kind of counting a dp problem you know we always we most of the time we initialize dp0 is one it means that if we don't have anything that's still one way to do the decoding so in the first in this one it means that if we don't have any digits there's still one way to decode which means it's nothing okay and then since the dp translation function is that dp like uh we might need to use dpi minus 2. we also need to initialize dp1 in this case so for dp1 means that you know dp1 is it's also one right so if there's only one letter if there's only one digits right it doesn't really matter so the digits can only be from zero to nine okay because for knight for zero will be uh we're gonna uh handle this separately so basically we only have one to nine and one tonight there'll always be a only one ways of decode this thing so since we have initialized zero and one then we can just start the four loop here we from range here start from two to n plus one right and then and yeah so let's check if the dp if the ice i minus one is not zero right because you know since here we are using a one base but the is zero base that's why we do i minus one and then we have dpi equals to dp i minus one so that's the uh that's to use this current to use the s i minus one as the ladder and that's why we can just use the uh the i minus one elsewhat and then for the uh for the two digits case uh if the two ladders right it's within the uh the range of 10 to 26 so that's going to be the end of the s i minus 2 to i right and we convert that into an integer if that one is within a range of 10 to 26 then we can do a dpi plus we could accumulate right i minus one so here it doesn't really matter we can you can do this as well it doesn't matter because at the beginning dpis is zero and so here we can either use like uh plus equal or equal the result is the same yeah and that's that and then in the end we simply return the dp dpn or dp of minus one yeah so that's it and then the uh the special case right special case is the like i said it's a zero case the basically the first letter is zero then we always return uh zero and also if the s is empty right then we also return zero so which means that if not s or s zero equals to zero then we'll return 0. that's how we handle this zero case or leading zero case all right so here is the okay yeah so i think that's it submit what 26 ah really uh did i dpi oh yeah sorry here dpi minus two okay yeah so i mean time complexity right it's just a of n right because there's only one single for loop here and other than that it's just like a standard dp actually it's just like the uh the stairs right problem and the only difference is that we can either we can basically we can get to the current state by uh by making the move from dpi minus one or dpi minus two and the only difference is we have to do a check for those two cases yeah and i think that's it for this problem and thank you so much for watching this video guys and stay tuned see you guys soon bye
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
926
hi everyone welcome back my name is in this video we will try to solve this question uh flip string to a monotone increasing this question is basically from lead code and it is question number 926 basically this question involves dynamic programming but we will try to see its solution without dynamic programming and we will try to solve this question basically on the general approaches okay so let's read out the question first the question states that we are given a binary string and a binary string is a monotone increasing if it consists of some number zeros some number of zeros followed by some number of ones it can be possible enough what does that mean that after one we cannot have any zero basically this is the gist of the question after one we cannot have zero we can have zeros before one the number can be of any the number can be any but after one we cannot have zero this is what question states so we are saying that it is saying that we are you are giving a managing you can flip so fi that is from zero you can convert it to one and one you can convert it to zero what we have to do we have to return the minimum number of flips to make s monotone increasing okay so we have to emphasize on this part of the question we have to emphasize like this thing we are seeing to return the minimum number of flips we are saying to return the minimum number of flips so that we can just uh make the string number on increasing once okay so before proceeding any further let us think like how a string can be used for example if we have 0 1 0 so we can ideally have 1 0 right we can add it as 1 0 this has no significance because it would be multiplied by 0 actually this one can be in neglected one like zero one zero so it would remain one zero right we can just neglect this part of the string first point is that we can neglect this part of the string second point we will just analyze by saying the questions for example if we have this question let's say we are considering this example it is say triple zero uh double one and triple zero so this is the financing given to us there are two possibilities for this there are basically two possibilities to convert this to the monotone increasing what are the two possibilities the first one is this the first one is that either we can convert it to zero either we can just zero one zero i like first one first inconsistency this first inconsistency is this one first inconsistencies this one another inconsistencies i'll gain this one by changing we had got another inconsistency so let us change that what we will get you will basically get let us change this one also we will get zero 0 so this is one possibility that is changing this both ones to zero this is one possibilities in this number of changes will be true number of flips basically number of flips will be 2 now another possibility is that we are having triple zero double one triple zero another possibility will be to change the whole string to one so that is one 1 in this we have to make in this let me just highlight this part in this we have to make these three changes plus these three changes and the output would be six flips that would be slippery but we have to make the minimum possible flips so this is what question states okay so i hope you get the question clearly now we will see the solution of it once firstly uh we will try to you know solve this question and then we will code this so i recommend you to pause this video over here and try to think of the solution once and we will just code it now okay so here is the intuition behind this question now let us try to analyze the string example we have given 1 0 let us say that this is the minus thing given to us this is not a valid one this is not a monotone increasing why because we are having one zero after one so to make it we have two possible options one is one another one is zero both are valid in both cases number of flips are one so basically we can say that the minimum number of flips are one let's see another example which is one zero now this part is valid but this part is not valid so there are two possibilities again either we can change the whole string to zero or we can change the 1 0 to 1 so in this case basically in this case we would make one flip and this we would make two flips so answer would be minimum of these that is one flip that is one play perfect now let's try to think of this string 0 1 0 now here this part is correct this particular this part is causing some problem and this part is causing some problem so there are two possibilities actually what we can do we can just change the whole string or we can convert this one to zero let us try to do this one this is the value of valid string okay so in this way we can just solve this question in big first of all our approach and then i will just move to the core one example for example we are having this uh question which is 0 1 0 so let us take initially the number of ones in the string are 0 the number of 1 in the string is 0 and the number of changes which we need to make a 0. the number of ones are zero and the number of changes which you need to make are zero so firstly i just said in the earlier part of the video that this can be considered as this one zero okay so what is the algorithm my algorithm is to scan the string from left to right henna if we encounter anyone any one which is one number then we will increase the number of ones if v and counter if we encounter any zero then we will check that is this that uh is this after anyone is this after one if yes then i will increase my change count then i will uh get my right over then i will increase my change count increase my change amount so as i said in the earlier part of the video example for hit there we are having number of ones is equals to two we having that we are having number of ones is equal to two and number of changes is equal to one because this is only the one so either we can change the number of twos or i can we can go on with the changes so minimum of those will be the answer minimum of those will be my answer basically let me just code it once let me just show you the code once then we will understand it more perfectly okay so this is the code of the that question this is a small code what we did we just uh initialized the size of the my string in the interior actually this is not required i mean you can skip that but i just made it once so initially we took the number of ones as zero we took the number of fonts as zero the number of ones in the given string okay this is the number of ones then i'm having another variable which is changes that means the zeros that should be change to one that should be changed to one if they are present after the digit one then we have to change them then what i did i basically traversed my uh string with the help of a for each loop with the help of for each loop and what i did i basically checked that is my character present in the string is zero if my character value interesting is zero then uh if number of zeros is equal to one what i did do nothing that means that if uh let's take the example of this string zero one zero now basically my character is zero but before that there is no one present there is no digit one present so these are just we can neglect this part we can deliver as i said so to neglect this part i just use this video i just use this loop so this loop is for to neglect the initial zeros to net the initial zero this part is for that else if for example if we are having one if we are not having zero uh let's say that uh the number of ones let's say that this is the part we are having one of the one and there is the number of once it's not equal to and we are proceeding at zero we are founding a zero basically we found a zero after a one so that means we have to change this so i didn't change this plus else if my c is one if my character is one then increase the number of ones and in the last we are just using either change all the one to zero or change zero to one so this is that part i wrote here right that we have to choose the minimum one so we choose minimum of changes and the number of ones and in the end we return the changes so this is the simple code which was required in the question this can be also done with the help of dynamic programming but as the constraints are small which are only 10 to the power 5 uh and we can just solve this with the help of we go up in traversal i hope you understood the question and the code as well if you have any doubt make sure to comment it out and we will meet in the next part of the video okay till then bye
Flip String to Monotone Increasing
find-and-replace-pattern
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none). You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`. Return _the minimum number of flips to make_ `s` _monotone increasing_. **Example 1:** **Input:** s = "00110 " **Output:** 1 **Explanation:** We flip the last digit to get 00111. **Example 2:** **Input:** s = "010110 " **Output:** 2 **Explanation:** We flip to get 011111, or alternatively 000111. **Example 3:** **Input:** s = "00011000 " **Output:** 2 **Explanation:** We flip to get 00000000. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
null
Array,Hash Table,String
Medium
null
442
in this video we're gonna solve this coding interview question find all duplicates in an array this is the problem statement in this problem given an integer array nums of length in where all the integers of nums are in the range inclusive from 1 to n this is the range and is integer appears once or twice written an array of all the integers that appears twice so we have to return the integers those integers appear straight in the given array so we're given an array of length n in the array we will have numbers or integers from 1 to n we have to return the integers that appears twice in the array the integer appears once uh want or twice so once or twitch we have to return all the integers that appear straight for examples if you are given this array the length of this array is three so in this area you can have integers from one to three the minimum integer can have one the maximum integer you can have three in this area of integers we have three integers one and two so here we have to return the integer that appears to H we have only one integers that appears to actually we have to written the integer one from this array in this problem we have a constraint the constraint is we have to solve this problem in a linear time complexity and we have to solve this problem in constant space complexity this is the constraint to this problem now let's take some examples for example if we're given this array of integers we saw that the length of this array is five so in this area we might have element from one to five the minimum integer you can have one and the maximum integer you can have a five we have to return the integers that appears twice in this array we see one appear storage and two appears twice we have to written these two integers as a list for examples if you're given this array of integers in this area of integers we saw we have two uh two appears twice and we saw three appears twice so we have to return two and three for this given array of integers and the length of this array is eight so in this area we might have element from 1 to 8. okay this is the problem statement hope you have understood the problem how we can solve this problem now let's assume we have this simple examples one two let's write out the index number right here so 0 1 2 3. and the length of this array is a four so we might have the element in this array for the maximum available we can have four and the minimum element we can have uh one so uh if we have uh this constraint we have maximum four minimum one what you can do we can map one at index zero to add index so one three at index two four at index at three okay so we can map one to zero two one and so on using this technique so you can solve this form let's see how we can solve this problem using a SAS a mechanism first thing we have here one what I'm gonna do I'm gonna Mark the index of this element we should have the index of this element should be zero at index 0 what I'm going to do I'm gonna Mark as uh as visited or we have one in this array then we have one again so it should be at index 0 but at index 0 we have already marked the index zero so it means that one already exists so we'll add one to our output list then we have two we see that R2 should have at index one so let's mark it then let's move forward two now let's try to Mark uh now let's check the index one we see index on already is marked so whatever you can do we can just add two to our list it means to already exist in the given array uh let's see let's stick let's take some examples so you can understand this concept clearly let's assume we are given this array of integers in this area of integers we saw we have total five elements the length is five and uh we might have the element in this range maximum is 5 minimum is one okay now we have first to one what I'm gonna do I am going to Mark the index 0 because 1 maps to zero five maps to a four okay now let's try to Mark the index 0. so here at index 0 we'll mark it as negative so we marked as negative in the negative value means the element won't exist in the array then we have two should have at index 1 to -101 so two should have at index 1 to -101 so two should have at index 1 to -101 so let's mark at index 1 as negative elements the element exist we have here two so we see that uh two I just here are two uh exist at index two now let's try to check the index of two what is the index of 2 which is 2 minus 1 that is one at index 1 we see we have already marked the index when it means that at index 1 we have uh we have marked the index one it means to already exist so we can add 2 to our output list now let's move forward we have four the index of four is three let's mark the index 3 as negative let's move forward we have one should goes at index zero the index 0 already is marked because you have negative value so let's add one to our output list this is the answer okay we saw that we have two duplicates in the given array uh those are two and two one so uh we saw that we solved this problem in a single patch which is uh a single pass algorithms uh Works in linear time complexity and it takes out of one space complexity because you were not using any additional extra space to solve this problem let's take another example for better understanding and the length of this array is eight we might have element in this array in this range from 1 to 8. the ranges uh from one to eight now let's Traverse the array first we have four let's mark the index three four minus one is three so we should have this element at index three so let's mark it as negative it means that the element four edges the index 3 is marked as negative it means that 4 already exists the index plus one already exists then let's move forward three so let's mark the index 2 as negative because 3 should have at index 2 then -2 because 3 should have at index 2 then -2 because 3 should have at index 2 then -2 we should take your absolute value okay now let's mark at the index of 2 that is 1 as negative let's move forward we see seven the in the index of seven let's say absolute value of the index of 7 is 6 let's mark 6 as negative let's move forward we have here eight the index of eight is one so let's mark it as negative let's move forward to the index of 2 is 1. we see that one is already marked it means that two already exist so let's add 2 in our output list now let's move forward we have -3 let's now let's move forward we have -3 let's now let's move forward we have -3 let's take here the absolute value which is three uh let's check the index of three uh the index of 3 is 2 which is already marked it means that three already exists we clearly saw that three already exists right here we marked at this index so here when you find out the duplicate we find out the index is marked so we can just uh we can just add three to our list then we have here one so let's have here one let's take the absolute value is one let's check the index of one that is zero is not already marked so uh we see that the occurrence of one is once or the occurrent of one is one so uh one does not appears to it so at the end we find out these two numbers two and three the numbers two and three appears twice so we will return this list this is how we can solve problem this algorithm will text of end time complexity and the space complexity is of 1. now let's implement this algorithm now let's implement the algorithm for finding duplicates first let's create our list the list will store this list will store the duplicates number so new array list now let's run a follow for INT icons to 0 I less than nums dot length I plus splash right inside here let's find out the index for our current element so end index equals to our current element can be marked as negative or marked so let's get the absolute value so nums I and let's subtract want to get the index now what I'm gonna do I'm gonna check if the index is already marked it means that our current element has a duplicate so nums here are nums index if we show this is less than zero we will add our current Uh current element to the list so list dot add nums I okay now here if this is not the case what I'm gonna do I'm gonna check if nums index is a greater than zero so let's mark that as negative so nums index equals to minus one times nums index okay this is our algorithm and at the end we will write the list this algorithm will takes off in time complexity and it will takes off one space composite because we are not using any additional space hope you've understood now let's run this code uh I saw a wrong answer it's a wrong answer so uh what's going on here in this one and okay so here we have a little mistakes we have to convert this uh first thing here what I have to do we have to get the absolute value because our current number can be marked okay so we have to take the absolute value now let's run this code now I think it should work Okay I accept it let's submit it accept it we have solved this problem this is the algorithm to solve this problem hope you have understood how to solve this problem thanks for watching this video
Find All Duplicates in an Array
find-all-duplicates-in-an-array
Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_. You must write an algorithm that runs in `O(n)` time and uses only constant extra space. **Example 1:** **Input:** nums = \[4,3,2,7,8,2,3,1\] **Output:** \[2,3\] **Example 2:** **Input:** nums = \[1,1,2\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1\] **Output:** \[\] **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `1 <= nums[i] <= n` * Each element in `nums` appears **once** or **twice**.
null
Array,Hash Table
Medium
448
228
hey guys welcome back to another video and today we're going to be solving the leak code question summary ranges you are so in this question we're given a sorted unique integer area called nums so what we want to do is we want to return the smallest sorted list of ranges that cover all the numbers in the array exactly so that is each element of nums is covered by exactly one of the ranges and there is no integer x such that x is one of the ranges but not in nums so each range a comma b in the list should be outputted as so a to b and it's going to be a string if a is not equal to b and a by itself if a and b have the same volume all right so i think the text over here is a little bit confusing the way they explain it but let's just look at an example it should be really easy to understand okay so the input over here is the nums list that we were talking about and as you can see nums over here is a sorted list and we're always going to be getting a sorted list so now the goal of our question over here is pretty simple we want to output the ranges all the possible ranges in this uh problem so let's start off and let's just go through this number by number so the first number we have is zero okay so that's going to be the starting of one range and how do we know it's going to be starting well because it's the first number so we have to start off at some place and again each of the numbers inside of nums has to be accounted for no matter what okay so now we start off with the range at 0 then the next number so the number that comes after zero is zero plus one which is one and one exists inside of num so we also have that and then a one plus one the next number is two so we have two as well so now let's do two plus one which is three so that's the next number but 3 is not inside of our num values over here so when we have some number which is not inside of values that means that we've reached a certain ending for our range so in this case uh to represent the number zero one and two we're going to have the range zero comma two so that means we're starting at the number zero then we have the number one and we're also going to be including the numbers at the ending so zero and two are included so we have that over here so far zero and two okay perfect so we don't have a three then we go into the next number which is four and like i said earlier because we already had a previous range zero comma two over here we're gonna start off with the new range so this range over here is going to start off with the number four then we're going to have the number five and then we're supposed to have six but six does not exist so in that case we're gonna have four comma five to represent the numbers four and five and finally we have just the number seven and to represent that we're going to have seven comma seven as the range so now we have the three ranges and we want to convert that into a string and the way that we're going to represent it is we're gonna have the first starting value so in this case 0 and we're going to have this arrow over here and then we're going to have the ending value so 0 pointing to 2 4 to 5 and then 7 itself because 7 does not have a range it's just a single number so let's just look at this example real quickly so over here we have zero by itself because there's no one then we have two three and four inside of a range over here then we have six by itself because we don't have the numbers five and seven and then we have eight and nine so eight and nine which are over here again everything in nums is accounted for and everything inside of our output does exist instead of nums no matter what all right so what i'm going to do is let's just directly go into the code and kind of walk through it step by step because i think the question is not too difficult all right so we're going to start off by having a results list and this results over here is going to store the range itself and by the range what i mean is that we're going to be storing these values over here we'll convert it into a string like this later on okay so we have our result i'll call it reds and now what we're going to do is we're going to iterate through each of our numbers so to do that i'll just do for num and nums okay so now in num nums we're getting each of our numbers so now what we're going to do is we're going to go so we're going to first thing what we're going to do is we're going to go to our results over here and we're going to go to the last list in our results remember in results we're going to be storing the ranges so this is going to be the last list that we have a range that we have and in that we want to get the ending point of our range and the ending point is going to be at the very ending as well so we go to negative 1. so now what we want to do over here is we want to check the next number of that certain range so the next number is just going to be plus one so now what we're going to be checking for is we're going to check if the current number we're on is not equal to that so if the current number we're on is not equal to whatever the very last element in the last range currently is then in that case that means we need to start off with a completely new range right so that is the condition that we're going to follow through and in that case what we're going to do is we're going to go to our results and we're going to append a completely new range and this range is going to be a list and the list over here is going to start off with the num inside of it okay so that's what we have but there's a few problems with this which we want to change around so one of the problems that we have over here is basically that what if we actually don't have anything at the negative one index of results so in the for example in the very first uh iteration in the very beginning results is going to be empty so in that case as well when results is empty in that case we also want to make a new list right we want to make a new range of values right so in that case we want to consider that as well so to do that what we're going to do if not a rest so if rest is empty or this condition over here is not followed and in that case we're going to go down over here and we're going to append a list which just has the starting point so the num we're adding here is going to be considered as the starting of a new range so that is the condition that we have over here and instead of this we're going to have an else condition so in that case what that's telling us is that we do have some sort of value inside of res so there's already at least one range existing and besides from that another thing that we do have is the fact that the current value that we're on so the num that we're currently on is actually the next number compared to the last value inside of our rest okay so we know that and in that case we're just going to append that to our uh res so we're going to go to the last uh list or the last range of values so negative one and we're going to append num okay so we have this over here and before actually going through with the next step we're just going to print out our results over here and let's see how this looks like and as you can see this is what we were kind of looking for so we have this number over here and the output that we got is 0 1 2 4 5 and 7. so now we have one step which is we want to clean up this output so instead of having 0 1 and 2 we just want to have the starting value and the ending value so we just want 0 and 2. that's it we don't want anything else so when do we know that one of the ranges is done right and we know that one of the ranges is done if we go inside of this if statement so once we go inside of this if statement that's telling us that we need a new range and during that if there was a range which existed before this that means that we need to end that range and close it over there and that's exactly what we're going to be doing and two thing and one more thing that we actually have to consider for is we might not actually have rest so rest might still be empty and in that case that means that we're currently at the first values that we're looking for so first we check if res so that means that res is not empty and now that we have this we can go to the last current value so press negative one so this is the last range that we had and we're going to check if it has a length which is greater than or equal to two and if that is the case that means that we do have a range so if it does have a length of just one then in that case we can just leave it as it is since it's only one number so now what we're going to do is we're going to redefine this value over here so we're going to go to res negative 1 and we're going to redefine it and the new value that it's going to be we're going to have it inside of a list and we're going to go to rest negative one and instead of that we're going to go to zero with index because we want to get the starting value now we're going to add this and instead of this again now we want to add the last value to it now the reason that i'm putting these inside of a list is because i don't actually want to add the value so i don't want to do 2 plus 2 equals 4. instead i just want to have 2 and 2 as two different elements okay so now we want to get the ending point which is going to be at the index negative one right so that's pretty simple so this over here is going to take care of everything inside of our results so all the ranges do end up getting closed up but the problem is at the very last iteration of whatever number it is this is not going to be done right this step we're not going to go inside of the step over here so in order to account for that what we're going to do is we're going to do that one more time i'm just copy pasting it at the very ending so we're going to do this right over here at the very ending of our for loop so after the for loop okay and now if you print results uh you should just get the starting and the ending values and as you can see we just got zero and two four and five and seven which is exactly what we want now finally what we want to do is we want to convert it into the way that they want us to actually give out the answer so to do that uh we'll be using list comprehension and the value or the thing that we're going to be using in order to join each of these numbers so between each of the ranges we have an arrow so let's just draw out that arrow which is this over here and we're going to be using that to join the starting and the ending value so to do that we can use the dot join method and over here we're going to be using a map now the reason we're using a map is because currently each of our values is actually a number right it's an integer but as you can see in our result over here uh they're all strings right so we want to abide by that and we only want strings so to do that we're going to use the map function we want to map everything into a string and what we're going to be mapping is going to be called x so now we didn't actually define what x is so let's do that so for x in and x is going to be each of the values inside of frets so x is going to represent each of our ranges and that should be it so now if you submit our solution it should get accepted and as you can see our submission was accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you bye
Summary Ranges
summary-ranges
You are given a **sorted unique** integer array `nums`. A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive). Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`. Each range `[a,b]` in the list should be output as: * `"a->b "` if `a != b` * `"a "` if `a == b` **Example 1:** **Input:** nums = \[0,1,2,4,5,7\] **Output:** \[ "0->2 ", "4->5 ", "7 "\] **Explanation:** The ranges are: \[0,2\] --> "0->2 " \[4,5\] --> "4->5 " \[7,7\] --> "7 " **Example 2:** **Input:** nums = \[0,2,3,4,6,8,9\] **Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\] **Explanation:** The ranges are: \[0,0\] --> "0 " \[2,4\] --> "2->4 " \[6,6\] --> "6 " \[8,9\] --> "8->9 " **Constraints:** * `0 <= nums.length <= 20` * `-231 <= nums[i] <= 231 - 1` * All the values of `nums` are **unique**. * `nums` is sorted in ascending order.
null
Array
Easy
163,352
47
hello guys I'm back right we figured out um fortnite one and um we figured out was a couple of different solutions supposedly I've attempted quite a few Solutions so we did figure this out yeah we had a look there was you know all these different you know solutions to it and uh I'm gonna go through that in another video um I don't feel like going through that in this video because this video is for something else which is 47 we're going to be coding this live right so we're back I guess you know in the business as usual and um you know so let's you know just get into it right this question I've always sort of wanted to do I guess for a long time you know I've had difficulties with it I personally still believe it's quite a challenging problem that I think certainly deserves you know a bit of attempt and um yep I'll be doing it right now not the companies have tested it for the past zero to six months so and it was apparently Amazon question and before that you know a couple of other companies would test it so you know a very early question like code so obviously we already know the topic um backtracking so you know obviously that eliminates like half the trouble already is figuring out what algorithm you need to pull out from the all the cards you know um I mean it's pretty easy to tell funny or like you know possible whatever you need permutations given the size of the constraint like that's pretty much you know it's a very small number so obviously we need this as one parameter hit index as another maybe some individual list integer as that as a pass what else do we sort of need I don't know it's hard to tell right what we need it is very hard to tell right so let's pause let me try to figure this out right given uh I'll pass what else do we need shoot what else do we actually need what is it right we needed a pass so um that's what we need termination conditions is a size or lights size if that equals to sorry what sorting it hurt I don't think sorting it would hurt right okay race dots salt arms because the time complexity of this thing is like already ridiculously big so keeping it in a sequential order is very nice because it's similar to 4.1 in like on because it's similar to 4.1 in like on because it's similar to 4.1 in like on like a pretty some abstract level right is that if we want our permutations right one two the first one the second one we only want to obtain one of them right so like what we did was essentially for foreign which is non-decreasing foreign which is non-decreasing foreign which is non-decreasing subsequence we could either have a hash stat and just cast it you know like that all we have a set for each level like he got used and after you've used it you can't you know pick it therefore we do some sort of pruning with branches right uh that's was our question and now how are we supposed to abstractly put it in this way right let's just pretend that you know I didn't have to worry about the leaves or the PC right I don't think we need this Index right foreign this is a risky move this is a very risky move right so we are iterating from zero to its length of whatever lengths for these examples we assume it's three and we just do we need to Bear anything we could ban something we could ban it right you know what I don't think I hash that of some sort would not hurt right it's gonna open up a new tab um because I do need to look up how to create a hashtag because I um I haven't done Java for a long time but you know I'm a little bit Rusty I'm like the antiviration of things man do we need that because let's say one two right I picked one I'm looking for all permutations right so how about this one two three example would make like far a lot more sense there's a small online example right so let's supposedly assume we're rocking a one two three example I literally just had a snack so we are back in business right so we're choosing essentially we're choosing for example if we've chosen one right you can't see on my little piece of paper we've chosen one as a starting number we could have two configurations one two and one should read right foreign right and you know from here onwards we kind of want to we have one two three and one three two right that's how the choosing works right if we have two as a starting we get two one three and two three one right and buy some versa what happens if we have duplicates right so for each level right we need to have a hash set I just got my head straight um band you know boom like that good pretty good right and after we go through we're gonna ban right no I'm actually I think we do I no I don't think having it here is a good idea it will cause problems I think well I do think we need to pass it in and let me tell you about it right because if we burn here right We're looping starting with what right Banning one when starting with one is good but burning Bob Benning two one we go through that isn't actually no that's also fine suppose um we could have it here I think and definitely got away with it in my opinion that's definitely doable but um I have a feeling we can do something else right so if band contains let's say um something if band contains Mom's eye right uh to index ID element we are going to be continuing right continue so we'll just prove it right we don't add anything we will just cut the branch right um and here we go pass DOT uh right if we'll have an else statement for the sake of it just to have seen safe right or go like else well I don't know go like past thought you know ad whatever were added to the pass you know Norms I that's pretty good so adding that to the pass right now we need to bend and right um I've already banned it and um I've added to the past so we are ready to go right backtrack norms I always forget that like you know you can't just add a scene to it because the list is always a reference oh that's all right so Pass and Pass that's fine pass and we're going to be passing in band right so with Ben this number here so that oh occur right yeah that will not occur wow so now it should perform um supposedly how it's supposed to there's a function called remove so this solves partially the problem but does not fully solve the problem and um I'll tell you why in a second but you know I'll just pass in new hash stats boom like that all right and what I'll do is we'll just return letting our answer right this is partially solved the problem but um does not fully solve the problem because it would it will do okay for like the one two three takes probably um it's not gonna huh that is weird pastel ad so we've added that in do we need something like P index I have a feeling we do because it's not currently working see that should do something okay it didn't it's right because wow okay that is doing some weird stuff my man foreign let's see if adding that would be anything helpful at all nope so what's actually being returned right because it did add one pair of something um it did add something back right one two three one two one foreign so we enter the backtracking algorithm we have Norms we have zero so it would start to pick from zero to whatever that is oh no you can never do that okay my bad you have to go from zero no matter what we don't need the syntax this is a terrible idea foreign also the element band okay here we go guys I finally sort of got on my head straight because I've been going through this is why Lincoln is annoying right here because you know you all have a moment of brain fart and um it happens constantly right okay I finally got on my head straight so there's the hashtag cut band values and there's also the band sort of Index right and um apparently you will do like band and that's right so the because for each one right for example if we pick starting with one right now let's say if we pick starting with two right index number one is bad so we currently go with the other index but also at the same time I we cannot reuse yeah we mostly we cannot reuse um any value that you know we have already existed oh man I don't know like just we cannot reuse the same value um because that would cause some duplicates right so like for this one two one case right 112 can only occur once doesn't matter if it's the first one second one the car only occur once right so how can we do it right is we'll only count it when we've seen it the first time and it's not the easiest no but man and index.contains all right so the index panning is only for that okay so that bans the index right um then index uh so that will ban that supposedly you know then remove we'll remove it yeah like that so oh my God what that doesn't make any sense at all right past we added to the Past we also need to remove it for the past okay that was my bad pass DOT removed I'm sorry right so we have a fresh coin start no tomorrow was I or remove passport size you want to spawn right okay that technically um okay now we've finally sort of okay we're just gonna okay that was my bad right um with all the okay um that marks our sort of first attempt on it proper um so all these runs right in like a weird way it doesn't remove any duplicates right it will perform okay let's put it this way this algorithm will perform with all possible unique permutations given this thing does not have any duplicates right if it does right okay how are we supposed to do if it does right so we are in the one starting with one right at the same level right and values right and then values all things so let's say if this value on this level has already been bad how are we supposed okay I have a feeling if we ban this in this way we're going to ban everything that's not what we want to okay let's put it this way guys we wanted to ban some of it and there's certain cases this is you know pretty annoying right so we banned this sort of value the you know because let's say if we you know if we're starting with one right like okay I wanted it to occur one okay I only wanted to reuse the other one if it's the first time so we've seen it right I don't want to I wanted to have one two right but I don't want the second to restart at the second one and having that as a starting point I wanted to cut that down completely right so we have band index that's terrific can we bear some values one way is we're just not going to enter it right that's one way foreign that so we should be able to get away with it no that's really bad because when you make more uh we may not know okay stop rude do something wow that actually even made it larger than what it was before here okay so we're back at where we begin right you know one really dumb way is literally I'm gonna have that I'd say and what I will do is I will cast it back right this is a cheating way but oh see that should perform exactly what it does now let's try that should also work I have no idea why it's you know it's wrong right this oh what foreign yeah it's really slow though okay so we've sort of worked okay we've okay guys let's be honest we've cheated with this problem right we've cheated with it so I'm gonna come back another time because it's one fitting we've cheated with this problem we've used a hash set we have officially cheated with leeco right we've cheated with it you know that's what exactly what I wanted to do but no I don't think just deleting this what's beating it up at all like you know it was to be slow but um yeah it was stupid slow in my opinion yes it is still at the very bottom of this problem okay so what we'll do is well obviously we'll do it you know we've done it um we've AC Dakota but it's not up to your standard we are going to come back with I think another video demonstrating how we are going to use Corners to solve this problem right um this because a lot of videos I will record my attempt naturally right A lot of these videos ain't really staged you know some of them are pre-recorded you know some of them are pre-recorded you know some of them are pre-recorded but they're all live footage of me attempting the problem as we got it's not like I've solved this problem I will come back and I'll pretend I'll show you outside of so this is us working out the problem together um this is why the videos are here but um either way um this is a cheated sort of attempt you know I'll come back I promise
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
992
Hello everyone and welcome back to my channel Algorithm H K Today I am going to write the code and also explain to you all the algorithm to solve all this is with different integers problem which is there on lead code it is a hard level problem And we are going to solve this using sliding window and two pointer approach ok then let's start by taking the name of Shri Krishna, we have been given an array in this question, out of this we have to tell how many number of good sub arrays are there. After that it is told that a good array is one in which the number of different integers is exactly not less than k and not greater than k. So for example 1 2 31 2 this array is given. What has happened is that there are three different integers in this. Okay and the value of We are going to solve this by using the technique of at most. I have already told this technique in my videos when I had solved Count Number of Nice Saber and had solved Binary Saber with Sum. I will put the link of both the questions in the description so that the meaning will be a little easier. From this question, you can learn the technique first because whatever it is, it comes with practice. Someone had also asked me in the comment section, what is intuition? If yes, then it is a little difficult to take the technique of intuition at most. Reaching the solution intuitively is like a slightly different method, so if you have solved this type of questions first, then only by using the technique of at most, I think, some people will probably be able to do this. Do it also, I was not able to do it but yes, if you have done it before then if you try this question again then I will put the link of those two questions, you can watch it and along with that please watch this video. Also like and subscribe the channel and you can also tell in the comment section, whatever improvements are needed, then how are you going to use AT MOST, I will give you a rough idea like this first and then on this example. If we understand by doing dry run then basically we will find out the number of sub arrays with at most k different integers. Okay, that means all the sub arrays of this array which have k different integers or less than that are all those sub arrays. We will count and then find out the number of sub arrays with at most k -1 different integers. Okay, so -1 different integers. Okay, so -1 different integers. Okay, so what will we find out by doing this. If we have taken out the number of sub arrays with at most k -1 distinct integers, then out arrays with at most k -1 distinct integers, then out arrays with at most k -1 distinct integers, then out of that, the number of sub arrays with at most k -1 distinct integers is If we of that, the number of sub arrays with at most k -1 distinct integers is If we of that, the number of sub arrays with at most k -1 distinct integers is If we deduct the sub-arrays having integers, deduct the sub-arrays having integers, deduct the sub-arrays having integers, then which sub-arrays will we get: at then which sub-arrays will we get: at then which sub-arrays will we get: at most distinct integers and at least distinct integers that are exactly How many are there in an array? Okay, now how are we going to find this? Using a hash map, we will find at most different integers. Okay, sliding window and two pointer approach will be used, so let's understand how we are going to do this. Using the example to 1 2 3 and k = 2 then we will take one answer to 1 2 3 and k = 2 then we will take one answer to 1 2 3 and k = 2 then we will take one answer ok which we will finally return and take a start and an end pointer and take a map number of I mean one at and If the number of cases is equal to or less than that number, what will we do? We will expand it. But if the cases increase at any time, we will contract it. Ok, how will we expand it? How to contract further by moving the end forward? Okay, so this will give us a window at every time in which there will be k or less different integers. Okay, and we will see that through the map, the size of the map. K through is basically fine, so let's do a dry run to find out the at most K. Here is two. Now it's fine, so start at zero. Okay, so whatever element is at zero, we will check whether it is in the map. What if the map? If it is in then we will increase its count and if it is not then we will store it with count one. Okay, so we stored it as one, okay and moved the end forward from zero to one. Okay, now the window is so many that it has become so much. Only that in which one element is coming, one is ok, so now in this window we will see that the number of elements, the size of the map till now is ok, the number of different elements, is it less than or equal to? Yes, if it is equal. What will we do with this? We will add the size of this window in the answer. What is the size of the window? Starting from the left, sorry, right, starting from the last element on the right, how many sub- last element on the right, how many sub- last element on the right, how many sub- arrays can be made in that particular window, that is the size of the window, okay. Then what will we do now, by adding plus on the answer, this end also becomes one and the answer also becomes one. Okay, now what will we do from here, we will move the end forward again and put the element on the end in the map, which is two. Is it in the map? If not then what is 2 1 and one? Here the count of two is fine so far. Now we see the size of the map again so two is that which is less than and equal to two and we will make one of two now. What is the window that is there? So again you will see how many number of sub-arrays can be formed starting from the last element. how many number of sub-arrays can be formed starting from the last element. how many number of sub-arrays can be formed starting from the last element. In this particular window, it will come 'T', '1', '2', here we will change it to 3. come 'T', '1', '2', here we will change it to 3. come 'T', '1', '2', here we will change it to 3. Okay, now from here again end. What is one? Now, one is already present here, so its count will be changed from one to two and the end will be made three. Now let's see again that the size of the map is less than equal to two. Window size, we will again add plus to it, what is the window size coming here, pay and minus start t is six, okay, this is the window size, now we will go here again, which is present on the third, two will map it here, we will see two, so first. If it is present from then we will increase its suf count. The count is two again. If it is less than equal to two then we will increase the window size plus then it will be from 6 to 10. Okay, now we have come here to the fourth index. Okay, it is on the fourth index. Now three was not present in it, so here we have added three in the map. It is okay by doing 3 and when we have added 31, now the size of the map has become greater than equal to two. It has become a greater day, sorry, okay, so what will we do now that we will move this start and whatever element was on it, we will reduce the count from the map. Okay, so earlier there was one, so we saw one. We have seen that the count of one is two, so what we will do is that we will change the count of one from two to one, okay, still we have seen that the size of the map is three, okay, so again what now, the next element is the first index. If we reduce its count then its count will become one, it is still fine, the size of the map is still three, so what will we do now, we will again remove the second index element from the map, it is fine because its count was one. Okay and if we move ahead then basically what will happen is that now the window size will be this. Okay, now from here again we will add the length of the window to it which will be T so this will be 12 Okay so the number of at most Different integers we have got i mean at most i mean all are with at most k the number of different integers we have got is the count and that is 12 and if we find out for k -1 that is one k 12 and if we find out for k -1 that is one k 12 and if we find out for k -1 that is one k So if we take out then the count will be phi is ok at most number of sub arrays with at most k distinct integers so what we will do is subtract phi from 12 t is at most number of sub arrays with at most k distinct integers and Number of Saber with At Most K My Different Integers Okay, so we will get from which will be our answer, okay, which we will return, so now let's quickly code this thing and see, okay, very simple. The code will remain if we have written it using this technique, otherwise this question is created by creating a function named at most which will calculate the number of subarrays with at most k different integers. Okay, now here int start equal to two. 0 End Answer It 0 N Map of Integer Comma Integer We will take the new hash map Now from End we will get the entire array expanded that is window Now here every time an element is present in the map then its count will be We will put zero, not zero, sorry, we will put one. If any element is present in the map, then we will put its count in the already present one by adding plus and otherwise we will put one. Its initial gate is zero and by default, what happens is that if any If an element is present in it, then it returns its count, otherwise we return zero. It is okay with that function and by adding plus and to it, we will put it in the map every time. For every window expansion, now till the map is The size which is there will be bigger than k. What will we do till then? We will keep contracting the window. If the element in the map which is at the start is greater than one, then what will we do about its count? map dot put num set start comma map dot. We will add it by doing minus and its count is correct, otherwise what will we do, we will remove that element from the map so that when we take out the size, it comes less. Now from here every time we will start plus the element which was there at the start. Have removed that and then what will be the window size and minus start plus and here we will return the answer return answer and here what will we return number of subray with at most k different integers and number of subray with at most k minus And different integers are ok, now let's run it, the length spelling is wrong here, let's run it for a minute and see what's going wrong, here I had to subtract the count from the numbers gate, I used the numbers off start minus and It must be coming out wrong due to this, now sample test cases are running and the code has been successfully submitted but before going please like the video and subscribe to my channel and also tell me in the comment section if the content is needed. Some Improvement Ts It For The Video Radhe
Subarrays with K Different Integers
delete-columns-to-make-sorted-ii
Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`. A **good array** is an array where the number of different integers in that array is exactly `k`. * For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[1,2,1,2,3\], k = 2 **Output:** 7 **Explanation:** Subarrays formed with exactly 2 different integers: \[1,2\], \[2,1\], \[1,2\], \[2,3\], \[1,2,1\], \[2,1,2\], \[1,2,1,2\] **Example 2:** **Input:** nums = \[1,2,1,3,4\], k = 3 **Output:** 3 **Explanation:** Subarrays formed with exactly 3 different integers: \[1,2,1,3\], \[2,1,3\], \[1,3,4\]. **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i], k <= nums.length`
null
Array,String,Greedy
Medium
null
198
hello guys and welcome back to lead Logics this is the House robber problem from lead code this is the lead Cod medium and the number for this is98 so in this problem we are given with a professional robber planning to rob houses along the street and each house had a certain amount of money stashed in it and the only constraint which is stopping the robber from robbing is that every adjacent House have a security system connected with each other so if the robber tries to uh Rob two adjacent houses at the same night uh the alarm will ring and he will get caught so what we have to do we have to uh we are given with an integer array nums representing where each index represents a house and the value in that contains the amount of money in each house so we have to tell the maximum amount of money what uh one can rob without alerting the police so let's see suppose we have the nums equal to 1 2 3 and 1 so if we rob this one and three we'll get four and this is not adjacent also if we drop this two and one we'll get three and this 1 and three will give four so definitely uh one and uh robbing the houses containing the money one and three is a better choice so uh the maximum amount of money is four now this problem can be solved using dynamic programming and uh we can choose the concept of pick and non-p pick in this concept of pick and non-p pick in this concept of pick and non-p pick in this like uh we Travers the entire array we go to each index and we decide two things either to pick it or to not pick it if you are uh picking a house to rob it that means you have to leave the last house which you have robbed or the money which you have robbed so let's see how we are going to do this so uh initially we are going to have two variables robbed and not robbed and initialized with zero so uh we are starting here that index equal to 0 we have Rob equal to Z no Rob equal to zero and then we iterate and we check if there is a possibility we can rob the house one then how much money you will get if you do a new robbery you will get one amount of money and if you do not Rob this house this particular house if you leave this what you will get uh currently zero because no Rob is zero here now when you go to the next iteration this new Rob becomes the Rob and new no Rob becomes the no Rob because for every house you uh move ahead uh the Rob values changes so this one comes here new Rob comes in the Rob and the new no Rob comes in the no okay now for I equal 2 I equal to 1 we have Rob value equal to 1 and no ra value equal to zero so I here now so we are here at two so at two if you do the robbery how much money you can get so if you will rob the this house that means you have to leave the last robbed house so if you leave the last one you will have only two okay we have only two coins let's say and if you do not Rob this two how much would you then in that case you would take that one so that one comes from here okay now we have the new Rob and the new no Rob done for this particular house we move to the next house the new Rob becomes the Rob new no Rob becomes no Rob two comes here one comes here now we are at the this house now if we pick three we have to leave two and we have to pick one instead and if we do not pick three then we have to pick two in the in that case so if we pick the house zero and house two that means three and one so the new Rob value becomes four and if we pick if we do not pick then we'll only have two so we only have two here okay we again have the new Rob new no Rob value replace it move ahead to the last house now coming to the last house if we pick this then we have to pick the two so that means the new Rob value will be three and no not uh actually this is overlapped I mean swept here it will be three and here it will be four you can understand so if we drop this particular house here it will come three because it will be 1 + 2 and uh not because it will be 1 + 2 and uh not because it will be 1 + 2 and uh not dropped if we do not drop this one then in that case we'll be having three and one so here it will be four I'm sorry for this like swapping but you can understand it I'm telling you so after this what we have to do is that we have to only check which of these is the maximum and return the Maximum Auto these and we are done with the solution so just use two variables Rob and no Rob iterate through the each house and then uh check for each and calculate the new Rob and new no Rob and finally return the maximum out OB so this is the uh approach now let's come to the coding section but before that do like the video share it with your friends and subscribe to the channel if you're new to the channel so let's we want uh variable Rob equal to Z and new uh no Rob equal to zero and we have to iterate in the array so we are iterating the array and here we have new Rob means you are performing the robbery and if you're performing the robbery that means the last house which you went you did not Rob so no Rob plus nums of I and if you do not rob that means you can pick the last off so in new no Rob will be m. Max of no Rob and the Rob and uh the Rob becomes the new Rob uh yes the new Rob and the no Rob becomes new no Ro pretty simple now afterwards simply return mad. Max Rob and no Rob let's see if it turns I'm sorry for the sound caused due to the construction in the next house here it passes the uh test cases with a good time complexity and a good memory complexity the time complexity for this solution is O ofn because we are traversing the array only once and the space complexity is O of one because we are only using variables that takes constant space you can also check the uh my C++ Java and python Solution the uh my C++ Java and python Solution the uh my C++ Java and python Solution by going into the solu ation panel here and check this solution here you can see the intuition the approach the complexity analysis Java code C++ python complexity analysis Java code C++ python complexity analysis Java code C++ python JavaScript and yes do remember me to aort so I hope you understood the logic very it was pretty easy and you can explain this to the interviewer in an interview and he will be definitely impressed by your solution if you do by this way so all the best for your uh journey I hope you like the videos please share it with your friends thank you for watching the video have a nice it
House Robber
house-robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 2:** **Input:** nums = \[2,7,9,3,1\] **Output:** 12 **Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 400`
null
Array,Dynamic Programming
Medium
152,213,256,276,337,600,656,740,2262
326
Will hand over to everyone welcome back so friend this was our problem 24th August so we see that this power of three lights which we have seen behind the problem of power off and so this is similar to it just in this we started checking onem this power of three four note So in that we used to check whether it is power off or not ok so for example we have angry bird 2017 so how is our output ghat Renu Kushwaha 363 liye 353 with 7000 power off free sleeping check friends 120 10 not possible to right 0538 108 10000 transfer subscribe no additional power of three subscribe to tight to us again flop giver hai kudi solved without clothes and agar jaan so let's see first brute force approach using while loop and water tank will do it in soaked fun time complexity right for example to Have given with strong bases so we have to check whether this is another option or not types and this after big 7 minutes of power trailer so what we will do is after the file and divide this point and move it to the side until we 30 That we divide by three Right 2017 So this knowledge on these If vote trouble Balhara And if our reminder comes zero in the last Mute the power of three If any number is a power of three If it is a tight free power Then it is on reset visual It should be a complete hit show, if ours is good, then Amma take the volume, write down the volume like what is the volume, note 10 goes to our end, we will check, unless our end is 30, it is fine, then we We will divide by three and then if our final reminder comes to zero then at last he will return to life that honey singh good night so let's and torrent this defeats working or not show what they are doing this soil away any sort 10 and Mode free is equal to zero if we divide that and set our reminder behind golden night and 1628 torrent then this will be ours brother with the help of people right then this flop giver negative role without loop sorry version or 21 running so let's See how they can be solid without using any loss or easy method like this, so let's see this and the value of the note on this is one we have one 162 60467 Okay, this is our maximum volume which is our any given thirty on the terrace One minus one, this should end, okay, so this is our value, this is the highest, this is our value, which is the highest from this point, which is less than this. S Tourist 131 - Mental, you have to spread it out and Tourist 131 - Mental, you have to spread it out and Tourist 131 - Mental, you have to spread it out and see, simply Google it. The fabric is fine but this is our value, then nine on this is our Maxwell which is less than this, okay, from Tourist 131 Miles From, if you see the value of 320, then it will accident it, okay Tourist 131 - will accident it, okay Tourist 131 - will accident it, okay Tourist 131 - Man That's it, we got this first clue, okay, which is tourist 431 - which is less than the mind, which is tourist 431 - which is less than the mind, which is tourist 431 - which is less than the mind, which is fitting, meaning, 3220 time, okay, so we will have our whatever mp1, Mala 2017, okay, so divide on that. We will try it, okay if our mode comes to zero, reminder comes to zero, that means it is power off free, not the other way around, okay, then it will be done in the phone simply pink, so now what will we do, we will do 200 in simply massage solution, wall dhari builder. Return i soft condition is and beaten 10 and mon active 162 261 146 700 on any wax paper w3dys quarter inch good luck our maxwell that is fitting in it tourist 131 - fine by value fitting in it tourist 131 - fine by value fitting in it tourist 131 - fine by value it is just less it is value and mexico if If you write Pimple Twenty then it has been made an accident. Tourist 31.1 it has been made an accident. Tourist 31.1 it has been made an accident. Tourist 31.1 is okay, so whatever is our end given, okay, then we will turn on the mode and see. Okay, if our reminder comes to zero, then we will do pro vitamin in it, meaning in that case. This is the meaning of power of free, like this is our 119. Okay, so if you divide it by 227, it will become totally divisible. Our reminder, zero will come, so you can see, I will explain it, so what is ours and what are your additional warnings and we We are doing this, it is 2017, so if you look at it in 2017, then this is our three interests, right, so it is totally divisible, so you can see, now, when we have this same first, then it becomes - right, which are nearby. So it becomes - right, which are nearby. So it becomes - right, which are nearby. So sorry attacking mode tight we are turning and seeing neither it is totally divisible nor it is so it will go to 316 ok like this if free good night ends Ritesh Kumar Noida then this person its on Sikkim so our reminder has been done zero Ahead it is okay after turning it to zero it is okay museum is totally divisible right 1 is so in that case well-written audience amount is right so let's fight case well-written audience amount is right so let's fight case well-written audience amount is right so let's fight to remedy code simple for soaked fun time of complexity right to have sold according to the form given in This is without law and order situation right side to submit a that surya submitted successfully 100 thank you so much for big is this deception note please aap kitna comment box and you can connect with meaning in english tree boxes and do n't forget to check out Videos too please visit the channel and stay tuned for videos thank you so much
Power of Three
power-of-three
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`. **Example 1:** **Input:** n = 27 **Output:** true **Explanation:** 27 = 33 **Example 2:** **Input:** n = 0 **Output:** false **Explanation:** There is no x where 3x = 0. **Example 3:** **Input:** n = -1 **Output:** false **Explanation:** There is no x where 3x = (-1). **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Recursion
Easy
231,342,1889
318
how are you Well now I'm going to try to explain this code challenge Not that code challenge that actually has been put as medium but I could see it as a little complicated no because at first glance it seems easy No but it appears in quotes easy No but when you really break it down you find that there is a certain difficulty so it says maximum product between the quantity between the length of the words no Then it says given an array of words not of words of strings it returns the maximum quantity of the multiplication of each letter not of each letter of each word by of each word letter where the words have nothing in common no and if this condition does not exist return zero Here is every three examples the first example there we see an array and where the Answer 16 The second array of string words actually says four words here and the third array, since they are all the same, none of them are different. The answer is zero, no. So let's see how we solve everything in code. I'm not going to try to do my best to explain it Well now I'm going to show you the logic behind the source code. Not always in these challenges you have to analyze first and then enter the code, if not we are lost then these challenges as it was against time the first thing that comes to mind is to calculate the distance between the entire array, basically the entire array, not the starting array, for example, in this case it would be the distance between ABC W with b to Z and with p to Z with Fu with bar and with bar with x letters no then null bar with not enough then what you have to do is apply the reverse thinking approach notation as it is called blocks no and only Search in the indexes where there is content in this case it would be 0 and 4 But since we are in we have to apply this algorithm to n cases then You have to put them in N cases no So this is not enough so you have to apply the Well since I have this information I am going to use this arrangement this stack and this stack or I have two stacks now to use it to use and then I am going to put the information that I can collect from this extract and the information that I can collect from this array, put it in another stack and find the maximum value and I am going to do that by going through this array, this extract and this array with an initial pointer that the code is like j and with a final pointer that is as a counter and that the initial pointer is going to be increasing the final conter is going to be increasing and the final pointer is going to be decreasing and they are going to sweep away all of the stack and the initial arrangement of that way we make sure that we cover everything all the cases So that's basically what we do here so in the first entry in the first If So to speak we are going to search only in this stack so that the distance of bird with f would be two times one two that's why it puts the value two here now we don't go to the second If to work with this arrangement no initial mail and the initial pointer moves one J plus one and with minus no counter minus one So it would be we would be in veaz with three the content of one with three is zero it is null well no then it puts zero but there is a way to compare if there is content in the initial array So the initial pointer is already in the J is already in Fu and the another is already in a bar so three times three nine and that is what we have what we see here no two nine zero nine no So we are here at 9 Then the next cycle comes in and it and there is nothing to compare and I already know in this case the initial pointer has already been crossed and it has already been crossed with the final pointer compares there is nothing to compare so it sets zero and with the computer the final pointer was in bar now it is in Fu and the initial control is in bar so three For three nine, of course, it is a redundant piece of information. But you still have to put all the cases, the first cycle does not enter, the cycle runs again and the first cycle enters, the cycle enters and there is nothing to compare, here we would be comparing the one. three with one there is nothing to compare Zero actually zero and the final pointer would give us at the end 16 not in the comparison four by four sixteen Why Because is 4 and here we have a b c let's see the length of here it is four and here as we have drawn the similar ones, taking us out also gives us four times four sixteen the maximum value of the stake is 16 let's go to the second case which is less complex no so here when comparing a with b a with a b we get a b and that's how it is and then a with b with c and with d it doesn't get null then we get the one from El Seco de with cd we get CD with bcd it doesn't get CD and bcd with abcd it doesn't get bcd so we have to compare when the first stack with the money then this case is even easier because here there are not so many anymore so here we have even more useful information in the first cycle enter and compare a with b c d is one times three in the second case already moves the initial pointer moves a with b moves with a with b with c with d Then it would be a with b with a with b it would be 2 times 2 4 between the first cycle again between run cycle between the first If and we work with that stack then we already have that the pointer is here with cd not a b with cd is 4 2 times 2 4 and we go to the second stack then one is if we were here with ABC now it goes to compare the abc with the CD compare with the CD not the for the ABC with the CD then we have two times two we are here in here So we have Ah we are comparing we have entered first Loop we have entered here we have got three the four if we are here it is because we are here is because it came to us here we are ave now the next one is this here is ABC we have run two So it would be one two I have for ABC with CD with headquarters what does it have in common to be two three times one three of course three times one three that moment three the distance of three times one three then enters the cycle and we are comparing there is nothing to compare here zero but then we are comparing the second look looks more difficult to compare you will see why it was the code no so the we are here So we pass the pointer here CD cde CD and the other pointer has already passed here no so here what I would do is three CD three the other pointer actually the other pointer is already the other pointer 1 and 1 2 3 and up to here the other whorehouse then three times one three so each one goes three then he enters again he enters the Ford and nothing enters he does not calculate anything which I do not calculate anything but the second enters if he enters the second Ford and the pointers have already been found initial or the final control are already They are already scattered So we have to yield by abs4 And we have here the point the pointer in the four and we already have that the bird by CD is four and finally we have that the to the pointer final is already in a and the pointer and the final pointer has and the initial pointer is in abcd so then it is three times one bsd because the anus The a is the one that differentiates them So the BS then three times one three and it comes out this array and the maximum value is 4 not the maximum value the first radius of 16 and the last case is the easiest No because the a is compared to put the a with the a and the A what is the obviously one of the premises The objective of the problem was that it be the sum of the letters, not the sum of the length of Word, and for Word times the length of Word J, the length of two words that do not share the same letters, then here, since they all share the same letter, then we must He doesn't find anything, he doesn't. That is, he enters the Ford, he enters the first among the first IFE, he doesn't find anything. In other words, he doesn't do anything, he enters the bottom, he doesn't do anything. And well, we don't ever fill the second stack. That's why in the end, zero comes out, no. and that is what you are asking for, it is not what to return zero quickly let's see the code or the code Here it is in the Solution class format a Solution class more product Here is the definition of the first array is car root is two array and here It is there to create the first stack, no, so what we do here is we make the intersection between the intersection to compare the word one. So to say, String 1 with String, the String in position one, that is, it distinguishes position zero with String. in position 1 no And so on until we get to the end and we put it in a stack no And we put everything in a pond then the one comes here to create the second stock we make a Ford another forum where we go through the second one is like I told you We have to use reverse thinking, that's why we use the second stack as a reference, not what we do in the first stack is we have the variable stack where we go through the initial pointer as I told you it was the proteo j and the final pointer which is with is the pointer final we do not take the length of the stack minus one so that it puts us in the last position and the pointer and the this variable share 3 which is what they share what it does is the reverse thinking is coming which is first we compare what the initial pointer with the final pointer and then we occupy the initial pointer plus one and the final dropper minus one in the same iteration no that's why it's a bit abstract no when explaining in the analysis no then Yes but it is but It is important to do the second comparison the internal comparison We are going to learn to do the external operation and other internal compression by incrementing the initial pointer and decrementing the final pointer to be able to work on the content of the initial root and the other The initial pointer that increases by one and decreases by one is to be able to work on the stack, not where we have the differences. So if it is null, what it does is calculate the distance of the stack at position j and the distance and set the variable a and the distance in the position in the final position not in the final pointer and The answer is a by b and that is put in the extract now if in the if the pointers which is the pointer plus one and the pointer the internal pointers to say it because one is the external pointers these are the internal pointers if the internal pointers here It would be good for me to tell you to comment on it quickly not internalized starts the end pointers and the same thing could be here not starting starts the end pointers Not here I wanted external pointers and here the Internet is easier to understand so here what we do is we calculate J plus one but already in the string no longer in the stack but in the String not in the starting chain not Word and with minus one and the initial load and a for B in the stack then counter minus so that it increases here it increases by one and here it increases by two no basically then as it doesn't say the stack we put 0 otherwise we calculate the maximum value of the stack 2 no Then we are going to test it no Then we have the first input no which is this and the answer should give us 16 we are not going to see Well that is something expensive obviously it did not give the truth is the problem is not Then it gives us sixteen as it tells us No now we are going to call the second example Generally when they give you the three examples it is because all the cases are already there not because you have already fulfilled so then no four here four and in the last one you have to give us zero Well I hope it has helped you in any way the code is going to put it in the description
Maximum Product of Word Lengths
maximum-product-of-word-lengths
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two words can be "abcw ", "xtfn ". **Example 2:** **Input:** words = \[ "a ", "ab ", "abc ", "d ", "cd ", "bcd ", "abcd "\] **Output:** 4 **Explanation:** The two words can be "ab ", "cd ". **Example 3:** **Input:** words = \[ "a ", "aa ", "aaa ", "aaaa "\] **Output:** 0 **Explanation:** No such pair of words. **Constraints:** * `2 <= words.length <= 1000` * `1 <= words[i].length <= 1000` * `words[i]` consists only of lowercase English letters.
null
Array,String,Bit Manipulation
Medium
null
41
foreign is called First missing positive we are given an unsorted integer array called nums and we have to return the smallest missing positive integer we have to implement an algorithm that runs in linear time and we cannot create any additional space so we our space complexity should be constant now for the first example we have the array one two and zero and the first positive number because we have one and two the first positive number that's missing is actually 3 which we return as the output of the function now in the second example we also see that we have negative numbers but we can basically just they are not of interest for us so we can basically just skip that now we have one three four so between one and three of course uh two is missing so that's the first uh positive number that's missing one is in the array two is not so we return two now for the third example we have a uh almost a sequence uh the number that's missing here is 10 but we are not interested in that number we are interested in the first number that's uh positive and that's missing in this case it's basically one because we don't have one two three but the one is the first and the smallest one so we'll return one as the result of the function now for the length of the array that's given us uh and that's given to us by the problem statement it ranges from 1 to 10 to the fifth and the distribution of numbers inside that array are ranging from the minimum and uh to the maximum integer now there are a few tricks that we have learned so far during the easy and medium questions and there were some similar questions to this uh there is step one uh trick that we used uh where we marked the corresponding index for a number so for example if we have number three we would Mark the corresponding index and we will get the index by just reducing the number by one so in this case it would be two and we would Mark the element that the index tool by either making it a negative or basically just adding the length of the array to it and so on problem is that we have negative numbers but negative numbers are really not of our interest here so we can basically just in some way discard them somewhere in some way mask them so that's the first problem that you're going to solve and solve that problem we will basically iterate over the array and we will find the first positive number and if there's no positive number then we know that the first missing positive number will be one so we can return early from the function but in this case when we start iterating from the start of the array we will see that the first positive number is three so our first operation will be transforming the initial array to the following array so we will if the number is positive we will just copy it over but if it's negative we will transform it to the first positive number which in our case is three so that's the first we sold basically the first problem because these two numbers now all the negative numbers so basically point to the index that corresponds to the first positive number that we found and we can allow that because we will be only changing the sign of the corresponding the element at the corresponding index wants and that's that basically brings us to our second uh second step we have to mark that the element exists inside the array and we will do that by marking the corresponding element at the corresponding index by making it negative so for example our second transformation is that we will Traverse through the array and we will find the corresponding index and we will mask that number that the number exists by making that element of the corresponding index negative so our first number is three and uh we will basically just make the first uh the index that matches the num number three which in our case is two so we will just make a number at that position negative so we'll make three angle I will just copy over the all the numbers uh our second number is four and the index that corresponds to that number is three so we'll just make the that number negative uh next we move to the number three but no it's not three it's minus three but we can always use uh the absolute value and because it points to itself and the number is already negative we will not do anything we already know that the number three is appearing in the air because we marked the corresponding index element of the corresponding this negative and the last number that is number one and in this case we already transform it but we'll use the absolute value and we will map it to zero and we will make the element that index 0 negative now when we Traverse the array again the transparent array we will start from the first element of course and we will basically search for the first positive number once we find the first positive number we will do the inverse transformation to find the corresponding element that is missing because we have never uh because we have never found it and we never marked its corresponding index negative so in this case the first positive number is 4 it matches the index one and we basically do one plus one to find the element that's missing and in this case it's the it's number two so number two is the first element the first positive element that's missing and if we go back to on to our array we see that we have one we have three and four but two is missing now it's important to know that we can have elements that uh map to an index that are that is outside of our uh of our array so for example if we have 100 it would map to index 99 which is out of boundary here so we have to be careful uh when operating on numbers that correspond to the index that's out of boundary for our already but for this problem it doesn't really matter because we are searching for the first positive number and if we have all for example if we have a second sequence 100 101 and 102 we will not map it to any of the uh of the indices and then we Traverse the first positive number in the last step will be 100 and we know that uh that element is the index 0 so the corresponding element is one and the number one is the first missing uh First missing positive number and we can have an array of for example length 3 where we have one two three so all the elements uh from one to three are there the basically the next positive element that is missing will be the element that's um uh the length of the array plus one so in this case it will be number four and the last step the last thing that we can have the lesson here is for example if you have one two and then uh 100 for example so 100 will not point to anywhere and uh one and two will point to the first and the second number so we will know that one two exists the 100 will be first positive uh number and it will match to the in our last step it will match to the index tool and when we use this index to find the number it's missing it will be two plus one which is equal to 3 and we know that the first positive number that's missing is number three now because we are only traversing to array several times we have the time complexity equal to uh linear to the length of the array and for the space complexity because we are operating in place on the same array we have constant space complexity which is required by the problem statement declaring uh n as the length of the array and our first positive will be marked as zero we will first reverse through the call array in order to find the first positive number and we will use that first position our first determine if we have any and if we don't have room just return one because that's our first positive number if all numbers in the input array are negative if not we will Mark every single negative number in the input array as the first positive number that we have found so basically we are discarding the negative numbers next we will Traverse through the array again and we will use the absolute value to find the matching index if it's in boundary of the input array and when we find the corresponding index we will turn the element of that index negative that will serve as a mask to know that we have found the corresponding element so if we mask the element in index 2 we know that somewhere in the array we have a we have found Elementary and basically our last check is to Traverse the array and see uh you can see what's the first positive element and that first positive element it's at the index that corresponds to The First missing positive number so we will just use that index plus 1 to return that number if however we don't return from this four group we know that all the numbers uh ranging from 1 to n where n is the length of the array have been found inside the array so basically we can just find we can just return the next element which we do by just incrementing the length of the array by one
First Missing Positive
first-missing-positive
Given an unsorted integer array `nums`, return the smallest missing positive integer. You must implement an algorithm that runs in `O(n)` time and uses constant extra space. **Example 1:** **Input:** nums = \[1,2,0\] **Output:** 3 **Explanation:** The numbers in the range \[1,2\] are all in the array. **Example 2:** **Input:** nums = \[3,4,-1,1\] **Output:** 2 **Explanation:** 1 is in the array but 2 is missing. **Example 3:** **Input:** nums = \[7,8,9,11,12\] **Output:** 1 **Explanation:** The smallest positive integer 1 is missing. **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
Array,Hash Table
Hard
268,287,448,770
1,815
hey what's up guys uh this is chung here so today um number 1815 maximum number of groups getting fresh donuts um this one is a quite difficult problem so basically you're given like uh a groups of people right so and there's a donut shop that bakes donuts in the batch and batches of the batch size right and then they have a rule that you know they must serve all the donuts for a batch before serving any donuts from that to the next batch right so basically what's what this one's saying that you know we have a group of peoples right coming into the uh to the donut store and in the donor store the donuts is served as a size of batch okay and when a group visits the shop all the customers of the group must be served before serving any of the following groups okay and then also a group will be happy if they all get fresh donuts which means that there is no leftover donuts from the previous group and you can freely rearrange the ordering of the groups and return the maximum possible number of happy groups after rearranging the groups right so for example we have a batch size of three and then we have a six group of people whose number are one two three four five six and then the hyper group the maximum hyper groups we can get is four because you know first you know obviously you know with three and six right those groups can be served at the beginning because they can be divided by the batch size right so then we have two uh hyper group already and then with the third one with this uh the remaining one two and four five right we can rearrange in a way that you know uh four two four and one five right because in this case you know let's say if we serve the group six first we serve groups three second then this will be two happy groups already right and then if we rearrange the remaining four groups in a such a way that you know let's see if we have four two and one five right so we have uh one's happy group second happy group and then the third one is also a happy group right because you know there's no leftover from the previous one but the uh this but this one is not hyper group because you know this is four people coming in right so the previously previous group number is two but the bar batch size is three so which means when the group four comes in right so there will be one left over donuts from the previously previous group that's why this one is not happy one and but this one is also this one is a happy one right because uh 2 plus 4 right actually 2 plus 4 equals to 6. right because which means that you know one donut from previous group and then a new batch size uh is three we can serve exactly four people in this one that's why you know the next in the when the next group comes in there will be no leftover uh donuts from the previous group that's why this one is the next one is happy but obviously the last one is not happy that's why the total number of the hyper group in this example is four right and then another example is like this one like four i think the batch size is the uh it's nine right and then the group size is 30 but the groups are of people is pretty big 10 to the power of 9 right so to solve this problem you know so when you see like this kind of a pretty small number of the s of the restriction here so most likely i think this problem will be np problem right and which means we have to somehow brutal force all the possible scenarios with some optimization if needed okay all right so we have to make a few observations here you know uh i think the first one is that you know since the group number is pretty big right we can simply it's easy to notice that you know we can always convert this group number into a modular of the batch size right because it doesn't really matter how big the group number is all we cares is a remainder after dividing by the batch size this is kind of obvious right that's the first one and second one i believe we have already uh talked about that basically the second observation is that you know if there's any uh group people that can be divided by the bad the batch size then we can simply serve those groups uh at the beginning because we know those are those will be the hyper groups all right so which in this case is second six and three right and then the last observation is that you know after uh eliminating those groups people that can be divided by the batch size with the remaining groups of people here if there are two groups that can uh the total of the group of peoples that can be divided by the batch size then we want to group those two groups together for example this two four and one five right the sum of those two groups can also be divided by the batch size which is three it's kind of obvious that like i said since they're the total sum is the same right the sort of the total sum it can be divided by the batch size and then the next one the next group after this the bigger group here will definitely be uh be hyper group so that's going to be the third observation right so basically ours our logic will be first we find first we convert uh this group number up to the remainder of the after divided dividing the batch size and the second one is that you know we find we remove all the uh the groups that can be divided by batch size third one is that we uh we also find how many groups we can find right and who's like uh the sum right of the two groups can be can also be divided by the batch size and then after this these three steps the remaining stuff we have to we don't have any other options but to brutal force all the possible combinations of that right so um cool so i think let's start coding here and i'll try to explain a little bit more okay so and so we are first win the length of the groups right so like i said first we simply convert groups into a remainder version of that divided after dividing by the batch size so we have a num uh dual modular of the batch size right and then for num in the groups right if the num divided by the batch size it's not empty right because here i mean i uh i also only convert uh like re i'm also removing the batch size the groups that can be divided by the batch size so that's why you know at the beginning we already have the answer right so at the beginning the answer will be starting with this one so basically this answer at this time will be the has already have the groups that can be divided by the batch size okay the batch size right so second one is that we need to find the two groups sum can be divided by the batch size right so to do this i mean what we can do here is that we can create like a frequency uh dictionary here basically i'm using a frequency of the counter here right and for basically for each of the group for and this frequency uh dictionary stores all the count for each of numbers right then we can see we can just loop through each number in the in a group right for num in groups right so we have a so for each of the numbers we want to find like a matching number of that right which means that you know the match number in this case will be the batch size uh subtract number right and then i'm going to have like a match equals to zero so be careful here actually you know if the match size let's say it's six right sorry if the batch size is six and then with number one we hope we're trying to find five right and if the number is two we're trying to see if there's a four exist in this like groups but this three is like special one because 3 actually it's also 3 right so what i'm saying is that you know like this so basically the match number will be the minimum of the frequency of the number and then the frequency of the match number right because let's say in this case right so if we have two ones and the three fives in this case so how many groups how many pairs we can find in this case we can find at most of two because we need to get the minimum amount of two counts right and then with each of the match here you know we have the answers gonna be the match right because we know we have find those groups with each mat with each pair of groups we know we can have definitely get one more uh happy group basically after this current pair right and after that you know i'm going to i mean decrease this frequency is the match right frequency of both two numbers right so that's going to be the match number divided by the match right but like i said you know there is a special case here you know actually so when the number and the match number are the same in this case is three here in that one we cannot use this minimum because that will double the matched number because with three and three actually let's see if there are like seven threes in total right so if we do a minimum of those two numbers so the match will be seven but it should be instead of seven it should be three right because it's divided right three match three that's why you know we have to do a simple check here right so if the match number equals the number and then the match is what is the number divided by two right else if they're different then we can use this like the minimum right so because and so the reason i look through from the groups here instead of the frequency itself it's because you know the uh let me think so actually from the group inside of the groups here actually what we can do is we can just do a number from this one actually from one to batch size actually you know yeah we can also do this one right because you know the distinct values in the groups can only be as many as a batch size right so as long as we can sloop through from one the first one to the last one this one also works right so okay cool so and oh and the reason i didn't look through from frequency because you know if we do it in python at least you know while you're changing the size of the frequency the uh the python will basically throw and then you throw you an exception that's why i have we have to look through from different data source okay so and after this one you know what's left so what's left in the frequency or any frequency that has still has a count equals to zero sorry greater than zero will be the groups that we didn't find them at if we didn't find the match right so and those are the groups we need to brutal force right so then we have a new groups here so for num and then count in the frequency data items and the new groups will be the num times count right so that's going to be the total new groups here all right okay so for these new groups like i said you know to brutal force that we have to use like a dp solution right so basically we try all the possible scenarios we try at each of the loop here you know we try to pick each of the number and then with each number we have like the uh so basically the dp right so the dp state for this brutal force will be uh will be two parameters so the first one we need to either groups actually we need to remain actually so and then we have groups here so the group is pretty straightforward right because now after picking a group right so these groups will be updated okay that's the ones and the second one is the remain so the reason we in the remains that you know we need to know when can we add uh increase the hyper groups right so we increase the happy group when this remain is equal to zero because after every time we pick a group this new remain will be updated and we increase that hyper group when this remains zero that's why we need this two uh state of this dp function right so for the dp right so and let's do a dp here so the first one is the remain second noise of groups right and then uh i'll use the like python's way of doing the cache here right and okay so assuming we have stp function here so in the end right so we in we simply it returns answer plus right plus the dp of what at the beginning the remaining is zero right and then the group's gonna be the new groups right but in python you know the it cannot hash a list type that's why we can convert this one to a tuple right so that can be it's so that it can be hashed right um all right cool so now let's implement this one and so the to add the exit uh condition if not groups right if groups not empty we simply return zero right else uh we pick each of the at each of the dps function here we try to pick each of the group and then after that we're going to have like a new groups right so uh so to do that i know i'm going to convert this one to a list here you know i think there could be other better ways instead of converting this like tuples and from list to topo and from topo to list i believe we can also use like um like a beat mask maybe but 30 i think 30 is a yeah i think we can try also use like a beat mask in this case but uh that's just another implementation but i'll just leave i'll just keep this way here since it's kind of a little bit more uh straightforward and so we have answers starting from zero right so we try each of the we try to pick each of the groups in range of the length of groups okay and after picking that groups you know the new groups will be so i have next groups because the groups of i right plus groups of i plus one this one and i know this part is a little bit slow but you know i'm just showing you guys the idea here right and then we have a new remaining right so the remaining will be the what remaining plus groups of i right and then we do a modular by the batch size right and then the answer will be the max we update the max for each of the groups and they're going to be the answer that you know we increase the groups happy group by one when the remain equals to zero right and then the remaining will be the dp of the new remain and then again tuple of the next groups right and then lastly we simply return the answer so keep in mind that you know we're checking the remain not the new remain here because you know remain means that you know we're trying to see with the current groups because if the remain from the previously previous uh group is zero then it means that we can have like one more uh one more happy group starting from the current group that's why we check this remain instead of the new remain here yeah i think that's pretty much it is right and uh yeah so let's try to run the code here accept it all right submit cool so it passed right um yeah i mean that's basically it this problem right i mean it's um it's a pretty difficult one i would say that you know so first you know we have to basically find a few patterns like the first one is the uh we find the uh the groups that can be divided by bad sides and the second one is that you know we have to find like a pair right that who's who can form like uh another groups because if you don't do this you know if you don't do this one and you just simply pull force everything after this first step you will get a tle because with this kind of length of groups here you know and with the uh the possible state here it'll be too much but if we uh can improve optimize our solutions by removing the matching pairs right and then the remaining one the remaining new groups will be pretty small which can be brutal forced by using this kind of np dp solution here cool i guess i'll just stop here and thank you for watching this video guys stay tuned see you guys soon bye
Maximum Number of Groups Getting Fresh Donuts
checking-existence-of-edge-length-limited-paths
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` customers that will visit the shop. Each customer will get exactly one donut. When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group. You can freely rearrange the ordering of the groups. Return _the **maximum** possible number of happy groups after rearranging the groups._ **Example 1:** **Input:** batchSize = 3, groups = \[1,2,3,4,5,6\] **Output:** 4 **Explanation:** You can arrange the groups as \[6,2,4,5,1,3\]. Then the 1st, 2nd, 4th, and 6th groups will be happy. **Example 2:** **Input:** batchSize = 4, groups = \[1,3,2,5,2,2,1,6\] **Output:** 4 **Constraints:** * `1 <= batchSize <= 9` * `1 <= groups.length <= 30` * `1 <= groups[i] <= 109`
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Array,Union Find,Graph,Sorting
Hard
1865
1,198
That's what has happened Hello friends this Ramkumar Mantri welcome to our channel fitness Guru group Next question read smallest element in all row from this matrix rights given so during number of Research Institute of Management in subscribe and what is the smallest subscribe list number 198 subscribe The Road Elements for Increasing Order 100 Subscribe to 270 Increasing Order Returns Massage Common Elements and All Roads Should Be Rich Nominal Middle Management Software Apps How Many Drops After and Research Writing by Observing Like and Share The Element Which Has Only One Element Which Come Under Five 14 2011 Small Five York All In Sequence Rate Mins In Increasing Order Tracking Knobs Or The Juz More Than One In Some Cases The Near To Find What Is The Smallest Latest Updates Later To Zinc Difficult Way Guest Us Entry Easy Way This Tours To return of the day half sweater approach has been up to the approach of welcome to approach share the best one's element account statement enrollment to dial singh dhindsa research on aisa kahne walon explain the complexities ulcer how to enemy will speak now hindus To Meet It's Something Like Seem Like Subscribe 100000 Subscribe Maintain The Element Subscribe The Amazing spider-man Measure Subscribe Amazing spider-man Measure Subscribe Amazing spider-man Measure Subscribe My Channel Like This You Will See What Is The Largest Fresh Water Element Like This Is To Approach Will Be Like This You Can See Fry 2012 Cumin Within Week Element Vansh Do Initial All Who 304 Like This All Will 2009 You Can See What Is The First Element Which Is The Match December 10 2012 Next Entry In To-Do List Manton Middle Age Ne Statement For Go to front of and 2.5 hr 98100 like this 2.5 hr 98100 like this 2.5 hr 98100 like this handle a want of preventive 150 computer which is 500 600 800 to 1000 to know from where you will find at 11.15 pm Nov 21 2010 100 number of columns of like this what you need To Find What 's the Common Element Small 's the Common Element Small 's the Common Element Small Wonders from the Species Vol. To Request What You Need to Clear Your Query Balwana Tell the Last Anyway Latest Updates Coming in Bay They Can Write Crush January Announced and You Might Get the Bell Icon This Like The Element Behavior 10 Liquid Something Which Country Which Is Equal To One Number 9483 Subscribe Now Two Times Subscribe 430 Medium Economic Judgment Potential Definitely One Time In His Right This Water Scooter's Easy Questions Return Time 725 Get More And More Latest Updates Five And Subscribe Our Channel Subscribe And Both Are Giving Free Water Not Only This Application Is Writing Like This Place Of Something Like This Is Very Interesting And During This Time Which Element Ki To Ek Anda Reaction Swadesh Lauta The Video then subscribe to the Page if you liked The Video then subscribe 80's Remaining in This You Know During the River Basin American So This Is Not The Advantage Can Find Especially When You Take Face Piece Complexities Pay Want To Consider Study This Is Very Much Aware Of Complexity And Subscribe The Solution Little But You Can See What Is This Improvement In Every Time You Are To Do Something To Every Time You All The Member Of The Day Ki Dahal Utta Pizza Boy Want To Return Right Sudhir Value Mainly You Want To Return Subscribe This Is Equal To The Return Of The King Is Not The Big Solution Subscribe for latest videos Like Dislike Directly Don't Like Subscribe Give The Rain Drops f2f Youth Road Glass Roy Discontented Satisfied Number The Meaning of Elements Need Not To Improve Solution Not Able To Find Gold In Return For This Is The First Element How To Maintain Element Rating Agency To Bigg Boss Subscribe specific elements of what is largest element person's size like share and subscribe to hai na govind next9news singh - see wife in the na govind next9news singh - see wife in the na govind next9news singh - see wife in the social media the ideal wife here greeting a concept of - miss greeting a concept of - miss greeting a concept of - miss whenever you want to search element in shot at least 100 bc Roy Like In Tracks Increasing Order For Others Might Get You Every Time For This Problem He Problem Elements In A Country Where Women Are Elements Of Increasing Order And They Want To Travel In Between They Find Something You Want To Avoid You Get No Idea To Solve The Problem In Terms Of This Agreement Shall They Go For The See Swayambar The Doctors Like This Initial Take And Variable Fan Ad Vijay Nischal True Something Solitaire This Element To Listen To What Are Doing Her This Week The First Floor Element Want To Know What Is the weather in the middle Bigg Boss death certificate Radhe-Radhe video mein ka statement one so half minute video It's not there in the state government withdraws his next subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe To That Which Will Return Dysfunction This Will Reach Of Indra Matter For An Intact Particular Rover Finding Way Se Zameen Khisak Youth And It To Find In Various Posts In This If You Are Able To Find Its Position In Which Position Idli Sandwich So Let's Check The Number To 1000 Like This Is The Value Subscribe Delhi Will Be Effective From This Room In This Quest To True Withdrawal Seervi Mein Tel Any Interest To Citizens Were Not Able To Fine Tune See The Value Of Root Will Return Active Till This By Which The Value Will B Negative Blood - 151 - One Is Great 0592 Negative Blood - 151 - One Is Great 0592 Negative Blood - 151 - One Is Great 0592 Files in Study What is This Is Not a Withdrawal Request Romance Subscribe to Next What is the Element of Bread Returns for You Are Not Able to Find What Happens in Study Center A Profound Stroke Next Festival to Reject Kiya One's Great Danger Is True Next Se Spent Hair Position * Next Se Spent Hair Position * Next Se Spent Hair Position * Gastric Mot Aapke Last Se Nikli Ka Note 10.1 Return Nakul Se Piano 225 Definitely 10.1 Return Nakul Se Piano 225 Definitely 10.1 Return Nakul Se Piano 225 Definitely Returns Minus One Clear So What Is The Complexity Year Will Get In Studies Subscribe Channel Measurement Ambassador White Number Of Columns Page if you liked The Video then subscribe to the Page Text logo and complexity on mintu and complexity you will get more than 300 votes - and also improved and more than 300 votes - and also improved and more than 300 votes - and also improved and improve the app will see the logic of elementary Middle is a navodayan gills what is the common element hair history why definitely you can set as no one dress returns - and fennel yes it as no one dress returns - and fennel yes it as no one dress returns - and fennel yes it will ask stuffing and 10 checking in abroad and 12th setting in every field like this song dj but can improve it how I can improve this level the first president of Kuch kahna hai hu is this level this grand this statement these want to hear any one okay the first elements greater definitely comment subscribe definitely write in the comment section and oil filter elements that every this diet Point 34 What One Approach Wicket 101's Seven Meanwhile This Greater The Last Salute and Great Ashok Veer Vikram Subscribe 4,320's Subscribe Now To Do The Volume That Noida - But You Can See There Different That Noida - But You Can See There Different That Noida - But You Can See There Different Parameters Compete With Him Shodhak Property Dealer Question Am Going To others a position of wanting in extra fiber position not only one thing I want to get the latest flash player if not only love letter supposed to have something like this is my all the great 8668099 but opposition will be id to know no I Want To From It's Not You But You Can You Find A 210 What One Thing That Can Reduce A Complex Setting Show That Is Not Here You Can See Finding The Opposition And Storing Enemy Positions Is There A Vacancy In Sanawad Hair Oil Capital Lemon Or You Can See Have Found in Sharing or Position of Five Years Witch Returns The Position Where You Can Win Sadak Chaliye Dysfunction 100 Taking a Row and What is Amazon More 2008 Contech Know Its Position and Defeated Not Able to Support It's Not Able to Get the Answer Will Return - - Position Plus Minus Plus Will Return - - Position Plus Minus Plus Will Return - - Position Plus Minus Plus One The Return subscribe And subscribe The Amazing Control The Position And The Key Position Care What Is The To Show The Pictures Of Is Through The Middle 1000 Not Able To Find The subscribe comment and subscribe the Channel Please subscribe this Video not this position - to give the this Video not this position - to give the this Video not this position - to give the position Video plz subscribe this Video Meaning The Meaning of Pollution Noise - 411 Meaning The Meaning of Pollution Noise - 411 Meaning The Meaning of Pollution Noise - 411 Donate Service Five or I Don't Like It Rain Se Position I Solved Will Be Returns in Waste Is Not Finding He and Opposition Will Be Mine in Software Testing Set up date notification for four plus one Which is - 5 notification for four plus one Which is - 5 notification for four plus one Which is - 5 Sentences of - Subscribe Position Study Sentences of - Subscribe Position Study Sentences of - Subscribe Position Study - - Verb - What is this What is the - - Verb - What is this What is the - - Verb - What is this What is the value Subscribe Don't forget to subscribe my channel Result of the meeting Which you can proceed in regular fashion A marriage Not able to get something very moist special effects grated ginger last element in other video channel hostel me cancer directly return management that effective day also pin sambar effective in between them where so now have to go to the position and kid and checking for the next Portion 6828 What The Are Lacking Special ₹1 Understand As One Saw A Country Like Special ₹1 Understand As One Saw A Country Like Special ₹1 Understand As One Saw A Country Like It Is The First President Of You Can't Exactly But It's Great Channel Subscribe Must Subscribe - Subscribe Must Subscribe - Subscribe Must Subscribe - Element 121 We Can Do So This Is About The Concept Of Finding The Smallest Komal Element So Will See The Next Problem Next Video Mein Thank You That A [ A [ A Do That A
Find Smallest Common Element in All Rows
unpopular-books
Given an `m x n` matrix `mat` where every row is sorted in **strictly** **increasing** order, return _the **smallest common element** in all rows_. If there is no common element, return `-1`. **Example 1:** **Input:** mat = \[\[1,2,3,4,5\],\[2,4,5,8,10\],\[3,5,7,9,11\],\[1,3,5,7,9\]\] **Output:** 5 **Example 2:** **Input:** mat = \[\[1,2,3\],\[2,3,4\],\[2,3,5\]\] **Output:** 2 **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 500` * `1 <= mat[i][j] <= 104` * `mat[i]` is sorted in strictly increasing order.
null
Database
Medium
null
1,824
all right let's do lead code have i done this question no okay oh looks lots of text i don't like lots of texts there are three lane through the invert of what there's a three lane word of length n that consists of n plus one points level zero to n okay a frog starts at point zero in second lane and wants to jump to point n okay however there could be obstacles along where you're given an array of obstacles of length n plus one each ranges from zero to three if it's zero there's no obstacles all right so it's one two or three if it's one means it's lane one two means of lane two three is lane three i guess so we met most one obstacle in three lanes at each point oh i meant oh wait there'll be at most one obstacle in three lanes in the three lanes at each point okay make sense for example if obstacle at point two is equal to one then there is an observer on lane one at point two and frog can only travel from point i to point i plus one there's not an obstacle in lane at point i plus one okay the rock can only travel from point i to point i plus one on the same lane if there's not yep so what else cause the frog can also perform a side jump to another lane even if they're not adjacent okay so you can jump like all the way up okay oh okay um sergeant another lane at the same point if there is no obstacle on the new lane for example if i can jump from lane yes return the number minimum which side jumps the frog needs to reach any lane at a point and starting from lane two at point zero minimum side jumps frog needs to reach any lane at point n starting from lane two oh okay so one two three i guess at point zero there will be no obstacles at one point zero and n okay good so we have ends up to 10 to the power 5 so i'm guessing a linear approach is what they want um can you do this using dp because i can think of the sub problem as the sub problems are going from zero to all each of these points what's the minimum number of jumps so the minimum number of jumps no side jumps to get to point one is zero the minimum sum of jumps to get to point two is one minimum side jumps to get to 0.3 is what um okay so you can have a dp per not position but per position but also per lane so like if i want to get to 0.3 i have so like if i want to get to 0.3 i have so like if i want to get to 0.3 i have to figure out all right what's the minimum jumps i can get to this point at this point and this point of course this point is not possible but also actually the um no that's not right um if i want to get to this point then it will be dp from this point hmm okay but from this point minimum number of jumps at this point is i have to consider jumping from here yeah but what if i haven't that dp doesn't really check out because i have to consider both ways um what if for each point i consider the minimum number it takes minimum number of jumps it takes to get to that point not jumping sideways so in this case it'll be infinity this will be infinity because i can't get to this point this will be infinity now let's not be infinity so it would just be one because i can get hit from here and the reason this is infinity is because i can't get from here to here there's a reason this is infinity is because i can't get from here to here because it's a rock there's a rock there so once i figure that out i can re-evaluate it and think for the infinity values for all the ones impossible to reach is there can i reach that position using um doing a side jump then i'll just be one plus that and if there are any so if there are any in those lanes that i can reach and there is infinity that infinity can be made just one plus in fact what you can do is once you calculate for each dp point so let's say i j for particular i let's say for example i zero is equal to infinity and you have one is equal to infinity we have two is equal to three what i can do is grab the minimum and set the rest grab the minimum one and set the rest to be equal to the min of the minimum one three plus one and what their original value was oh but what if it's a rock because the rock then it stays infinity so if not obstacle so if there's a zero there's nothing there if obstacle yeah so if obstacle at this position i great oh wait a second there's only one obstacle per point i think there's at most one obstacle in three lanes at each point so that means if obstacle i does not equal to j uh that's not j maybe i should have thought this at one uh it's not equal to j plus one then the min and it's not if statements if i want it to be code correct um then that and infinite all right so this will stay infinite which is equal to four in this case i'm just looking at this case here and this will be equal to infinite and this would stay um you know uh they should let's just pretend not numb jump so far the 2 is 3. all right so yeah this is kind of difficult to think about so let's just go through an example let's uh go through this example i guess okay so how do we how do you do this we this will always be a zero so what we can do is start with an array of infinite values one two three four five now this will be easier you know it's and then the base case could just be to apply this logic to here so i'll go through all of these find the minimum is zero and then apply this logic for the base case i know that this is going to be one so i could just really just hard code this bit and then i go okay so for each how many jumps would it take to get to this position well if it's if there's a rock there um leave it as is infinite so in this case there is a rock so we leave that there is going to be one plus the previous one if there's no rock here it's gonna be one plus the previous one if there's no rock then i find the minimum is one and so then i go through and i try to set each of these to one plus one which is two and this is already two this has a rock there so i don't change it and for infinity i should have just done this it's a bit hard to one let's do it a dash for if it's infinity and how many do i have so i have one and one two three four five there we go all right okay then i calculate for each of these what's the value so that stays infinity because the previous one is infinity and then i go here and like all right can i yep i can't because this previous one is one so i can do it two oh except there's a rock here so i can't um and then i go here it's like there's no rock here so make this a 3. oh no make this equal to 2 to the previous one in fact this will say 1 and then this and this will stay zero oops yeah my bad oops so yeah if i'm going sideways i can just like copy the number across i don't add one to it only when i'm going sideways so here i copy it across and then i calculate now i'll stay one yep and here there's rock i can't hear it here because previous one is dash country chase has a rock here and here i can copy the one across then i find the minimum out of all of these and update each one if there's no rock so here there's no rock make this a two and then here i can try to copy the values across there's a rock here so um i'm gonna just i'm just gonna set this one to two so copy the values across i can't copy the values across here and i can't copy here because the dash before and then now i can go through each of these two and set it to be the min of whatever it was and two plus one so here is going to be three here's going to be infinity still and then i copy the values across again so that's two it's going to be three infinity and for this one i guess we already found the answer but uh we could also just complete it and just say this is going to be three because it's two plus one and there's no rock there and then i can just go through the last column and find the minimum value and return that so that's how you do it that should work now okay you can do it in i know you can do it in constant time in uh in linear time let me actually comment this out and you can do it in all of one space but um is it worth doing in well with one space it might be because i'm just copying the values across i might as well do it in all of one space so if i just keep an array of three values like um one zero one initially it's always going to be one zero one so initialize a vector of ins of dp so um of size three to be equal to one zero one now the logic would basically go through and set and copy them across so the copying thing happens um if i can just do the copying thing by just um checking for obstacle and then setting the corresponding obstacle values to zero so for int to auto for end i in obs so obstacle in obstacles i could just say dp um yeah it's fine if there are no obstacles and continue so if obstacle is equal to zero not an obstacle then just continue just copy the values across and the first one is always going to be zero so i can just copy those across and just continue from there and then i have all right so i know i and then i have all right so i know there is an obstacle so i need to go obstacle value and dp the obstacle value -1 is equal to infinity so i just say max int i think it's in max i wonder if there's a function to just get the min of i think there is begin dp.end is there always an answer i think so because there's only one obstacle for it is possible to jump so yeah it should be possible so that means i can guarantee that the min value here is always going to be um and min jumps and then go through each of the values and set them to be the min of zero i less than three plus i so if um the optical minus one is equal to i then continue i think because i don't want to set the yeah and i'll set them and then they'll set the dp of i to be equal to the min of min jumps plus one and what else the actual value of it so far so dpi yep and then at the end return the min value of vp.beginvp.end i don't know if this i know i've actually done this before so we'll see if that is a thing i might have to check the docs that's annoying oh what this okay and what else line three has an obstacle so i'm going to mark that as something else maybe oh um x that's zero uh that's one zero one this is one zero one because i'm continuing this is one zero x so it's infinity in fact this is all going to be zeros it's going to be one this is going to be one it's going to be one as well it's going to be uh one it's gonna be one it's going to be one this obstacle here means i need to jump out and okay this needs to be um two hold on this is going to be two yeah that's going to be two and oops and two so that should be the answer so apparently i'm putting out three i see yes the logic i shouldn't be jumping if there is no obstacle in fact it's probably easiest to just like say add a zero here say this and yeah all the way up to four okay give that a go what infinite max end and max i think i should never be able to get there what also this should be from one to i oh okay so that was the issue please algorithm god yes thank you
Minimum Sideway Jumps
maximum-number-of-eaten-apples
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. * For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. * For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ **Note:** There will be no obstacles on points `0` and `n`. **Example 1:** **Input:** obstacles = \[0,1,2,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). **Example 2:** **Input:** obstacles = \[0,1,1,3,3,0\] **Output:** 0 **Explanation:** There are no obstacles on lane 2. No side jumps are required. **Example 3:** **Input:** obstacles = \[0,2,1,0,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. **Constraints:** * `obstacles.length == n + 1` * `1 <= n <= 5 * 105` * `0 <= obstacles[i] <= 3` * `obstacles[0] == obstacles[n] == 0`
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
Array,Greedy,Heap (Priority Queue)
Medium
null
1,575
Hello everyone welcome you are going to me channel 42 ok and as always I also start watching the playlist of starting questions if you want to understand DP from scratch ok and code service mic is available in Facebook Instagram you can check date out Liquid number 1575, this question is not at all hard from any angle, that is why I have made a big cross mark here, it is a very easy recognition problem, okay, if you want to do something else, I will tell you the reason, we will do only what the question number has said, right? We will write the line balan, right? The story will be simple, we will convert it into code line by line, our work will be over and don't worry, we will understand it from three diagrams also, it is very important, okay, so friend and definitely today's question is how will we make it? Through review and memorization, more bottom up will also come. All the questions that I have just told you will come up at the bottom. Don't worry about the bottom. Your separate topic will start. Let's take the concept of my DP. There we will do it from the bottom line. Okay, so account. Which is the name of the possible out question, this question has to read more questions and understand that the question is quite street forward, has given you a distinct positive wait, the representative of the name of the location, D, position of the city, I am okay till now, it is clear, start finishing fuel, this means What happened, which index will you start from, which index do you have to reach and how much fuel is there in your car, right now if you take mother, you are on I, then you can go to any other city, this note of true date Equal, you have come, you can go to any city and Jack is the index, now you have come index, you can go to any win index, okay moving from city, I have come to cities, this is the amount of fuel you have. It is a strange thing that if you are going by IK, then as much as your fuel is, there will be less in it. Okay, then how much mines will there be in the fuel? The value given in the Mins IK and the value seen in IK is their model, is n't it? Value is here, look at the correct mine location, this much will be reduced in my fuel. Okay, now what is it that your fuel cannot go negative, the easiest thing has been given here, this made the question even easier. You can go to a city only once, which means sorry, you can go multiple times to any city, it is okay, so friend, you just have to tell me how many possible routes are there in total, from start to finish, it is okay, when I tell you an example, there will be more. It will be clear, this is my location, okay, the start index is one, that means you have started from here, you have to start from here only, ok, you have to finish at zero every time, this is your target, zero index and fuel, you have only three. Right now we follow the mother, okay, every time you have to start the index from 1, okay, then from one you take mother, you go from one, you go directly to zero, one thing is done, I am writing the index, one said. So it is okay from the index, you went from one to zero, either you write down the value, which value is on the index band, from there you go to the value of index 4, okay, then how much fuel loss, the three, on which index was it on one because That is my starting point, my finish is given on the index where we have to go, okay now if I do one method, I will take two, then how much fuel is used in total, three fuel, if you had three failures, then date it, then this is also a valid thing. Okay, what other way can it be that you went three, okay, you went from 3 to 4, then four to three, okay, you can visit again, so for 3c4, one fuel is deducted, from 4 to 3, then one fuel is deducted. Why was one fuel deducted because the value has been given, how much fuel will be deducted, the mode of locations is, I used one from this location and here, so the total is three, how much fuel is used, three fuels are used and we had three fuels, so this is also a valid thing. Okay, what else I see, I also see that from three you went to 2, from 2 to 3, then from three you went to four. Okay, here too there will be a fail, here too there will be only one figure, so this is also valid. I have it, you are giving the total, how many passes can I get, by doing one, two, three, I will not be able to get five possible. If you are okay, then let's see how to solve it and I am going to do exactly what you said in the question, I am fine and this is in very easy language. The code will be converted from your story, let's start with this, let's make its tray diagram and this is going to be a very easy question, look at what it is saying, do what it is saying, I will show you, just do what the question is saying. Lime by line ok three diagram let's start it see this was the finishing index this is the fuel there are only three you have starting index 1 so see where you have started from index number one till now it is clear see now From this index one, if you go here, okay, that means where have you gone, the index number will go to zero, okay, then obviously how much fuel will be spent, here I write how much fuel is there now, my 3 is how much fuel will be spent, where will the index number be at zero. Is it worth its value? If it is one, then this much failure in fuel will be lost. Okay, so where are you now? A, four comma is 3, it is 4. You have gone to A. Okay, its index is zero, it is one, it is clear till here and write fuel here. I will give you how much fuel is used, I will check every time that yes, have you reached the destination? Yes, now the index has come but you are here, is it at zero, then is it equal to the definition, ok, it is very good, so what will I do? Here I will make the value of the answer one, okay, but what I did in the question, if you can explore further, then I will definitely do one, but plus I will ask you to explore more, okay, let's explore, let's move ahead from here and where else are you - Where move ahead from here and where else are you - Where move ahead from here and where else are you - Where can you go? Okay, maybe you went from zero back to one. Okay, if you go from zero back to one, then let's see where you are going. So here's what will happen after this. And let's go ahead, look, I will make the whole tree. Making the whole tree is fine but why don't I make the whole trick because there is no space here but it will be very mixed up, that's why it is best that I will show you in one pass. Okay, after this, let's move ahead. Okay, after this, there is still fuel. Look, there is one, which means it can go further. Let's see where it goes. It is possible that it may go back to zero, otherwise how much will it be. If it goes to zero, it will be four. The value here is 1 is 3, one is back to one fuel and c. So if A is back to 4 then I write four to I three come you are back where is A to index number 4. If A is back to 4 then the value will come to four. Zero one tu, what is this definition, okay, after that and here also from the option it can be here, it goes to one pe zero pe naja ke tu okay, so what is the value on 2, you are and this is right now I am on three. So 3 - 2 = 1 ok so So 3 - 2 = 1 ok so So 3 - 2 = 1 ok so 432 where am I this time I have been here right now zero one you have come to the second index now how much fuel is there fuel was earlier one was now zero now it will be zero here also flower It will be zero, okay, but pay attention here, there is no destination here, this definition is not there, okay, if there is no destination, then there is no problem, I will slow down further and see, I will try this later, then it is obvious that it is petrol. If you go to Kahani from here then take the value of petrol and it will become zero. Value of fuel will become &lt; 0. Take it here and it will Value of fuel will become &lt; 0. Take it here and it will Value of fuel will become &lt; 0. Take it here and it will become zero. Isn't it the story from here which is an obvious thing, take it and it will become zero here. But you see, if you go to the story then take fuel, it is going to be zero right because you have reached zero, but look here you have reached the destination, it is right, so you will definitely do one, brother, got another definition. If you put me plus forward then explorer, then what friends are doing is this, but take it, if it becomes zero, then what should I send, I have sent zero, okay, so one plus zero came from below, so one plus zero became one, then send this one above. Will it give or send one? One came from the left side. Okay, from here zero came from the right side. Then what will it do here? One plus zero will send one here. Let's take some mother from here. Zero is gone. Let's take mother. Come on, it can be either. Hey Maa, let's take three A's from the right side, okay, either way, you have gone A, Maa let's take it. Okay, so friend, what did I write here? One Plus and then this recension was done yesterday, okay, so the result that came will be added here. And so on, okay, that's why I want to say, tree diagram, it is very important, you can clearly see what is happening, how to run the regen, you can see it, okay, so it is obvious, here is something from the right side also. The answers that will come are mine, aren't they? Some answers from the right side will also be my answers. If you look at them according to what we said in the code, if I had made a story diagram, see how it would be, then see that the story is the clearest cut. So this was the thing. We always have to start from where, index is equal, you have to start from start, okay, so it is obvious, when I do the function recognition tomorrow, I will tell you, brother, yes, I am starting from start index, okay and I have a destination fixed. And how much fuel do I currently have, the fuel is this and I have to go to the destination here, only these three will have to be sent, out of which, brother, this band is constant, isn't it is fixed, I have to go here only, isn't it okay now? It is clear from here, now look, this is a very important thing, here one thing has been clearly stated in the question that if the fuel taken is zero, then I cannot do anything, brother, there is no option, the return will be made zero. If the fuel taken is zero then it will be clear from here but I want to do one very important thing here which is very confusing, let me tell you what is that point. Look, pay attention just now when I had made the tree diagram. What did I say, brother, which index did I start from, which was given, right here is the start, okay now look, I started from here, where can I go from here, I could have gone here or I could have gone here. Okay, so we will read both the options to apply, let's take it, oh and it would be longer than one to five, so now in this matter, I will try on this also, I will try on speed, I will try on this also, I will not start but if I want to start from here then it is an obvious thing. We have to try it everywhere, we have to try it on this also, ISP also has to be tried on this, okay, so you will definitely have to look, you have started from here, but you should explore it once. Then we have to stop regarding this, okay here it is cleared, after that when we take the mother on our own, we went here near the four, we went here, okay, then you have multiple options, you can go from here to here or So here you can either go here or sleep here, then there will be a loop on again, that is, from every recovery, you will have to look at one every time, you are the same people who are confused, brother, why are you putting a loop on recovery, so it is okay. It is clear from the tweet diagram that now you are also going to the story like mother, let's come to this level now, see you are here now but now you can explore many more places from here, so all the possibilities have to be checked, date is on this. You will have to put a loop, otherwise that's what I am saying, brother, one more thing, check that wherever you are right now, you are on the G index, the start index will be mine, if it becomes equal to the destination. So what did I say that yes OnePlus should do it, here OnePlus should do it, but there is more in the answer, we have to start, rest of the people thought it is okay, so I am saying, if it is equal to the definition, then the answer should be in one. Add one plus is fine, but now we have to see further, you can try zero a little, now the index is at zero, so apart from this, try with as many eggs there as possible, why would you try at zero, right now you are just standing there. Yes, okay, then put this check here: Are you standing at the start or not? Standing at the start should not be equal to that. If you say start, then in the current solution, I have sent start from here. This will change again and again, so don't say start. You can say this, current index is fine, when you solve it in starting, you will have to send start here, start from here, right fuel and destination are fine, so what I am saying here is that if the current is yours. You are on the current index, where if the current index is not equal to it, then only you will store it, if it is not equal to it, then it is okay, you solve it again tomorrow, okay till now, what do you have to do in the clear last. Whatever answer will come here, remember in the beginning, I had kept the value of the answer variable as zero. If the current index which is the start, I want to say current index, if the current index is equal to decreasing wherever you are, then I have kept the value of the answer as one. Have done but and further also have to be explored, isn't it right? Apart from the current index, whatever answer comes in the index, we have to keep adding plus in the answer. Who has to return in the last, the answer is correct, hence the diagram is very important here, as soon as you It came to light that okay, I have come to four, so four is my destination, so I have done one thing, brother, I must have got one thing because I have reached the definition, but from here the story can also go back from zero, right? We went back to three and then back to zero, so every time we will do plus one, okay, so we added one, after that we stored more, okay, so what will we do, two things are changing, so you are D. We will take DP and add value to it, so let's code it quickly. Let's do a sample recognition and memorization video and you can code it yourself because it was a simple story. It is okay in this question, what I said in the beginning, so first of all let's go. Let's take out N. Okay, what did I say that from where we are starting and our finish has also been given, okay we told that also and location start finish and fuel like every time, how to do the base first. If fuel lesson is given in zero question, okay, see start A, here I write the current index, meaning if the current index is equal to my finish, it is equal to the finish index, meaning we have got one thing, then answer plus. This is equal, you have done one, it's okay, if you want to explore more text, you have the right then tell me the next city, otherwise what I told you, take it for simple, we are going to take it from I and more than the current index, take it for I and make it simple. Okay, if that is my current city, what is the current city, this index is equal to that, if not, then only you will know how much will be the remaining fuel, subtract the current fuel from it, absolute value of location of current city means I - locations where You are going to know that it current city means I - locations where You are going to know that it current city means I - locations where You are going to know that it is okay and the answer is equal, you are sending the answer locations, the next concentration is about to come, the finish is about to come, you know what it is and my fuel is now this is the remaining fuel, what to do in the last return Have to answer or not, what will be the location here, I think now it should be passed, so what we have to do is simple one 2ddp, we have to take inter T, two things are changing, current index and one is my fuel, so current index means these. How much is the length, how much is the length of the locations, so I have given so much that I am late by 101 and the value of fuel is given by me, it will be 200, so what do I do, I am late by 201, okay and one more thing has been said, the value should be very big. If you have power then do modularization and return the answer. Here I have taken power 9 + 7 modular of constant mode one. It is taken power 9 + 7 modular of constant mode one. It is taken power 9 + 7 modular of constant mode one. It is clear till here and yes, I will check everything before proceeding further. What is IFT off current index? How much fuel is there, if note is equal to minus one and we will store it in the last one before returning then here we give brackets and return by modulo all the sums. Mode is ok. Solve this question was a simple story. What did we do with the code? It has been done through regional memorization and you must be seeing the time complexity in clear cut because what we are seeing is that first, what will be the maximum size of the location i.e. N has become N* fuel. Look at these but we are putting a loop N* fuel. Look at these but we are putting a loop N* fuel. Look at these but we are putting a loop of N. then n will be added
Count All Possible Routes
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
You are given an array of **distinct** positive integers locations where `locations[i]` represents the position of city `i`. You are also given integers `start`, `finish` and `fuel` representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city `i`, you can pick any city `j` such that `j != i` and `0 <= j < locations.length` and move to city `j`. Moving from city `i` to city `j` reduces the amount of fuel you have by `|locations[i] - locations[j]|`. Please notice that `|x|` denotes the absolute value of `x`. Notice that `fuel` **cannot** become negative at any point in time, and that you are **allowed** to visit any city more than once (including `start` and `finish`). Return _the count of all possible routes from_ `start` _to_ `finish`. Since the answer may be too large, return it modulo `109 + 7`. **Example 1:** **Input:** locations = \[2,3,6,8,4\], start = 1, finish = 3, fuel = 5 **Output:** 4 **Explanation:** The following are all possible routes, each uses 5 units of fuel: 1 -> 3 1 -> 2 -> 3 1 -> 4 -> 3 1 -> 4 -> 2 -> 3 **Example 2:** **Input:** locations = \[4,3,1\], start = 1, finish = 0, fuel = 6 **Output:** 5 **Explanation:** The following are all possible routes: 1 -> 0, used fuel = 1 1 -> 2 -> 0, used fuel = 5 1 -> 2 -> 1 -> 0, used fuel = 5 1 -> 0 -> 1 -> 0, used fuel = 3 1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5 **Example 3:** **Input:** locations = \[5,2,1\], start = 0, finish = 2, fuel = 3 **Output:** 0 **Explanation:** It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel. **Constraints:** * `2 <= locations.length <= 100` * `1 <= locations[i] <= 109` * All integers in `locations` are **distinct**. * `0 <= start, finish < locations.length` * `1 <= fuel <= 200`
Sort the arrays, then compute the maximum difference between two consecutive elements for horizontal cuts and vertical cuts. The answer is the product of these maximum values in horizontal cuts and vertical cuts.
Array,Greedy,Sorting
Medium
null
82
Hello Hi Everyone Welcome To My Channel It's All The Problem Remove Duplicates From Shot At Least Two-Thirds Of Life Problem Shot At Least Two-Thirds Of Life Problem Shot At Least Two-Thirds Of Life Problem Of Remove Duplicates From Tip Toe Give This Liquid Will Not Difficult Number Only Distance From The Original On Returning Officer Appointed Nodal Subscribe Like Share And At Least One Count Of Values ​​Will Start From Obscurity Interview Record Saturday Modifying Girlfriend Everything But Its Problems Like This Point Use Ability And Studio Will Solve This Problem Subscribing To Exit 12345 Subscribe Will Solve This Problem Solving Problems Appointed Nodal Middleton For That Vidmate South Indian Dishes Mez From Water Will Not Know What You Will Not Be A Joe Hair Know What Will Ooh Hair Will Start From This Mode So Android Appointed Will Know Which Can Very Love You To Do Subscribe Know What Will Ooh Will Not Nal Ki And value of start busy schedule satisfied and will keep moving in more channel subscribe to the Video then subscribe to the Page if you liked The Video then subscribe to the u otherwise get switch off lips oo will update points life but not minor updates 167 Share and know what we will do will interact wild these is not to listen in that case will also no devotional subscribe not from start from and variable from subscribe null start fluid subscribe and subscribe the Channel subscribe will update sodomized busy notes end mode amazon system Tune With Some Media Will Not Reduce Sexual Orgasm Means 9 News Pain Ko Che A And Sunao Tips Walking And Left Right You Concentrate Late Say Where Is Not Least One Wedding Bliss And One To Three Do Subscribe To Take Only One Place To Another Is Very Big So Let's Pray To Compile Beau Half Inch Ginger Custom Taste Cases Cutting Pass Notification Under Submit Subscription of Absolute and What Will Happen So Let's Acid Video from this Video not here in this Video To watch it subscribe now or after at our new start Will be and he will meet a great soul Soul will move and mix gently sirvi 12122 half body 1231 subscribe Video subscribe no hua hai navjeevan severe cutting bhi correct answer so let's subscribe like to know what is the currency of subscribe to 220 feel it solution Hit The Like Button Subscribe My Channel And Various Rate More Improvement And You Want To Avoid subscribe Video Subscribe Note Key Value Daughter subscribe The Channel and subscribe Is Updater Hai Vitamin Hair Will Make Her Daughter Video Keep Moving In A Way Which Would Look Into This Update Please Like Point Undhiyu Subscribe Our Video Similarly He Did Not Seem To Be After No Veer Waterloo Subscribe Here To Subscribe New You Tried To Complete The Trial Court This White Shoes In Implementation Meena Thanks For U
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
326
um hello so today we are going to do this problem called power of three which is part of fleet code daily challenge um so the problem says we get a number n and we wanna return true if it's a power of three false otherwise um and so power of 3 just means that n is equal to 3 to the power of x for some value of x um yeah so here is there are some examples like 9 it's a 3 to the power of two um and seven also yeah probably um another power of three maybe uh three to the power of three or something yeah but you get the idea so this is the problem we had a similar one recently but for 4 to the power of x so the solution here should be pretty similar um so let's get started yeah what we can do the first thing we can do simplest thing is to just keep dividing by three so keep dividing and by three until we get to one um keep dividing by three until we get to one and we have if we are not able to get to one that means uh there is no solution we can return false um so yeah as simple as that basically let's say for example for nine we divide the first time by three we get three we divide the second time by three we get one so that's a solution and this is because like if n is three to the power of x uh that means n is just three multiplied by three multiple times x times right so we can divide each time and x times and then we should be able to get to one right um so yeah by the way with this method we can also find what x is right because it's just the number of times we divide and so let's just implement that so while we haven't reached one and we can still divide because if any times we can divide let's say maybe we have um some value that is three multiplied by five right um we divide the first term by three so that's good the second time we start to check five we can divide five by three so we should exit or even if it's something like three multiplied by five multiplied by seven so as soon as we find uh five not divisible by three we should stop right um and so that's what we should do here so n modulo 3 is equal to 0 which means as long as we can divide then we divide by 3. and what we should do return here is that uh we should return when we reach one right if we are able to reach one so we then if n equal to one because if we aren't let's say in this case we divided by three we exited with this value we check it's different than one will return false um yeah so that's pretty much it let's submit okay so that passes test cases um now in terms of time complexity here we are doing at most x iteration here x being the power of three if n is a power of three but at most like as an upper bound it's uh of n right um a different way we can do this actually is instead of dividing is start from one and keep multiplying by 3 until we get to n so just the reverse right so if x is a power if n is a power of is 3 to the power of x that means again just the same thing we said earlier is x times right so we can just start from 1 and keep multiplying by 3 and check if we are equal to n if we get to a number where multiplying bigger than n or bigger or equal to n we should stop our loop right because um yeah until we reach until we get a value bigger than or equal to n then we stop right so basically we keep doing that while i is smaller than n um yeah so we start with i equal to one and then what we need to do is while i is smaller than n we will keep multiplying by three so keep multiplying by three and then if we if here i equal to n that means it's a power of three such yeah so let's run this let's submit um yeah and that passes test cases um yeah so that's pretty much it for this problem today um please like and subscribe and see you on the next one bye
Power of Three
power-of-three
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`. **Example 1:** **Input:** n = 27 **Output:** true **Explanation:** 27 = 33 **Example 2:** **Input:** n = 0 **Output:** false **Explanation:** There is no x where 3x = 0. **Example 3:** **Input:** n = -1 **Output:** false **Explanation:** There is no x where 3x = (-1). **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Recursion
Easy
231,342,1889
1,557
Hello hi guys we will be doing minimum number of questions but it's to-read call minimum number of questions but it's to-read call minimum number of questions but it's to-read call log production makes questions and it seems to be difficult for us but so you language of launching its tradition reflects that way Bagru statement's 186 graphs with advertisement list Number From 0 - graphs with advertisement list Number From 0 - graphs with advertisement list Number From 0 - 110 Shades Instructions For Effective Way To Go From Which All Subscribe So We Can Switch Every Mode Gangster Federal Credit Union Solution And You Can Advertise Right Som Ki 11 Lakh Wicket Song Hai Main Example Statement So Us Basically What Whom we have given z10 after that uncle so now let us come back first of all let's make it in which we note that jio seven our crops are going we can be called God can know something men where can we go on this Can go very soon and subscribe So now how happy we are Informing means if it does not move upwards then what would be the 10 possible degrees of these degrees, this is the one which is coming inside this one, if this one was coming inside this then I will do its degree, the belt will be 531 because the other one will be 140 degree because he has no comment, I did not know that he has taken the degree, okay, if now we only those people will give the next one, we are thinking that if we just switch off the mode of life, then if we Where is the phone on 043 this we less zero if we are ignored then where do I reach one question why above positive and 1965 so these are visiting okay so all these so we that if we only one if that word all our people Which is ours, then give us another example, what is happening in this, an app made from zero, from you 1370 Now we mean in this that Mr. Shyam ji, so what can we know from this point from our side that these degrees Increase at that time Bluetooth is on so a big forest is going, so what are the degrees of elements of these things in it, so we had put it in the minimum indices and how to make a key, zero to three two, this remedy cannot be done if we So now we can switch them in saree mode so of course we can do it [ appreciation] appreciation] appreciation] Okay so we have life in front of us so what do we have to return one person has to fit on time You would have answered this right today we Let's make 1 liter in which we will join these degree storm how many notes and your relation can't open them 0pen Now we are trying to do this so that on one hand we become post product of ITIT in it because in our computer science injection Try adding it, from our I know 80 IS West 1010 questions will come, meaning from here we now how to run this 0234, now we were aware of all the notes, he clarified that it is so now we said that I am S in degree, so I am Yoga Guru. Yes, we have already subscribed. Degrees were doing zero, so what will we do in answer dot push back, we will lower the flame of the gas and we will call it 'A', so it is ready from here and on submission, we should follow the instructions given there, that is a but one solution and Talking about free time complexity of mode VCES that we just ran it from end to end but they ran it and it is just our shoe Saugata Roy who is our
Minimum Number of Vertices to Reach All Nodes
check-if-a-string-contains-all-binary-codes-of-size-k
Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`. Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists. Notice that you can return the vertices in any order. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\] **Output:** \[0,3\] **Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\]. **Example 2:** **Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\] **Output:** \[0,2,3\] **Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4. **Constraints:** * `2 <= n <= 10^5` * `1 <= edges.length <= min(10^5, n * (n - 1) / 2)` * `edges[i].length == 2` * `0 <= fromi, toi < n` * All pairs `(fromi, toi)` are distinct.
We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.
Hash Table,String,Bit Manipulation,Rolling Hash,Hash Function
Medium
null
279
hey everyone welcome back and let's write some more neat code today so today let's solve perfect squares this is going to be a dynamic programming problem and it's pretty similar to the problem coin change which i've already solved and i would say that this is a very similar problem to coin change it's nearly identical actually so we're given an integer n we want to know what's the least number of perfect squares that can sum to this number n so basically the difference between coin change and this and coin change we're given an arbitrary number of coins with certain values with this we're only allowed to use perfect squares to sum up to the value n and if you don't recall a perfect square is just basically a number that has been squared so for example an integer 1 squared is going to end up being 1 integer 2 squared is going to end up being 4 integer 3 squared is going to end up being 9 so on and so on right so they give us a couple examples n equals 12 minimum number of perfect squares is going to be three four plus four that's three thirteen is going to be nine plus four so that's two perfect squares needed so your first idea is probably gonna be can you just be greedy right like can you just take for example 12 what's the largest perfect square that's less than or equal to 12 right because if we had like for example 5 squared right that's gonna be 25. that's too big right that's not going to sum up to 12 ever but let's start with the largest perfect square that does 4 squared that's going to be 16 that's still too big then we go to 3 squared that's 9 right so we're starting with the biggest perfect square that's available to us that's less than or equal to 12 right and so now what we're going to do is we're going to try 2 squared right 2 squared is 4 right so 4 plus 9 is going to end up being 13 right so we went too far right we're trying to get 12 we went too far right but i wrote down over here if we started being greedy right we started with the biggest one three squared and then we'd get these values one squared is the only way we're going to be able to sum to 12. but we notice if we're not greedy if we start with 2 squared for example that's going to be 4. we get another 2 squared that's going to be plus 4 another 2 squared is going to be plus 4 and that's going to be 12 right notice how with this approach which was not greedy we did not start with the largest perfect squares but we were able to get it in three perfect squares whereas when we were greedy over here we had four so this is not a greedy problem this is a dynamic programming problem and i'm going to show you how you can work your way from the brute force solution to the dynamic programming solution which is going to be pretty efficient so what's the brute force approach usually with dynamic programming problems usually a brute force approach is always going to be a decision tree so let's say we start out with our sum being 0 right of course we want our sum to be 12 but initially we're zero so we have a few branches that we can take we can start with one squared right that's one perfect square we could choose we could start with two squared that's another perfect square we could take we could try three squared which is another perfect square and then we would be sequential right we'd go 1 2 3 4 and just keep going like that until we get to 4 squared right what does 4 squared lead us to that leads us to a sum of 16. so clearly we went too big right 16 is greater than 12. we went too large so this is not going to be the path we take so once we get to this point we can just stop immediately we're not going to continue down this path but with these other 3 we'll get a sum of 1 of 4 of 9. and so i'm not going to draw the entire decision tree but that's basically what it would be right so from this 1 we would also have you know the same three choices 1 squared 2 squared and 3 squared and that would lead us to sums of 2 4 plus 1 is going to be 5 9 plus 1 is going to be 10 so these would be our sums so far and basically you can tell for example we got to the sum 10 right it took us two perfect squares a one squared and a three squared to get to this right so basically the height of this portion is going to be the number of perfect squares it took us to get here and the thing you're going to notice with this decision tree is that there's going to be a lot of repeated work for example from here if we took a 1 squared right then we'd get five again right but we see that there's already a five over here and now we have another five over here so there's going to be a lot of repeated work in this decision tree and remember our ultimate goal is to get to this sum n equals 12 right and so each of these values right 10 tells us so far we're at 10. our goal is to get to 12 but so far we're at 10. here we're at five here we're also at five right so do we really need to continue down both of these paths because from here we can see that it took us two perfect squares to get here from here it also took us two perfect squares to get here and from here what we're now trying to determine is if we start at five how many perfect squares does it take us to get to 12 from the original root we were trying to determine from zero how many perfect squares does it take for us to get to 12 or thinking about the problem in a different way once our sum is five in reality from here on we're really looking for what's the minimum number of perfect squares not what it takes to get to 12 because we've already gotten to five but right now we just want a plus seven to add to this 5 so that we can get to 12 right because when you look at the decision tree because we've found that to get to 5 the minimum number of perfect squares it takes is 2. and so we want to know from here what's the minimum number of perfect scores does it take to get to 7 then we can see if this is a possible solution but of course we know that the actual answer is going to be a different path it's going to be from here where we take another two squared and we get to a total of eight and so from here we're looking for what's the minimum number so we have eight now right so we're looking for eight plus four is what's going to give us 12. so at this point what we're looking for is what is the minimum number of perfect squares does it take for us to get to the total of four and we know that there exists a perfect square that exactly matches four right we know two squared is equal to four so how many perfect squares does it take to get to four it takes exactly one perfect square so we know that's actually just a given right it takes a single perfect square so then we can see that in total it'll with this path it'll take the minimum number of perfect squares will be three so let's now try to actually formulate what exactly is the sub problem in this case so we know we tried we started at one two three four and we just went arbitrarily high until we got to a value four where four squared was 16 and that was too large than this right so in reality we had exactly three choices 1 4 and 9. these were our sums initially so along this path we actually took this n equals 12 and changed the sub problem to actually n equals 11 because we know we've gotten a sum of 1 so far we want to know what's the minimum number of perfect squares does it take to get to 11 for this one we want to know what's the minimum number of perfect squares does it take to get to 8 right because 8 plus 4 is going to lead us to 12. for this one we want to know what's the perfect number of squares does it take to get to 3. so basically we're taking this big problem n equals 12 and breaking it down into three sub problems right so whichever one of these yields the minimum number of perfect squares that's going to be our solution and so what we're going to be doing here is we're going to continue to be breaking these down into sub problems until we get to the base case which of course is gonna be n equals zero right how many perfect squares does it take to sum to zero of course that's gonna also end up being zero so what we're gonna do is we're gonna start bottom up because we see that a big problem like 12 is gonna depend on smaller sub problems like 11 a and three we don't know which ones it's going to be it could be any of them that are smaller than n so anything less than n and even three is also gonna have sub problems right so before we wanna solve n equals three we're gonna need to solve n equals two n equals one and the base case is just gonna be n equals zero which we don't need to solve so this is going to be the bottom up approach what i'm going to be doing is i'm going to be computing the minimum number of perfect squares starting at n equals 1 then going to 2 then going to 3 until all the way we get to 12. and for each of these sub problems right let's say instead of doing 12 we were doing n equals 5. i'm going to make this same kind of decision like i'm going to make i'm going to try every single possible perfect square so 1 square 2 squared just like how we stopped early here like once we got to a number 16 that was bigger than our n that we were looking for that's how we're going to stop for the sub problems as well so for example 5 we see that 1 squared is going to be 1 2 squared is going to be 4. 3 squared is going to be 9 so we're going to stop early here we're not even going to get to this 4 squared 16 position so with that being said what's going to be the time complexity of this because we can tell that there's going to be a nested loop right we're going to be going since we're going to be starting at 1 and going all the way to n which in this case is obviously 12. so that's going to be big o of n right and for each of these n values we're going to have this original layer like this first layer of the decision tree only a single layer right but how big is this layer gonna be well it depends on the value n right but we know it's definitely bounded by at least the square root of n right because remember we're stopping once we get equal to or greater than our n value right so we're gonna start at one then go to two then go to three and eventually we'll get to either the square root of this right in this case 12 doesn't really have a square root integer it'll be three point something right but for example if instead of being 12 this was 16 we would do 1 squared right 2 squared 3 squared 4 squared which is exactly 16 and then we would stop right so we're stopping at this value which is the square root of 16 right so this the overall time complexity is going to be bounded by n times the square root of n with that being said let's jump into the code it's pretty short so like i said we're going to be solving all these sub problems before we solve the original n problem so i'm going to have a dp array where we store the result of those sub problems i'm going to initialize every value just to n you could do max integer if you wanted but we know that for n the max number of possible squares is going to be at the at most end because you know at the very least we could do 1 squared plus 1 squared and then eventually get to that sum and that we're looking for that target value and so the size of this is going to be we're going from 0 to n so the size is going to be n plus one and remember the base case is going to be where the target value is zero we know that takes zero squares to get to that target value so we're going to be iterating through every target value in the range of one all the way to n in python n plus one is non-inclusive so in python n plus one is non-inclusive so in python n plus one is non-inclusive so this is going to stop the last iteration is gonna be n and we're gonna be going through every single possible square value so s in range from 1 to the target value plus 1 because this is non-inclusive is non-inclusive is non-inclusive this is not the actual square value this is just we're going through every value from 1 to the target but we're going to be using s to compute the square so s times n is going to be the square right we're going from 1 2 3 4 but we know if we go over for example if target subtracted by the square is less than zero that's when we're going to break right that's when we can stop early we can stop short we don't need to continue we don't need to waste our time but if we don't stop short that's where we're going to compute the possible solution so we're going to say for dp of target a possible solution could be the minimum of what it already is right in that case there would be no change or the minimum of the remaining amount so for example target minus square right so let's say our target was 12 our square was four now the new value that we're looking for is 12 minus four so we're looking for eight right so we're going to say dp of target subtracted by square right that's why we're solving this from 1 all the way up to n because we're depending on the smaller results that's why it's called bottom up but this also needs an additional one because we just used a square remember what we're trying to do is counting the number of minimum squares we just use a single square so one plus whatever the minimum number of squares it takes to compute this new amount right 12 minus four how many minimum squares does it take to get to eight plus you know the single square that we just used right now and once that is done we'll have gone through every single target value one all the way to n so therefore the solution to n will be stored in our dp array so then we can just return that return dp at position n that's going to be the minimum number of squares it takes to get to n so remember the overall time complexity of this is big o n multiplied by square root of n you can kind of write that like this there's not a good way to do it but yeah that's the time complexity there is a more efficient way to solve this problem but this is kind of the main solution that i think an interviewer would look for like this is the actual intuitive solution there are like more mathematical solutions that i don't know if you know that would actually be helpful to learn but i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Perfect Squares
perfect-squares
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`. A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not. **Example 1:** **Input:** n = 12 **Output:** 3 **Explanation:** 12 = 4 + 4 + 4. **Example 2:** **Input:** n = 13 **Output:** 2 **Explanation:** 13 = 4 + 9. **Constraints:** * `1 <= n <= 104`
null
Math,Dynamic Programming,Breadth-First Search
Medium
204,264
1,773
hey guys ben here so today i'm going to talk about question 1773 english code count items matching the rule see how we can approach this problem so given this a list of list items so basically it's like this list of lists and whatever string low key and your value so what i want to do is let's look at example so basically we want to validate this statement and if one of these three is valid we wanna increment we will say okay this rule is followed so the first rule is when low key you go to type and type equal to blue value or when located with color and color equal to low volume and low key equal to name and name equal to dual file so what does it mean so you can as you can see that items have three different values so type color name and then there will be a low key and low value to match it so let's look at example so if items are phone which is type this phone and color is blue name is pixel the other one is that item is the type is computer color is silver and name is lenovo and the other one is phone gold iphone so and the low key and the value is colored located is colored and dual part is silver so we want to check that okay if the key for all these items who is matching the silver one we can see only the computers matching silver one so we will return one because there's only one item matching so you get the idea and at the end i'll explain the difference between each the equals method and the and two equals operator so we want to return the count right so we just save the count initially to zero and then loop to the list so we can look to the list and call it l and from items right and then what we can get is we can get three different strings first is type so is l dot get zero because it's the first item in the first item right here in this list so second you can call it color all right so now we get all we need and we need to check the condition so what if while this room is valid we will edit the count so say rule key is equal to what can i use so right now i'm trying to explain why we cannot use the equal word equals so basically the equals is a method that in w equals the operator and the equals is comparing the content and that equals checking the two object points to the same memory location so at this case we want to use the equals so the equals type is equal to type we want to also check if the type is equal to the null file okay so or the low key is the equals is key okay so we can use the echo i'm gonna use okay and then here we're going to start a to call it that course i'm gonna sell the low key equals right yeah this is the same okay in this case we just implement the camera and then again we return account so in this case we'll be all one time will be open because we look to the islands so cannot convert to list the string during string so yeah the typo but it's all good and yeah that should be it you know yeah so wrong time long time capacity all right thank you guys if you like this video give it a thumbs up and then share the video to your friends if they have studied computer science to try to do interview questions also subscribe to the channel i'm gonna call until i get to google get to the fame google facebook netflix amazon see you next time
Count Items Matching a Rule
percentage-of-users-attended-a-contest
You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`. The `ith` item is said to match the rule if **one** of the following is true: * `ruleKey == "type "` and `ruleValue == typei`. * `ruleKey == "color "` and `ruleValue == colori`. * `ruleKey == "name "` and `ruleValue == namei`. Return _the number of items that match the given rule_. **Example 1:** **Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "lenovo "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "color ", ruleValue = "silver " **Output:** 1 **Explanation:** There is only one item matching the given rule, which is \[ "computer ", "silver ", "lenovo "\]. **Example 2:** **Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "phone "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "type ", ruleValue = "phone " **Output:** 2 **Explanation:** There are only two items matching the given rule, which are \[ "phone ", "blue ", "pixel "\] and \[ "phone ", "gold ", "iphone "\]. Note that the item \[ "computer ", "silver ", "phone "\] does not match. **Constraints:** * `1 <= items.length <= 104` * `1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10` * `ruleKey` is equal to either `"type "`, `"color "`, or `"name "`. * All strings consist only of lowercase letters.
null
Database
Easy
1338
1,796
Show More Hello Friends Today I Will Have To Solve This 1796 Question Of The White Tiger Technologist Visit In Aaf Dekhre Ko Mili To Question Subscribe This Channel Printer Input Festival Shab-O-Roz Ajay 10 Solution Of This Question Just Only For The Learning How To Code This Question Solution With Multiple Subscribe It's Something Is The Number 123 Number Can Be Set From Here This Two Quid Check Every Character Of Spring And Director Intuit Small Brother Twills For The Set And Return Gift Second Largest Missal Paw Subscribe Button To 9 Tractor 1000 Characters 90s Subscribe To A Settled She Should They Have To First Create Unrest In Vs Intended To Be Written In Seclusion Tumor Of Sports Activity - - - And Kuch Bacha Ok What Is Activity - - - And Kuch Bacha Ok What Is Activity - - - And Kuch Bacha Ok What Is The Spelling Of Quetta Is - Bank of Baroda to the operation Quetta Is - Bank of Baroda to the operation Quetta Is - Bank of Baroda to the operation pimples, if you feel that there will be norms in some time, will submit its report, then immediately order test cases that your knowledge computer loot solution is done, verification is done, button is pressed, school learn how to think pollution. End Comment It's time from the point of view of third dynasty okay no jo hair guddu method do one take electric how to do hello exactly thought planets witch can do this point to point loot points maximum point on is point maximum how to play the subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page To le liye hai reliving that wealth was not getting award in this difficult is chitta na dharai unicode virvar unit ke president sa simple way simply report jab first element instruction to enter And Exit In The First President To Visit Is Ahirwal Simply Loot The Video then subscribe to the Page subscribe and subscribe the That your novels end with revolution and black time That you understood that the album of this question will start so they need To listen to be used on hua hai
Second Largest Digit in a String
correct-a-binary-tree
Given an alphanumeric string `s`, return _the **second largest** numerical digit that appears in_ `s`_, or_ `-1` _if it does not exist_. An **alphanumeric** string is a string consisting of lowercase English letters and digits. **Example 1:** **Input:** s = "dfa12321afd " **Output:** 2 **Explanation:** The digits that appear in s are \[1, 2, 3\]. The second largest digit is 2. **Example 2:** **Input:** s = "abc1111 " **Output:** -1 **Explanation:** The digits that appear in s are \[1\]. There is no second largest digit. **Constraints:** * `1 <= s.length <= 500` * `s` consists of only lowercase English letters and/or digits.
If you traverse the tree from right to left, the invalid node will point to a node that has already been visited.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
114,766
208
Hello hello guys welcome back to back division in this video you will see how to implement it differs from digit code for the match challenge so let's not look at the problem statement the problems but they need to implement right to information adhvansh sex to S2 subscribe The Channel Please subscribe and subscribe the case letters and will run from pillar to understand this app will not interested and want to share with you set n this year will not be present when you so much for years in this will return for this is not present in This you will hear and decide will get in touch with you will be able to find the latest subscribe and Share And subscribe The Amazing subscribe to ki noida to solve this problem I will take or try not structure and structure with different don't want operations Do You Want To Do So In This Case I Will Keep Away Now Which Means To The Current Character Not Actually Need To This Value Press The Subscribe Button No Need To Dissolve Sleep This Problem Solve This Thank You Want To The Country Which State Will Give You Can But For This Problem This Is Not The Best Modified In Order To Solve Different Problems And Seervi Away Former Everest Trimendous So Lets You Must Read This Book And Add This That 108 Note's Develop And Share Will Be At Least E Request U For ur so let's you want to remove work in this way you will get different to three liberty key notification falls and you will not be able to use this question to keep track of the public for the way you will get different problems will also Request Channel Subscribe Like And Structure Of Heart Will Look Like This Is The Current Account Storing The Number And Springs With The Given Prefix And This And Share Also Storing How Many Words Ending At This Current Mode On This After Winners Will Be Appointed To The Next Advocate Sudhir V0 Calculated for pointer in C plus cit acid 1968 subscribe And subscribe Video subscribe 0999 Simple example in to-do list will take off its root to-do list will take off its root to-do list will take off its root Latest Air Force Operation Students at Apple so will take each and every character 151 will have to Make Notes From This Route Will Be Interested In Veer Is Equal To One Can Achieve Which Is The Character Know Will To Create Subscribe Will Have To Make You Will Be Amazed And Share And Subscribe Account Value Will Know In Christ Two No Divide of Twelve One More TV Channel Subscribe And They Will Have To Keep Track Of Seervi Subscribe Now To Receive New Updates Will Start From Root Directly Presents Subscribe And Subscribe The 10 Middle East Kings Pay Room For Rent To You Can See But From Root The Amazing No Child Name Baby So Will Have To Insert A Child Name After Interview In The Village And Again In No Affluent Servi 21 2009 Research Is The Present In This Country Can See From This Is The Present President And Displaced And Subscribe 100 Years Ago ND Share Dis Current Node In This True When Will Have To Return True Saying Dad 10 String Is Present In This Tree Na Dhoop To Is App Present In This Tree Will Start From This Root Is At Present For The Truth Labs To from this point to go to piece present from this thank you want to go to PSP subscribe and subscribe the Channel Please subscribe and subscribe the Channel Searching for fruit you will and the position for this is the end in node for That And They Want To Find Weather In This Present President Industry Is Equal To Traffic Will Consider Patience Subscribe This Will Also Be Written Taste Will Be The Last subscribe and subscribe This is not peace presents subscribe and subscribe the Channel subscribe gym play return forms directly Research Train Name Day Apps With This Present And Destroy Sudhir And Gautam For Implementing The Strike Surgical Strike Implementation Is Very Simple But Problem Simple Problem Time Complexity Of Implementation Will Be To The Length Of The Longest River In Multiple The Number Of The Time Complexity And Subscribe Will Be 20 * Number 90 Plus Implementation 0091900 The Maximum Subscribe My Channel I Will Define The Structure Of The Earth By Will Also Take True Tangible Variable Noida And Greater Noida Function Will Actually 500 Index Value And Will Just Film The 90906 Equal To You Are You Will Not Mean That You Will Have To Quit After Observing subscribe And subscribe The Amazing Don't Know The Character Values ​​From Character Express Amazing Don't Know The Character Values ​​From Character Express Businessman 512 Set The Root Character Was Lad There Lives And The Value Of And Less - Lad There Lives And The Value Of And Less - Lad There Lives And The Value Of And Less - From Bigg Boss This Greater Noida Will be adding classes Will get the candidate Don't forget to subscribe Limitations for implementation in points Will give and take off But e thought with the value of the world Every character will keep traveling in the trains Will calculate the intellect and see the indices Already created so even know what is not created and will create unordered and after that will increase account value of the node in order to keep track of how many springs we have really you guys did not enter processing center word finally will updater and share value for this Channel And You Will Be Updated To Plus One Value subscribe and subscribe the Video then subscribe to the Page if you liked The Video Trees Members Only Difference And Difficult Problems Enterprises Traversing Will Just Checked And Values ​​Which Traversing Will Just Checked And Values ​​Which Traversing Will Just Checked And Values ​​Which Indicators The Beatles Tours In Which Is The Current month will not last subscribe to subscribe 1212 20 serving given in fix different pass doses so this is the inter logic and if they are not able to traverse the next9 like subscribe and very simple but very few can understand only one solution in different Languages and Everyone Can Benefit From Like Share and Subscribe
Implement Trie (Prefix Tree)
implement-trie-prefix-tree
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: * `Trie()` Initializes the trie object. * `void insert(String word)` Inserts the string `word` into the trie. * `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise. * `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise. **Example 1:** **Input** \[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\] \[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\] **Output** \[null, null, true, false, true, null, true\] **Explanation** Trie trie = new Trie(); trie.insert( "apple "); trie.search( "apple "); // return True trie.search( "app "); // return False trie.startsWith( "app "); // return True trie.insert( "app "); trie.search( "app "); // return True **Constraints:** * `1 <= word.length, prefix.length <= 2000` * `word` and `prefix` consist only of lowercase English letters. * At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
null
Hash Table,String,Design,Trie
Medium
211,642,648,676,1433,1949
116
Hello friends welcome to my YouTube channel I am Kumar Singh so and difficult series what will you pick up question family like a job portal where questions on daily basis with vipin question will go through the algorithm in turn will decide the issue heart Samai question mein hai Ramoli and modifications of ok leader can be laut se Nehru so what will we do, we will first complete the alarm part whenever MS Word code then we inki vitamin question hai he melt comment section so let's move to the co 29th December Again Will Move To The Question On Loot Election Splitting Sodi Question Is A Plane Dinesh Strike Half Inch 9 And Development Ministry My Loot Was That Aapke Yourself In This Process Quite Simple Bihar Entry Facility Object Which Points Loot Ride Bodh Business Next Point Next9 switch between two points on this simple we have us subscribe to our channel Bluetooth will move to Javed Loot-Loot using back and you will just made Loot-Loot using back and you will just made Loot-Loot using back and you will just made destructive watching the question then the responsibility comes something like this question That's what we used to do but now this is a surgery to subscribe our channel and subscribe to our channel. What do you have to do, you have to provide root knot, so that deportation camp print is inevitable time when we have to print like now from fruit, it should be soft. Take the scent, approach, okay, what do we do, we show on the routes that you go, if the left is not null, then it is okay, this next notes your left, you, if my left is not null, then the next one on the left should melt. If the route is fine then it will happen that you are upset1 I am left what is to hai next what is next of Russia he is bittu and what is right is 3D Divya so now what will we do we will first in his life then this is good so if this is not So you do it, you rent it, so now what will we do, if I and I had to stay, he will do it next to me, what will happen with this 123 because he has taken it, now he will do it, why are you here, so I also shoot the difficult in the loop according to that, I Just as there is a desire to reduce chances in the section, then first we move towards the court that the country will do it with comment at this time so that we get one thing written because this is the way can be implemented. We are users of dry ginger and detergent because we use Do thank for a small part will go more on because when we are on roots mode crown was left leg in Russian president gift diet ok morning important and then we think like second application ok eat we go some then will move to the next Taking The Amazing Spider-Man 100 important thing, we will work and we will cut it and one minute is the point of contact, so what will we do, we will take the next point and we have simply minimized the root, we go to the gym, this is the width. You can say something else, now I call it Saif, this is a man tied to me, but look at this message which is a neck point, it will automatically go with the root, this thing that I have written on it will be done on the next point. Root ko wa hai jab mix nor will only channel ko and this is the reference because we took it separately so we changed the currency and we are like ok so next point 101 check which we talked about a yes this is ok so like We had made a plan to stop near us or now the left on this route is not there, so the next one on this left will be lighter, then after positive one, two comes, then on this note channel, the next one to you will be light. So that we move left-to-right, that we move left-to-right, that we move left-to-right, with top to bottom, only simple root dot love not equal 2nd, we who are to the left of our root, the next one there, you who we have now in this and so of our life. Now this is not equal, if you go towards Upright Tubelight then Sim, we write it above, we do not ride their route, we do not ride the time, the value of the route is nothing, we have the right of the route, in the next if you subscribe for the route, then this is yours. So this is for doing this and this is for right do take source code simple now here how do we use here against using otherwise if you will right then we note left and right here okay now my right winl If it is not a lieutenant then it is going to the value of the left instead of the possible fare, so here we are in the top bottom and can again restaurant from Naseem record, we again his pimple, so with this we should fly away in that form, in this it does that Under all your pimples, in good communication, you did not use base metals, fruit tap, give me a bell, I want to come out of the house now, measurement is required, not if we go through, then you spend so much, after all, it was Questions for a Day, now Sachin Always got hundreds of these, if we submit, then people talking, then line of department heads, district, so now we free the setting of approach, what else can be the approach, I will not write direction code of all real freedom but also tried to explain you now. Let me try and increase, if you do n't want, I will be my best friend with you. In this typing, give a comment, travel toe. Okay, morning and product. Secondary Dum, it is a fortuner that we love you like the most. We are very suitable, we do it very well, we do it. City that we use the gift here, we all know a small problem, whatever decision can be taken, it can happen anyway, that is the problem, so this problem Meghnad is the first that you will defiantly Subscribe button more benefit pimples 102 Ok thank you for watching my video and allow you to explain in this series by subscribing that the question is solved question and if we do this mark like this then we can also add it then we should subscribe to the channel first as soon as possible simple eligible content Every day you come to buy milk, subscribe to this page so that we thank you and wish you a happy new year.
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. Initially, all next pointers are set to `NULL`. **Example 1:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[1,#,2,3,#,4,5,6,7,#\] **Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 212 - 1]`. * `-1000 <= Node.val <= 1000` **Follow-up:** * You may only use constant extra space. * The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
null
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
117,199
1,057
hey everybody this is Larry this is me forgetting to do week one of the Leo da challenge so or weekly challenge premium challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's farm and I'm still in koshima uh you can see from my shadow that I don't my lighting is terrible this is what I look like but in any case let's took a look at today's Farm 1057 canas bike so bike is let's see n nxy plane the N workers and m bikes okay they're more bikes than workers you're given workers length Okay assign a bike to each worker uh okay so the two workers two bikes okay I mean it seems like um a sorting or heapy thing or like um yeah I don't know how would I think about this I mean is a th so maybe it's just an N Square solution right n Square log n it's a little bit sketch yeah am I miss reading this poem this is supposed to be only a medium right I mean the M distance um grab workers zero grab Spike zero first okay so I mean it is just like a minimum distance thing I'm trying to think whether there is a better way to do it um for each worker you sld all the bikes then I don't know if you could do or all of my ideas off my head is n Square log n which is a little bit high for a th000 that's why I'm a little bit like trying to think whe I could do a little bit better than that right uh even if you minimize it's going to be end square or well there only nend things but and then every time you do it or every time you relax it requires you to uh this an awkward problem isn't it don't to think I mean maybe we could exploit these two it's a little bit more but it is definitely a awkward thing well the farthest distance that two things can be away is 2,000 right so two things can be away is 2,000 right so two things can be away is 2,000 right so can I do that in a linear sorting kind of way I guess so maybe that's the way to do it so then you do n square and then because you do this um yeah I guess so because you take advantage of the fact that the this for this distance is 2,000 so then it then this distance is 2,000 so then it then this distance is 2,000 so then it then you can just kind of check them in one at a time uh all right fine the bike that is index too okay yeah I'll give it a try just because just yeah okay fine I don't know how I feel about it but uh but let's kind of you know do something like this first right and then maybe for something like for i and m of w right so now for J and range of B and then we have maybe just like uh distances right as you go to collections that default T of list and then now you have so workers sub I uh it has two indexes so bike subj of zero so you have absolute value of this plus let just call D I'm going about oh jeez so this is the m distance right and then distances of D we could pen i j and yeah and then now we just want to make sure that bikes is used and workers is used so maybe like a workers used is a set and bikes used as a set and then now we can just do this for I in uh distances do uh this. Keys sort uh this sort is different from sorting all the other things because this is just sorting from distance so this is going to be like 2,000 L and then now it does another 2,000 L and then now it does another 2,000 L and then now it does another linear thing or not linear but n * m linear thing or not linear but n * m linear thing or not linear but n * m or W * B of okay so then distance sub I or W * B of okay so then distance sub I or W * B of okay so then distance sub I right is the thing we're looking on so for uh WB in distance of I if we not in workers used and B not in bikes used then now we can just do workers used. add W bikes used. add B and what are we doing we're doing answer so yeah answer is equal to none * W for so yeah answer is equal to none * W for so yeah answer is equal to none * W for each worker and then answer of w is equal to B and then that's pretty much it right is what I would say but I misunderstand this bug Z grab zero right oh no I'm looking at the wrong case okay by one grab zero uh h huh let's look at distances maybe I have some like weird typo or something the idea seems okay though I think right so one I mean there's something wrong because this is the Sha two which is the distance between one and zero do I have a typo oh I do have a typo that's why all right this is good let's give it a run again no output submit I mean this isn't hard per se but it is a very weird problem um so what is the complexity here right well this is W * B the Sorting is on keys and the keys * B the Sorting is on keys and the keys * B the Sorting is on keys and the keys can really only go up to 2,000 so I can really only go up to 2,000 so I can really only go up to 2,000 so I think that's the thing that uh it's a little bit thing but and of course you can have you could have actually done this without sorting if you depend on how you do it because you can have a r of 2,000 elements and then just up one of 2,000 elements and then just up one of 2,000 elements and then just up one by one I don't I wouldn't worry about it that much because 2,000 log in and it that much because 2,000 log in and it that much because 2,000 log in and 2,000 is not that 2,000 is not that 2,000 is not that much but that means that each of you know this makes it linear so or not linear but I said that twice but W * B linear but I said that twice but W * B linear but I said that twice but W * B so this total thing is actually going to be o of w * B plus maybe like uh I don't be o of w * B plus maybe like uh I don't be o of w * B plus maybe like uh I don't know domain maybe or range like range right so yeah so that's the time for space this is obviously just o w * B and it is apparently good enough w * B and it is apparently good enough w * B and it is apparently good enough so yeah um that's all I have for this one let me know what you think I need to pack for tomorrow so stay good stay healthy to a mental health I'll see yall later and take care byebye
Campus Bikes
numbers-with-repeated-digits
On a campus represented on the X-Y plane, there are `n` workers and `m` bikes, with `n <= m`. You are given an array `workers` of length `n` where `workers[i] = [xi, yi]` is the position of the `ith` worker. You are also given an array `bikes` of length `m` where `bikes[j] = [xj, yj]` is the position of the `jth` bike. All the given positions are **unique**. Assign a bike to each worker. Among the available bikes and workers, we choose the `(workeri, bikej)` pair with the shortest **Manhattan distance** between each other and assign the bike to that worker. If there are multiple `(workeri, bikej)` pairs with the same shortest **Manhattan distance**, we choose the pair with **the smallest worker index**. If there are multiple ways to do that, we choose the pair with **the smallest bike index**. Repeat this process until there are no available workers. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the index (**0-indexed**) of the bike that the_ `ith` _worker is assigned to_. The **Manhattan distance** between two points `p1` and `p2` is `Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|`. **Example 1:** **Input:** workers = \[\[0,0\],\[2,1\]\], bikes = \[\[1,2\],\[3,3\]\] **Output:** \[1,0\] **Explanation:** Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is \[1, 0\]. **Example 2:** **Input:** workers = \[\[0,0\],\[1,1\],\[2,0\]\], bikes = \[\[1,0\],\[2,2\],\[2,1\]\] **Output:** \[0,2,1\] **Explanation:** Worker 0 grabs Bike 0 at first. Worker 1 and Worker 2 share the same distance to Bike 2, thus Worker 1 is assigned to Bike 2, and Worker 2 will take Bike 1. So the output is \[0,2,1\]. **Constraints:** * `n == workers.length` * `m == bikes.length` * `1 <= n <= m <= 1000` * `workers[i].length == bikes[j].length == 2` * `0 <= xi, yi < 1000` * `0 <= xj, yj < 1000` * All worker and bike locations are **unique**.
How many numbers with no duplicate digits? How many numbers with K digits and no duplicates? How many numbers with same length as N? How many numbers with same prefix as N?
Math,Dynamic Programming
Hard
null
350
hello friends in today's video we are going to discuss lead code problem intersection of two rs part two we will also discuss its part one after this problem is done any problem what you have to do you are given two integers are in numbers and numbers too and we have to written an array of their intersection such that each element in the result must appear as many as times it shows in both the array uh and you uh may return the resulting anode means only those elements will be the part of your answer which are present in both that is num1 and number two and those elements will be counted in your answer array as many as times they are common in both this array okay uh like see in this example uh two is common in both the array and how many times two is common in both the array two times so two times uh your answer will contain the number two okay let's just it's approach see here what uh you are given number one this and numbs to this what we will do first we will try to uh do a brute force approach for this means what we will do for uh for every element in them so you have to check if corresponding matching element is present in num2 or not and once you are getting any corresponding match element uh remove that element from nums two so that next time you can't use that element if any of the further element the same element present in num one again okay now see you are on one check if one is uh for this one corresponding uh one is present in nums two or not check means yes uh means we are not having anyone in numbers two now for two is there any corresponding to present in them to yes a for the two we are having corresponding to present in namstress okay then two is the part of your answer already here and make this two cut so that next time when you are going to encounter this uh any of the two again in namsun you are not going to match that to with this uh match already mesh two okay so make this two cut now for next two check if there are any corresponding matching position in nums two yes we can check that uh for these two a corresponding matching two is present in your numbers two then make this two cut now again come to uh this one check for this one if there are any element present numbers too so that you can match it no there is no one number two so this is the part of your answer okay now take it let's another let's take an another example is your answer vector for four check if there is any matching for present in numbers two uh so if you are going to check now then we can easily get yes a four is present in nums two so that uh that can match our current four okay make this four cut so that next time we are uh getting another four in our numption we are not matching that four with this particular four okay next uh check if for nine if they are we are having any corresponding matching elements yes we are having the for nine matching elements so make this nine cut now for check if for five we are having any corresponding matching elements in number two no we are not having any matching elements or five so uh stop your iteration because all the elements of numsonar has been processed you can uh you can start from any if you are starting from nums to then you have to search corresponding match elements in numser you can do any of the way your answer will be the same okay so 49 is our answer now let's discuss the it's go it's coding approach first we will discuss root force approach then we will further optimize it okay now see this is your brute force what we are doing for every element in numbers one we are at rating in nums too and we are checking is there any matching element corresponding match elements in them to is present or not if it is printed then make okay 1 and make nums 2 j barber one means cut means uh remove we are what we are doing we are removing that element from nums 2 and that element in the sense means that matching element okay means next time when we are having the same num i present in our num swan then we are not going to match that number with this particular number means what we are doing if for this particular four we are having my then make this four cards so that next time is if any of the further four is present we are not going to match uh this particular four because this is already been matched okay so we are doing this and if you are not saying any particular element then what we will do we will make okay is equal to 0 and we are not pushing we are will be not putting that element in our answer otherwise if we have matched that ok is equal to 1 and if ok is equal to one then answer dot push back number nine that is your answer okay you can reverse numser and f2 sir you can also start scattering from numbers two so uh what is the complexity of this approach is of n square okay this is your complexity uh what time for mexico now let's discuss the uh space complexity is over fun because we are not using any particular space so your space complexity is often okay because uh see uh you are not using uh space complexity uh because uh we are uh returning an answer now so for that you can uh see is space complexity often but we are not uh using any element for our own so you can see it often because uh answer is uh you are using to return that answer together so space complexity is over fun now let's assess its optimized approach for optimized approach what we will do uh means what you have to do we will maintain a counter of answers means uh what just let me tell you what i want to do first what i will do i will keep track of uh mr the number of time a particular element is present in num in nums one okay so for this four is present one time okay nine is present one time and five is present one time okay now you have maintained counter variables now it started trading from nums to and check if uh we have the account of this particular element is greater than one or not in number one okay now let's move uh for nine check if you are having count of nine greater than one yes so reduce its counts to uh minus one means a zero so now the nine is not present in your answer okay so nine will be the answer uh part of your answer array next time check for four is four count of four is greater than one yes so then 4 is also the part of your answer and reduce its counts to 0 because uh you have utilized this 4. now you are on this 9. check for this then you are having a count of 9 greater than 1 uh greater than 0 no you are not having the count of greater than zero so this nine will not be a part of your answer similarly this eight will also not be part of your answer similarly uh check if this four uh is part of your answer you can see that count of this four is already zero so this four is also not the part of your answer so your answer will be 9 and 4 i mean as you are giving uk we can write an answer in any order so now let's uh um could uh code this problem up first what we will take a vector of integer answer okay next uh we have to maintain the uh counter now so for the counter of the count of elements that are present in namsun for this you can use an ordered map i am using a vector because uh you can see that uh the ranges from 0 to 1000 so it is always beneficial to use vector because that will further reduce the complexity okay uh so what we are doing vector of int we will maintain a counter vector of size one thousand one and zero and uh first what we will do we will take the count of uh on count of elements that are present in amsterdam okay so what we will do for auto x of nums one we what we will be doing we are increasing its count okay we say you can use auto keyword um auto measure auto automatically is it detects that what is the data type that is present in themselves okay if it will be care then auto will replace it with care if it is in then auto will replace it with ins if it is any other data structure then auto can automatically detect this okay so now what we have to do we will uh iterate the elements of nums too as we have discussed okay like see i mean so uh we are iterating the elements of namsuna and checking if it's count is greater than zero or not okay so what we are doing for auto x of number two we are iterating the elements of num2 check if count of x is greater than zero or not if it is greater than zero then what you have to do answer dot push back x and similarly uh you have to reduce the count by uh minus one to count minus means the count minus is similar to means this is a decrement uh a post decrement operator this is similar to count of x barabber count of x minus 1. this is similar to this operation okay now in the last what we will do we will return our answer so return answer and now let's run the run this code let's submit it i hope it is correct yes it is correct now let's trace this time and space complexity time complexities o and because we are rotating elements only once this is a single for loop we say we in the previous approach our sp uh our time class complexity was n square but space was on as we are reducing the time we have we are increasing the space so our here what is our space complexity is our space compressive is o of n because we are uh of a and uh this is like see uh this is uh o of n or we can say of thousand because we are using thousand uh space so you can also say it is a constant space because that is not depending on the size of numser and m2 and what we are i was telling now us we can use this code and we using this code we can also solve the problem of which problem intersection of two rs okay in uh of part one in the in this part what you have to do now uh each element in the result must be unique means what the only those elements will be the part of your answer which are present in both the arrays we here you have you do not have to worry about the count okay like say 2 is present in both the array but you have also only taken the single instance of 2 only one time you have to take you does not have to worry about the number of times a particular element is present in both rs okay so for this approach simply what we will do instead of decreasing this uh by minus one make it zero so that next time uh for this particular two you have made the count zero so the next time when this particular two will come ah we will not be having any correspond uh no uh next uh for this two you have this is the part of your answer and you have made the count of two zero so that next time when these two will come these two will not be getting any uh account is greater than zero so this these two will not be the part of your answer okay so let me say this is a small modification that you have to do and uh your answer will be the correct okay so uh i hope that uh we are done with both the parts and what i will suggest to you should try both the questions intersection of tourist part one and part two and i hope you enjoyed this video if you are having any doubt then mention them in comment section definitely i am going to answer them apart from their that if there are any suggestions for me then you are welcome to give me those suggestions thank you for watching this video uh we will meet soon till then take care bye thank you friends
Intersection of Two Arrays II
intersection-of-two-arrays-ii
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**. **Example 1:** **Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\] **Output:** \[2,2\] **Example 2:** **Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\] **Output:** \[4,9\] **Explanation:** \[9,4\] is also accepted. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 1000` **Follow up:** * What if the given array is already sorted? How would you optimize your algorithm? * What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better? * What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
null
Array,Hash Table,Two Pointers,Binary Search,Sorting
Easy
349,1044,1392,2282
39
hey guys let's take a look at number 39 combination Sun we're given a set of candidate numbers without duplicates and let's target I'm target find all unique combinations of candidates where they sum up to target the same repeating number may be chosen from candidates for the for example 2 3 6 7 taki 7 of course 7 could be the possible solution and the other one is 2 3 so 2 could be picked twice yeah we can just to use brute force just find out all the possible combination there will be 2 it will be 2 to the power of n right into the like this possibilities so it's not acceptable we need to improve as we did some 3 some or for some problem the first thing we need to do is sort the string so I sorted array because if we sorted the array we can just end stop looking forward like we find 2 3 is 5 and then we got 6 4 6 it will be 11 so we don't know more need to learn no need to continue thinking about the array which has the prefix of 2 3 6 we cannot add any more numbers into the array so we first we sort candidates the next we just use backtrack tracking as we did before we just to keep just keep searching and find the possible solution that's what we did in the last problem which is the sulukule the actual solution is only one and this complicated it would be like a two dimensional array but for here we need mod we have multiple solution and the solution will be simple it's just a one dimensional one dimension array so in this backtracking I will just pass down the temporary result to the iteration function so we try to create a function called a walk so these because every number could be picked twice for this walk I would just need to only receive a temporary result which is called temp result it's empty it's not empty it's a VR 1/2 temporary array ok empty it's a VR 1/2 temporary array ok empty it's a VR 1/2 temporary array ok we finally will walk with the empty result every time we walk we check the empty a checked the ID array first we check if it's satisfies 5 condition so we summon them up mm-hmm them up mm-hmm them up mm-hmm if that's the case maybe we can just pass down the sum also to prevent the sum up every time okay so we just pass down the sum 0 okay if sum equals target we just pushed attempt to the final result first result was empty and finally return results if equals to sum the result push the temp ok and we need to return enable - we stop and we need to return enable - we stop and we need to return enable - we stop walk we in order to terminate the walk process we need to fly if we turn like return false okay then we should stop walking okay for if it is some Ori some to target then there's no need to their needs no need to add more numbers into the array yeah it's gonna be overflowed right it says it's the candidates should be positive integers okay so we can return false if not we could add more numbers in it right so we will try to add all the numbers in are smarter than candidates okay let's push it in when you push it in like we when we get the two we get 2 and the way we get 2 3 push 3 in push to in push 3 in push 6 thing but when we push 6 into the tool we've got B to 6 and it will be 8 so we need to stop so we if ya its we should make it more like a check you should terminate equals walk okay some should be some + num and attempt some should be some + num and attempt some should be some + num and attempt should be called call cut contact contamination concatenation so you can't cat num yeah if I return true okay return true it should be terminated and then if should terminate then we break so these actually is the best part of backtracking we should stop right we found that we cannot continue anymore rather than we just list up all the possibilities and check them one what one by one okay so and if we were done and we're done yeah you try to check the check if the algorithms work the first one the first input is empty it's some zero so it's not here and we try to push two three six seven in number be this and the we should walk two three each number and each and with array of number it's himself and we should return right okay so we should return false and now we walk again with the sum with the number and the array of it number if the sum is squeaks target where which is the case seven we push the first solution to the final result and then we go on right okay so you will be the salmon will be gone so it's got its return so wait a minute yeah and the next one we should push two three six seven in okay the number should be two so we put two - three - six - and then so we put two - three - six - and then so we put two - three - six - and then we will walk them again and in two - but we will walk them again and in two - but we will walk them again and in two - but they're in order so we actually check - two - and then - it's not okay check - two - and then - it's not okay check - two - and then - it's not okay so it's two three it matched and it stopped and then we go back two three yeah three two a - oh there is a yeah three two a - oh there is a yeah three two a - oh there is a duplicate problem if we check 2 to 3 then 3 to 2 actually will be checked so we had a we need to solve this problem maybe we can just improve its the for loop here we can only pick the number bigger or equal to himself like two we can to pick two about three we only pick three start with three right that is a good case so we check the lung here and if num is smaller than what we start okay wait a minute we should start in we should pass in the index also start with I so the next one should be start with I again yeah we need to sorry we need to pass the index also the index should be zero oh this sub not bi but index okay if the index is zero which we should we start with index and yeah the first one is 2 3 6 7 and next one we should walk with a 2 and start with AI which is to eat himself through walk 3 we should start with 3 that which is 1 yeah this should work let's run the code oh no here it's not okay I hope you work Wow just hit off that memory hmm what wait a minute what zero start with the zero sum is zero and the grace okay we lock the sum and index ah no if oh god we need to I forgot to oh we should terminate if it's bigger or that equal to target about if only we equal the target we collect the temporary result it should be better it should be right oh yeah it's concepted nice we removed the log and submit about now let's consider yeah it passes and about the time flex Lee what is the time complexity so the worst case is actually the same nothing like there is a huge target that we need to check every possibility and we cannot finally find them so the worst case it's still worst is o ^ the end I think is o ^ the end I think is o ^ the end I think but January we improved a lot better for some numbers in the middle we can cut down the calculations a lot and space wow it's hard to check final real how many results are there it depends right the maximum should be I don't know wow I cannot understand that I cannot get the time and I cannot get exact time worst time and space complexity the worst case should be like 1 2 3 4 and we have a number of 100 then you could be a super big target and these theses 2 1 2 3 and actually that means we can have a have them each of them as a solution right so actually the worst case should be also Oh 2 n I know man anyway we have finished this problem I think this problem won't be asked in the interview I think but the idea is very simple if you got to search like some we are free to solve the problems like find the all possible solutions of some numbers adding to some target we first make it ordered and then we can terminate as fast as we can by comparing the results to the target and when we walk when we create the iteration function at first we thought it would be just need the temporary array and but we need to catch the sum up without till some we can reduce the calculation by just passing the sum also extra sum and finally we think we'll you found that there is a duplicate problem we need to avoid some duplication so we need two extra index yeah that's how I solve this problem hope it will help you to some extent see you next time bye
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
1,721
hey everyone welcome back today we are going to see problem number 1721 swapping notes in a linked list first we will see the expression of the problem statement then the logic and the code now let's dive into the solution so here I've taken the first example from the lake website so we are given a linked list where we need to swap the kth node from the beginning and the kth node from the end right so we have K is equal to 2 here we need to pick this second node this is one and this is 2 from the beginning now we need to pick the second node from the end as well so this is 1 and this is 2. and we need to swap these two values right so here it becomes 4 and here it becomes 2. so now we are going to see how we are going to do this so first we are going to find the kth node from the beginning of the linked list so initially I will be having a left node pointer I will point it to the head of the linked list so to find the kth node from the beginning it's pretty simple so I will move my left node using the loop where I will start from 1 to K right so here K is 2 and we will start from 1 right so since it is 1 I will move my left node then 1 increases to 2 then that Loop is ended so this will be my kth node from the beginning of the linked list so in order to find the kth node from the end of the linked list I will have a right pointer pointing to the head of the linked list then I will be having a current pointer where I will initialize my current pointer as my left node so my current pointer will be pointing to the left node right then I will run the loop until my current dot next is now right by the time I will be moving my current pointer and right pointer simultaneously so in this case I will move my right pointer and my current pointer so right will point to the second node and current will point to the third node then again the Right Moves and current moves then again Right Moves and current moves so now current dot next is now so after that we just swap the left and right node values so here 4 and 2 are exchanged right so the time complexity will be order of N and space will be constant space that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially we have to find the kth node from the beginning of the linked list so we are initializing a left pointer as my head then we will be iterating through from 1 to K where I will move my left pointer then in order to find the kth node from the end of the linked list we have to initialize the right pointer pointing to the Head node then we have to initialize current variable as my left node right we will point the current variable on the left node where we found previously then I will write another loop where I will run the loop until my current dot next is null right I will move my current pointer and my right pointer simultaneously in this Loop then we just need to swap the left and right values then finally we need to return the head node right that's all the code is now we will run the code as you guys see it's pretty much efficient so as I said previously the time complexity is out of N and space will be constant space thank you guys for watching this video please like share and subscribe to get notifications of my videos press the Bell icon below and also if you guys have any kind of questions put that in the comment section I will be very happy to answer your questions keep supporting happy learning cheers guys
Swapping Nodes in a Linked List
maximum-profit-of-operating-a-centennial-wheel
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Array,Simulation
Medium
null
790
Hello friends welcome back tu de stylish code youtube channel so today our question is a medium level problem of late code isko aur usko given hoga tu types of tile tu cross van domino app like agar hum baat ka board of question like tu agar hamara If there is a van then our boat I think will be like this. If there is in time of van and if our vote is tu hai tu ki size then our board will be like this. Okay, this is our board and inside it is given, we can type two inside it and like ours. There will be tiles of this type or this one type means okay, you can make it cry with whatever type we want, so this is ours, so if we are given in the question, like the first explanation which they have given. = 3 and the answer we are giving is 5 in it, so = 3 and the answer we are giving is 5 in it, so = 3 and the answer we are giving is 5 in it, so if we talk in three, we will have three crosses, our board is okay, its on 3, so inside it we put tiles of two, then 123 if we put tiles of two again. So the tiles will look like this in this step and if we do it like this then this shop will be created and it will have an opposite like this, it will be like this, total is five, okay if this was our pick question. Explanation If we look at the solution in this, then like I have tried some tests in this, if our N, if there is a van, then we will have the answer van N. If we have you, then the answer will come in this, you N is our three, then it will be in the case. The answer will be 5n. If our is four then our answer will be 11 and if n is our 5 then our answer will be 24. So if we call this thing was the explanation of our question. If we want, we will solve our question with this. So like, if we look at the value of three, then three, how can we write three, you cross, plus one, it is equal to 4, how can we write, you cross, five plus 11, and if we see the answer, then 5 and 11 are fine. In this case, it becomes this and if we look at the case with n = 5, then our answer is 23, which means we wanted the answer to be 24, which means we are thinking of changing it to van, but in this case. If it is not made, then instead of one more van, we try another number. If instead of van, we try another number, then like, if we want here, if we add plus van here, then our answer becomes 24. So if we see, where is the answer, if we keep the value of tu here, if we do 5 - 2, then it if we do 5 - 2, then it if we do 5 - 2, then it is three, then can we write our question in such a way that we are writing here. This was n - 1 + tha. Okay, so This was n - 1 + tha. Okay, so This was n - 1 + tha. Okay, so we write this as you cross n - 1 n - 1 n - 1 plus n minus 3. So now we check the pipe in this. How does our 5 become Swami, before we change anything else. So like you close f3 - OnePlus and by doing this we also remove the app for, so we have to fix this thing, initially our which is un if it is zero, whatever will be our DP error, whatever we will take the error inside it at the zero of n. We have to keep van n equal tu van hai n = 2 I think you must have understood the approach to solve this question, then first in the court here the condition is if my n less give equal tu hai him. In case it is okay to return to end, now after this I will store my answer inside it equal to new end and its size will be I N + 1 N + 1 end and its size will be I N + 1 N + 1 end and its size will be I N + 1 N + 1 so because I have to go from zero to end then DP will be the value of zero. As we had discussed, value of van dp van will also be our van and value of tp2 will be ours so here we will apply the formula which we have created i = 2 formula which we have created i = 2 formula which we have created i = 2 star bp high mines van plus bp if we talk about given question If our answer is missing then we will have to do modules so we will create modules function for that what do we make here zero mile to van tu three four 12345678 I think = ok and let's do this here and this Let's submit here, before submitting, there is a doubt, wait, I make it long and I do the answer here, run it once again, okay, I submit, this is my code successfully submitted, after this if If we talk about its time complexity, then its time complexity will be n because here we will print the pay and time slow and if we talk about this space complexity, then in space we have created a space here in an edition named DP so DP's time. Our complexityon will also be on, if we optimize it a little in terms of space, then our solution will be like this, we remove the DP from here, remove the DP, the longest zero will will will not come and whatever our second will be. If there is a term then we give it 2 and here we will create it as a long variable Okay, now if we have to bring back the value of all then we will change the value of A to C and the value of C we will We will change it from di and in the last we will hit return learn let's run this and here it was open to put the sample Now again we run this here okay and we will submit in this Our today's solution if If you liked our solution then like the video.
Domino and Tromino Tiling
global-and-local-inversions
You have two types of tiles: a `2 x 1` domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return _the number of ways to tile an_ `2 x n` _board_. Since the answer may be very large, return it **modulo** `109 + 7`. In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile. **Example 1:** **Input:** n = 3 **Output:** 5 **Explanation:** The five different ways are show above. **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 1000`
Where can the 0 be placed in an ideal permutation? What about the 1?
Array,Math
Medium
null
1,091
and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 1091 shortest path in a binary matrix before we jump into this problem i just want to ask you please to subscribe to my channel i have a goal of hitting 1 000 subscribers by the end of may and i need your help to get there if you find value in these videos and they're helping you get jobs in fang then please leave a like comment on my videos and most importantly subscribe that being said let's get into this given an n by n binary matrix grid return the length of the shortest clear path in the matrix if there is no clear path return negative one a clear path in a binary matrix is a path from the top left cell ie00 to the bottom right cell ie n minus 1 and -1 bottom right cell ie n minus 1 and -1 bottom right cell ie n minus 1 and -1 such that all of the visited cells of the path are zero all of the adjacent cells of a path are eight directionally connected i.e they are different and connected i.e they are different and 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 on this path so let's look at two examples here so we have this grid 0 1 0 and basically what's the length of the path well we can see that we start here and we're allowed to actually traverse eight directionally so this is one of those problems where you can actually go eight directionally sometimes you can only go four directionally but in this case we can go diagonally so our best path is simply to just go to the right and we'll end up where we need to go and you know this is two total tiles so that's why we return to here so if we look at this other example with this um you know a little bit more complicated grid essentially we start at the top we go here and then here and that's going to be our shortest path so it seems pretty simple when you look at the diagram and it's easy to figure out what the shortest path is just by looking at it but obviously we need to write an algorithm to solve this problem for us so what do we want to do here well anytime you hear shortest path the thing that you typically want to think of immediately is going to be a breath first search because we can actually think of our matrix here is actually an undirected graph and what that means is you know each direction that we can go into is you know like an edge we have from our current node and using a breadth first search over an undirected graph will always give us the shortest path so if a shortest path exists because remember we're not guaranteed to have it we could be blocked and we'll touch on some edge cases when we get to the code editor if a shortest path exists then using a breadth a search will give us whatever that shortest path is so that's the approach that we want to take to solve this problem and it's going to be a standard breadth-first search that we a standard breadth-first search that we a standard breadth-first search that we do uh throughout a matrix right it is a little bit weird to think about breadth first search when you're not using like a tree or graph but you can actually do it here and it's quite simple uh so what we're gonna do is we're gonna go to the code editor we're gonna address some important edge cases because there are a few in this problem that if you don't address them you could potentially um you know lose points to your interviewer because it shows that you didn't think about uh the problem before getting started so let's go to the code editor and we will write the code editor and it's time to write the code for this problem remember that i said we need to address two edge cases before we begin and this is going to show our interviewer that we're actually thinking about the input and you know we're not just jumping into our solution so let's think about this you know it is possible to not actually have a path right the problem tells us if there's no clear path return minus one so that means that we could be blocked and what's one thing that we want to check before we even start doing it well if our starting point is a one then there's no way for us to start from there because remember a clear path needs to be all zeros so if our starting point is blocked then we know off the bat that we can't actually get to our ending point similarly if our ending point is a one which means it's blocked then there's no way to possibly get there from our starting point even if the entirety of the matrix is zeros but that last you know target cell is a one then there's no way for us to get there so we can check immediately whether or not we can solve this problem um by just knowing whether or not the start and the end are you know even reachable and you know it's not guaranteed that we'll be able to find the shortest path but at least we don't have to go into our breath first search to figure that out so you know that's just like one bit of an edge case that we can check beforehand so we can say if grid zero which remember is our starting point um or grid minus 1 -1 -1 -1 so essentially what this is checking is if grid 0 so if it's a 1 then this statement will be true obviously um integers non-zero integers will evaluate integers non-zero integers will evaluate integers non-zero integers will evaluate to true and zeros will evaluate to false so basically if we have true here then you know it's not possible to reach the start and then same with the final position if it's a one then we can't actually do it so we can simply return minus one oops minus one okay now what we need to do is we need to kick off the breath first search so to do a breath first search you typically use a cue so let's set that up so we're going to say collections.deck and what going to say collections.deck and what going to say collections.deck and what we're going to put into the queue is going to be our current coordinates x and y and then also a variable to keep track of um what our path length is right since we count um being the start tile as part of our path right because you can see here this path length even though we've only jumped one tile we count it as a total path length of two so that means that the starting tile we need to count it as one so we're going to initialize our q here as basically a tuple containing 0 1 so this is the x coordinate the y coordinate and then our current path length and then we need to define all the possible directions that we can go in so what we're going to say is we're going to say directions and you know be careful here to actually get all of the directions so we're going to say 0 1 we can go 0 -1 -1 -1 we could go one zero we can go minus one zero we could go one uh one minus one um minus one and then minus one okay let's just count these make sure we have eight one two three four five six seven eight okay cool looks like we have all the directions written out now we actually just need to perform the breath first search so let's do that so we'll say while we have q basically while we have summing the process we're going to say that the current x the current y and our path length is going to equal to whatever is in the left side of the queue so we're going to pop from the queue and we're basically now we're going to check okay are we at the end have we reached our you know target cell which is the last position in the matrix so we're going to say if x so if x comma y equals to let's see length of grid minus one and then this is going to be length of grid zero minus one uh essentially what this is doing we're just checking whether or not our current x and y is equal to the x and y coordinate of the bottom right corner which is what our target is if we have uh if we're at that point then we can simply return whatever the path length is otherwise we need to go eight directionally and when we go eight directionally remember that we can actually go outside of the bounds of our matrix so we're gonna have to check that the square that we're moving to is not only open which means that you know it's a zero there's no point of us going to a one tile because i would just waste space and waste um you know iterations through our queue we need to make sure that we're actually going to zero and that we're actually within the bounds of our matrix because obviously if we try to go outside of the bounds and then access the index of the values at that index then we're going to have an index error and our function is going to blow up so we're going to say 4 x increment y increment in directions what we want to do is we want to say that the new x is going to equal x plus the x increment and the new y is going to equal to y plus the y increment and now what we need to do is check whether or not we're moving to a valid tile so let's check whether or not our new x is valid so we're going to say we're going to make sure that the new x oops if 0 less than or equal to new x less than length grid so basically we're checking whether or not the x is a valid position and we're gonna do the same thing for the y here so new y less than length grid of zero and then we also need to make sure that we're actually moving to a zero remember that we can't move to uh a tile with a one so there's no point of even adding it to our queue so we're gonna say grid new x um new y and we're gonna say and not new grid so if grid new x new y is zero then obviously that will evaluate to false and then not that will be true so we wanna make sure that you know everything here is true that we're in our bounds and that we're moving to a tile that is actually a zero so at this point what we can do is we want to make sure that we don't actually uh and apologize for the sirens in the background um we what we want to make sure now is that we don't go back on ourselves because we'll just get caught in an infinite cycle so what we want to do here is we're going to overwrite the position for the tile that we're moving to by setting it to a one and what this is gonna do is basically it's gonna ensure that you know we don't um go back on ourselves now this does assume that you can modify the original input if your interviewer says i don't want you modifying grid then what you need to do is actually use a set and you're going to keep track of the tuple pairs for each x and y coordinate and then you're just going to be checking whether or not you visited that tile before but in this problem we're actually allowed to modify that input so we're going to be doing that and the last thing we need to do is say cue.append cue.append cue.append new x new y and then distance plus one because obviously we've now gone an extra tile and what we want to do is either we're going to find a path length here so we're either going to reach the bottom right corner or we're not going to which is the case where this while loop will break because we no longer have any valid paths to go down in which case we can just return minus one and i just realized that we've made a slight bug here by you know similar to how we were overriding um our x and y coordinates in the grid uh we actually need to do this for the initial position um so that way we don't get caught in an infinite cycle because we're always moving one forward uh we're never doing it um like we're this is forward looking right because we're currently at x and y but we're setting it for the new x and the new y we haven't technically moved there yet because it's not in the queue so we would never actually set it for the initial position which is why we need to do it uh here so that is that so let us just run this make sure we haven't made any bugs and name distance is not defined oh i call it path length oops my bad path length okay that should now run okay cool it does apologies for that little mistake there but no big deal so what is the runtime complexity for this algorithm well in the worst case uh our matrix is essentially going to be all zeros and you know it's just going to be the path from actually no it won't be all zeros uh i guess we can think of it as being like zeros only on the edges right so we would have to traverse all the way through the columns and then all the way down the rows to reach our final position so this is going to be a big o of n algorithm because the path length is going to depend on basically the size of our grid um so we can think of this as being big o of n and then for the space it's also going to be big o of n because obviously we have a q here and the amount of idle items in our queue is going to depend on you know the size of our grid so we can just think of it as being you know big o of n or you know if you want to get really pedantic it could be like rows times columns um or rows times columns but i mean this is just you can think of it as just being big o of n um so yeah that is the approach that you want to take to solve this problem i think your interviewer is typically looking for the bfs algorithm to solve this um there is i guess it's worth noting i think an a star algorithm which can also solve this problem uh in you know big o of n time but to be honest it's really complex the chances of you pulling it out uh during the interview and not making any mistakes are quite low so definitely stick with the bfs solution for this one you know don't risk it if your interviewer then asks you can you do it with a star then you know you better hope you know it if not i mean most likely you probably won't have that most interviewers are going to be happy with the bfs solution and i think asking for anything more is a bit harsh so you should be fine with the bfs don't worry about it if you understand the solution this is more than enough uh for most companies and most interviews so that being said if you enjoyed this video please leave a like comment subscribe let me know if there's any videos or topics that you want me to make videos on i'll be happy to make those for you guys just let me know in the comment section below and i'll do my best to get back to you otherwise happy elite coding thanks for watching bye
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
482
hi guys this is Nikesh here so today I'm back with an another Google interview problem so the problem name is license key formatting so in this problem you have been given instinct yes and it is okay this thing is something like this so if you can observe the string has been divided into n plus 1 pipes by n number of dashes okay so this one this strain has been divided into four five one two three four and you have three dashes and so you have also being given an input K which is four so in this case what you need to output is you need to form a string which will have you will have K number of characters in every group so basically the first group has four characters second group has four characters so that's the first key point and second key point to observe here is the input string contains the lowercase letters whereas the output string contains only the uppercase letters so one is uppercase knitters second is K groups so key characters in every group so one more condition given here is the first loop can contain lesser number of characters danke so it's not necessary that the first group should contain a number character but it can contain lesser number of characters so first rule can be less than key so if you see the problem rate so you don't get up the first rule so you need to first form the last loop so that it has on the phone all the K characters so the good data structure to use here is the stack so let's see how we can solve this problem by using a stack let's say I take a stack so first we traverse the string from left to right and input all the characters to our spec and whenever we are inputting to the spec we make sure that we input the uppercase letter of that particular character so in this case it will be fine yes three Z and we whenever we encounter a - we don't push it to the stack we a - we don't push it to the stack we a - we don't push it to the stack we push only the alphanumeric characters and not the - okay so in this case I do and not the - okay so in this case I do and not the - okay so in this case I do not push - whereas next is - and if you not push - whereas next is - and if you not push - whereas next is - and if you can see I input the uppercase letter of this one and then into 9 and then W so now we need to pop all the elements from mustache and everything before we append the character to a result string and increment the count so whenever we increment the count we also make sure that the county is not equal to K if it is equal to K then we need to append that - to our results thing so we need that - to our results thing so we need that - to our results thing so we need two variables which is a and then account and we need to check this count is equal to K and that then append a - is equal to K and that then append a - is equal to K and that then append a - so let's see how this is work so our result strings is this one and count is initially 0 thank you so for the first - I of the character W so for the first - I of the character W so for the first - I of the character W and happened into the string results thing the count becomes 1 so 1 is not equal to 4 in this case so we continue we power 9 count is 2 then it's e count is 3 then we pop - and count is 3 then we pop - and count is 3 then we pop - and count becomes 4 so in this case as come is equal to K we need to append a dash to the special string so we appended - and the special string so we appended - and the special string so we appended - and then we make the count as 0 okay so now before we start the popping the element from the stack again so now it's Z and count becomes 1 next is 3 1 becomes 2 next is death then fight and then fight come becomes we are then compared the condition the stack is empty so this now the resulting found is like this so it's w9e - - z3f and that fight but we need w9e - - z3f and that fight but we need w9e - - z3f and that fight but we need something like this so basically if you can observe we need to reverse the string what we have formed to get the output string so basically at the end reverse the result okay so basically result will be five f3g - two e9w result will be five f3g - two e9w result will be five f3g - two e9w so it's exactly this thing what we needed okay so this is one of the important question as we Google introduced and next I'll be showing how we can solve this by recording if you want me to solve any particular question please let me know in the comment section below and keep learning every day thank you hi guys so this is nikasha so today I'll be writing the code for the problem license key formatting so this is one of the important question asked in a Google interviews as I already explained the logic and how to solve this problem I will start writing the code right away basically first we need three things one is stack let's name it s T we need result string to show the result and we need account call will that change lies with pound with zero the first thing what you need to do is you need to traverse the string and push all the characters to a stack except the top except the dash and whenever you're pushing you need to make sure that you are pushing the upper case of that particular character we have enough she is not equal to you - we have enough she is not equal to you - we have enough she is not equal to you - then we need to push it okay now we have Travers to the string and pushed all the uppercase characters uppercase of alphanumeric characters to a star so for now we need to start popping it and append to original string and every time we happen we increment the count and once the count is for the which is gay we need to append and - and make the we need to append and - and make the we need to append and - and make the count to zero we basically will loop until our stack is empty every time we need to appear in the result append the top of the character top of the stack to our results and you need to pop it as well and you need to increment the count so if the count is equal to King and if stack is still not empty this is not the last character then we need to happen and also make sure we make the counter zero okay so after at the end of this while loop the stack is empty we have appended all the characters to a results thing from top to bottom so in this case the result is in reverse order so we need to basically reverse it and then return the result okay so this is the problem let's run it and see if it passes for all cases looks like the three should pass for the base case let's submit the problem okay it's on so it has been accepted so this as I said this is one of the important question has done a Google interviews so if you want me to solve any other particular question please do let them know in the comment section below and if you want to get notified whenever I post any video please do like share and subscribe and hit the notification button as well and keep learning every day thank you
License Key Formatting
license-key-formatting
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first group, which could be shorter than `k` but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return _the reformatted license key_. **Example 1:** **Input:** s = "5F3Z-2e-9-w ", k = 4 **Output:** "5F3Z-2E9W " **Explanation:** The string s has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. **Example 2:** **Input:** s = "2-5g-3-J ", k = 2 **Output:** "2-5G-3J " **Explanation:** The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. **Constraints:** * `1 <= s.length <= 105` * `s` consists of English letters, digits, and dashes `'-'`. * `1 <= k <= 104`
null
String
Easy
null
1,269
all right let's take a look at elite code 1269 number of ways to stay in the same place after some steps so we're given in a steps so the number of moves or turns we can take and then a length of the array that we're working with and then our goal is to return the number of ways there are to stay at index zero so we start at index zero and after three moves or three turns we want to see how many different ways there were to stay at index zero and at each turn we can either move left stay in the same spot or move right so this is a pretty good this is a really good problem for recursive gfs plus memo and i think it's so intuitive this is a very this should be very straightforward if you watched my previous question which was student attendance records i started out by doing that problem with recursive dfs but it timed out because the constraints are a little bit high but for this question the constraints are pretty low and this is a perfect problem for recursive dfs plus memo so let's take a look at how we can visualize this in a tree format so basically we're going to just keep track of two variables so we have two parameters for this dfs method that we're going to create and we're going to just update these two variables every time so what are they there it's the steps remaining variable and the x position um so basically let's say let's take this first one for example we have the array of length two um also what that means by array of length two is we start at index zero right we start at index zero um the array length means that it's going to the right so if you start at array 0 then you can only go right at this first position yeah the array is to the right of um to the right of index zero so the array of length two would look like this right so index zero and index one um yeah so basically when you're so also you if you go out of bounds oh yeah there's another constraint that says the pointer should not be placed outside the array at any time so if we ever go outside of these bounds if we go to the index of negative one or if we go to the index of two then we're out of bounds right so those are two other terminating conditions we can take care of in our recursion so okay so let's look at this example this first example let's see how we can visualize it with a tree so we have three steps remaining and our x position is at zero we have three choices at every turn right we can either move left stay in the same spot or move right so moving left would cause our so obviously everything in this second level would mean that we would have one less step remaining so obviously from three down to two and then the second value is the main one we care about which is x position right so if we go left our x position goes down one if we stay in the same place our x position stays the same if we go to the right our x position moves up by one so pretty much you know if this second value ever goes you know above the length or goes below zero then we can just terminate early so this branch will just terminate and return zero and then so eventually once we reach zero steps remaining and simultaneously if the x position is also zero then that will return one right so this um this leaf will return one all the way back up to the top and then let's see so i guess this branch i didn't write it out but you can imagine that if you were to move left from this position you would also get to a end result of zero so there's four possible ways right that will return a x position of zero when there's zero steps remaining so you know everything else will return zero and those four possible methods or paths will return a value of one so eventually you'll get a answer of one or answer four combined and yeah so let's see how exactly this can uh be written in code it's very easy to implement in code and so uh i'll kind of show you so i use cache just because of how powerful it is to memoize my each of my calls but i can show you what it looks like without using cash um the old school way if you will so basically we have our um so i'm going to get to this pruning step in a second but um the out of bounds conditions are here right so if the index that we're at is greater than or equal to the array length then it's over stepped to the right if the index is less than zero then we've overstepped to the left aka like we've gone out of bounds to the left so in each of these two cases then we should return zero so then the case where we return one is when the steps is zero and the index is zero and um i guess this notation just means that um if the steps is zero but the index is not zero then you should also return zero um yeah so then like you know basically you'll just have a temp variable which will keep track of the answers from the three different dfs calls right because you can try all three different combinations at each uh at each turn right you can either go left you can stay at the same place or go right and then at the end you should just return the modded value at each step um so what it looks like with a cache is just um if we were to cache it then we can just say cache of um steps index equals temp and then we'll just return um equals temp mod and then we can return um cache of steps index and then also we'll have to just do a check here so if steps index in cash then return cache of steps index right so this will just go check to see if we've already come across this exact same sub problem before and if we have then we'll just return whatever was cashed in there earlier so oh yeah back to the pruning right so basically another optimization we can take is if there's not enough remaining steps and our distance from our current location back to the origin is greater than the number of steps we have remaining then obviously what's the point of trying to explore that path there's no way that you know let's say we're at position you know whatever this is five or something four index four and we only have one step remaining right what's why would we even bother with this right one step is only going to get us down to three we there's no way to get from this current position back down to zero right so we can immediately just you know short circuit and prune is what they call it so we can just immediately return zero and stop execution here so that's the pruning that we do and yeah so let me show you this cache method so with the cache this is what it will look like um right so i just like to use this built-in lru funk tools cache on in built-in lru funk tools cache on in built-in lru funk tools cache on in python which is pretty nice so you can get rid of these uh hard-coded hard-coded hard-coded you know er i mean sorry not hardcoded but just like annoying things to write you don't have to write that stuff it'll cache the results of the different steps index combinations for you and see if it exists so yep that is how to do this problem if you guys have any questions please um oh what did i do yep okay so if you guys have any questions about this leave in the comments if you have any questions you want me to explain leave in the comments if you have any feedback for me please go ahead let me know and thanks for watching
Number of Ways to Stay in the Same Place After Some Steps
market-analysis-ii
You have a pointer at index `0` in an array of size `arrLen`. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers `steps` and `arrLen`, return the number of ways such that your pointer is still at index `0` after **exactly** `steps` steps. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** steps = 3, arrLen = 2 **Output:** 4 **Explanation:** There are 4 differents ways to stay at index 0 after 3 steps. Right, Left, Stay Stay, Right, Left Right, Stay, Left Stay, Stay, Stay **Example 2:** **Input:** steps = 2, arrLen = 4 **Output:** 2 **Explanation:** There are 2 differents ways to stay at index 0 after 2 steps Right, Left Stay, Stay **Example 3:** **Input:** steps = 4, arrLen = 2 **Output:** 8 **Constraints:** * `1 <= steps <= 500` * `1 <= arrLen <= 106`
null
Database
Hard
null
965
hello everyone so in this video let us talk about an easy problem from lead code the problem name is uni valued binary so you are given a binary tree and you just have to check that whether it is uni valued which means that all the nodes have the same value now you can check it out it's very simple you just do a whatever traversal you want on this particular tree and just take the first value out of the string okay whatever the first value and just match this particular value with all the other values if they are matching it with this particular value that is fine it is a uni value if at any point it doesn't matches out then it is not a uni value so the multiple approaches uh to solve this problem out you can do multiple type of traverses whatever you want on this particular tree I've done this whole solution so what I've done is that first check that if the root is already null then the answer is true that it is only valued like it's just a h k if the root is not null which means that it has all like at least one node just take the root node value and store it in a global value which means that I have now the value that I want to compare with all the other nodes okay now I'll just do this whole traversal on this particular node what I'll do is that if the root is null I just returns 2 that is we have reached a state that there is no node and we have not found out that it is false so I just return four like true or else if the root is not null and the value of the root value or like any node value that I am iterating or if it is not equal to the value that I want to then I return false because all the value should be equal to this particular value if they're not equal then it is written false so if any root value that or any node that I'm iterating over if it is not equal to this particular value then it unfolds or else we just do a type of traversal just do left or right this okay risk function will be returning whether any sub t on the left hand side or right hand side returns uh false which means that it is having a particular node that is not having the same value or with all the other nodes so this OK function will be called on the left hand side as well on the right hand side and this will be like Traverse and returning out whether all the values are same or not and then both of the sub trees should be having the same value so both sum should be returning two that's why if any one of them return false then it is bad so that's why it's an and operation that both left subtree and right said subtree should be returning out true that it all the values inside those subtrees are having a same value so this function is a recursive function which is just traversing all the whole Tree in O of n time public city so uh and just returning out whether the subject that they are responsible for have the same value uh that we have matched with this particular value and this time so you can pause this video and try to write in the code of yourself by like you can try it by yourself as well it's not too difficult to understand as well as right so that's your logic and the code part for this particular problem as well if you still have a dots you can mention in the coin box of this particular problem thank you for watching video till and I will see you in the next one lucky recording and bye
Univalued Binary Tree
unique-email-addresses
A binary tree is **uni-valued** if every node in the tree has the same value. Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._ **Example 1:** **Input:** root = \[1,1,1,1,1,null,1\] **Output:** true **Example 2:** **Input:** root = \[2,2,2,5,2\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `0 <= Node.val < 100`
null
Array,Hash Table,String
Easy
null
23
hello and welcome back to the cracking fan YouTube channel today we're going to be solving lead code problem number 23 merge case sorted lists before we do I just want to ask if you're enjoying the content please leave a like and a comment it really helps me out with the YouTube algorithm and a subscription really helps the channel grow all right you are given an array of k-linked lists you are given an array of k-linked lists you are given an array of k-linked lists each linked list is sorted in ascending order merge all the linked lists into one sorted linked list and return it so let's look at a very basic example uh where we have the three lists here right one four five one three four uh two and six so let's kind of just visualize how we might do this so obviously we want to sort this and keep it in ascending order so you know we have two ones here which is the smallest element and then we have how many twos so there's one two do we have any threes yeah we have a three uh do we have a four yeah we do uh do we have a five yeah we do actually we have 2 4 sorry and then we have a five and then we also have a six and there you go there's your sorted linked list so obviously doing it like this is really simple but you know we can't just write it out by hand we actually have to write an algorithm so the simplest way to do this would actually be to just extract all of the elements because they're linked lists right these aren't actual links so we would actually transform them to lists so one four five um and then we have one three four and then we have two six right and what we can do is actually just concatenate all of these together so we could say one four five one three four uh two six and then what we could do is we could sort this to get it in the correct order so we'd get one two three four five six and then we would uh make a linked list so this works and it's going to be n log n time because of the sort uh for the space complexity you're going to need Big O of n because you need to make the list uh sorting also takes big O of N and then you have to return a new linked list and that's also going to be Big O of n but if you do this you're not going to pass the interview uh this is not what they're looking for this is the naive solution so definitely don't do this but this is one approach where if you're struggling to come up with something this is at least the most basic way to solve it now let's actually think about what the kind of optimal way to do it is and ideally we can achieve still some sort of like logarithmic time uh in actually combining them but can we actually do it without any extra space so what we're gonna do is we are essentially going to have our lists right and what we're going to do is we're going to actually merge pairwise lists so we're going to merge these two together and this one actually it since we have an odd number this one doesn't get merged yet so we would merge these two into one list so this would look like one uh three four five and then that would be the new merged list and then we'd have two six and then what we can do now is actually merge this one down into our final solution so one two three four five and that would be the final solution so why do we want to do it this way well if we merge the linked lists um you know as linked lists then we actually get Big O of one uh space complexity because we don't create any extra space so we need to merge the linked lists uh as they are to get that Big O of one space complexity because we don't actually create new nodes we're just appending uh nodes so we have this merge here uh and we obviously are going to do this you know a certain amount of times so what's going to happen here is that because we're actually merging two at a time and if we had another one let's say it was like six eight here that we had to merge since we're doing two at a time we're actually cutting down our space um buy two every single time so what this actually means in the end is that um you know we would be essentially having a log K uh merge time because we cut down the solution so it's basically log base 2 of K or k is the number of linked lists we want to make or that we have so since we're cutting it down by two every time it's actually log base 2 of K and remember that merging to linked lists is going to take Big O of n time right so that means that our final um space time complexity would be Big O of n log K and our space complexity would actually be constant because we're doing the linked list merging in place so hopefully that makes sense right so we have lists here and we merge them in pairs so therefore you know at each iteration of our merging we have you know half the number of inputs that we need to merge every single time right so if we had eight in the beginning then we have to do four and then two right and same thing you know if we had 16 or 32 basically we're cutting it down in half uh each time right and because we cut it down by half that's actually going to be a log base 2 operation and then there's obviously K total lists we need to merge so the time complexity is going to be or the amount of merges we need to do is log K and then obviously it takes big O of n to actually um merge them so that's where we get n log K from obviously doing a linked list merge in place uh if you remember from the easy lead code question on this is going to be constant space and that's where we get this optimal uh time and space complexity so hopefully that makes sense implementing this is a little bit tricky it's a bit annoying just because uh the way that you actually have to implement it uh even though you're merging them it's you'll see in a second what it means um there are some kind of tricks you need to do to actually get the merges down but this is just the general intuition we'll go over how to actually implement it in a second because it is a little bit complicated and I think it's easier to just see it in code so I'll see you in the code editor let's type this one up and hopefully all the confusion should go away if there is any so I actually lied we're going to look at one final diagram here just to understand how the actual merging happens in case it wasn't clear so let's look at this uh list of linked lists so basically we have um you know six lists here right so what we want to do is we want to merge them in pairs right so we essentially take list 0 and list one and merge it into one list two and list three merge it into one list four and list five and merge it into one now it's important to realize that our original input is given to us as a list where we have like linked list 0 linked list one linked list uh two on and on right what you need to realize is that when this merging happens between say linked list one and linked list 0 is that we don't actually get rid of any of these linked lists we're actually merging them into linked list zero so our original input array will actually not shrink even though you know the actual work that we need to do shrinks by half each time this original list won't actually shrink which is important because we're going to need to actually move some pointers to actually figure out which lists we need to merge so when we do the merging we always merge so if we have a pair of uh you know lists that we need to merge we're always going to merge the second one into the first one such that first one always becomes the bigger one right we always merge three into two uh four into five one into zero right and then we can do the same thing right here so when we have zero and two we want to merge you know two into zero and then we're going to be left with zero and at the end list the first item in the original list will actually be the linked list with everything merged into it so that's one thing that's important and it's important to realize that like I said in this list we're modifying the original input here so even though it doesn't show like list one is here actually in the original input it's still technically there right just because we've merged it didn't mean it just got deleted it's still in the list but we're not actually considering it anymore so every time we merge notice how the interval between merges is one in the beginning right it's always a difference of one and now when we go to the second iteration emerging it's actually going to be a difference of what so to go from index 0 to index 2 is actually going to be a difference of two right same thing from two to four so every time you actually increase the um the distance here or sorry you merge you actually need to increase the distance of the like index that you're looking at right so here we want to merge zero with you know four and if we had more things we'd merge from like five up until um you know nine right so every time you need to increase the interval to actually find the list and the reason we do this is remember that these like lists that got merged previously they don't get deleted from the original list but we still need to access the correct index of the list that was previously merged so hopefully you understand this part because it's crucial to the actual problem and um understanding how you need to basically move your interval uh basically the gap between the actual list that you need to merge changes each time that you merge right it's also going to uh increase right so it starts at one and then it doubles to two and then it goes to 4 8 16 32 and on however many lists you have so you need to actually um keep that in mind and we'll see that in the solution so I just wanted to add this little extra portion just because I know that in the coding if I didn't really talk about this beforehand it might be confusing so hopefully you guys appreciate this now let's actually go to the code editor and type this up it should be a lot clearer we're ready to actually do the merging so the first thing that we need to do is if our lists is given to us as an empty list we don't have anything to merge so we can simply return none right so we're going to say if not lists uh then we just want to return none here because there's nothing for us to merge now remember that we need to keep track of the interval here right and I told you the interval starts at 1 because we're going to be merging pairwise um lists in the beginning and then remember it increases to 2 after the first merge and then 4 8 16 and onwards so the interval will start at one and if this doesn't make sense please go back to the diagram and look at um the illustration and actually walking through the code might help you understand it so the interval starts at one and basically we want to go until the interval is less while the interval is less than length of lists right if the interval gets so large that it's actually spanning over the entirety of the uh list then there's no way we could actually get two possible lists so that's when we know to stop so we're going to say while interval is actually less than the length of lists then we have to keep going so we're going to say 4i in range from 0 to the length of the lists minus the interval uh interval times two so let's explain this part so what we want to do is we want to merge uh every pairwise interval right so we start at interval zero and we basically go into the length of the list minus the interval right that is the stopping point for where we want to go um and every time we're actually jumping interval times two because remember we need to once we merge let's kind of think about this so we have one two three four five six seven eight so the reason that we have it set up this way is obviously we start with an interval of one and we're going to merge one and two together right so this will then become into one but now if we were to Simply increase the interval by whatever the interval is which is one then our next value would actually be two but we already merged it so that's why we need to skip over this value which is why we have interval times two so we now go to three and then we merge the one next to it so now three and four would get merged into whatever that is and then we do the same thing right if we were to go to 4 next we've already merged four with three so we need to skip over four and now go to Five all right so we'd merge five and six into one and then the same thing right we don't want to merge six into seven because we already merged it into five so we just need to merge seven and eight together and there we go and obviously we want to go to length of lists minus the interval because we don't want to overshoot our bounds here because we're actually jumping by 2 each time so hopefully that makes sense that is essentially how we're going to uh Define the kind of the which ones we need to merge at our current uh iteration so we have our for Loop and what we're going to do is we're going to say lists of I is going to be self dot merge and we'll write that function in a second um where we're basically going to pass lists of I and we're going to pass lists of I plus the interval right because remember the interval basically tells us the gap between two uh lists and those are the two that we need to merge right I and I plus whatever the interval is when the interval is one it's just going to be the next index over when we've already merged it once interval will become two so we now need to look two indexes to the right of where we are to merge them so hopefully that makes sense at the end of this for Loop what we need to do is we need to double our interval now because we need to basically you know we've cut down the number of lists by two but remember we're just reassigning lists of I to whatever the merge of lists of I and lists of I plus interval is this right interval doesn't get deleted so that's why we need to be skipping over things as we go because those orig the original lists is not going to get deleted we're basically just merging things into uh that left interval that we merge into so that is why we need to now skip over things that have been previously merged and again this is where understanding the diagram is crucial here to understand why we do this and how it works so if you don't get this part please go back to the diagram because it really shows it pretty much clearly why we do this so at the end as we saw in the diagram everything actually gets merged into the lists of zero right we always start with the zeroth and essentially everything will get merged down into it so all we need to do at the end is simply return lists of zero and that is the actual Logic for the merging now let's actually Define the logic to just merge two linked lists so we're going to say def merge self and this is going to take list one and list two in this part we can basically just copy from the merge linked list problem this part it's not too important how we do this so we're going to say if not list one obviously there's nothing to merge so we return list two um if list two is non-existent then if um if list two is non-existent then if um if list two is non-existent then if not L2 we just return L1 otherwise what we want to do is we just want to merge them so we're going to say if l1's value is actually less than or equal to l2.val is actually less than or equal to l2.val is actually less than or equal to l2.val remember that we need to maintain the sorted order so if the value in list one is actually less than the value the current value of list two then you know we want to add so we want to say l1.next we want to say l1.next we want to say l1.next is going to be the merge between the next value of L1 and that current value of L2 so uh L2 if this is confusing go review your merge linked list question where you'll essentially do this and then we just want to return L1 here and then otherwise we just want to say L2 Dot l2.next Dot l2.next Dot l2.next is going to equal to self.merge between is going to equal to self.merge between is going to equal to self.merge between L1 and l2.next L1 and l2.next L1 and l2.next so remember we always want to merge into L1 otherwise the logic that we set up here won't work so whenever you have two intervals you always merge the second one into the first one and ideally return the second one here so okay so that is the merge function this is pretty standard uh merging of two linked lists let's now run this make sure I didn't make any stupid syntax mistakes and wrong answer what happened um let me double check this up what happened uh okay uh interval equals one range zero length of lists minus interval times two lists of I merge to lists of I plus interval multiplied by two um let's see merge two did I screw this part up L if not L2 uh return L1 if L1 Dot val.l2.01.next um interesting return oh of course I didn't return L2 here whoops sorry about that I might cut that out anyway whoops that is definitely why that didn't run okay cool there we go yeah you should probably return your value from your function there um Okay cool so as we can see it was accepted no problems there other than that stupid bug I just made but whatever we'll ignore that um time complexity so like we talked about in the explanation obviously there are um to merge a linked list is going to take end time and because we are merging them uh in pairs each time we essentially cut down the amount of merges we need to do by two every single time so this is actually going to be log um and then obviously there's k-linked um and then obviously there's k-linked um and then obviously there's k-linked lists so it is n log k for the merging portion uh and then the space complexity the merge function um does not actually use any extra space we do this in place so it's going to just take a big O of one time so this is the absolute most optimal solution this is the best way to solve it this is most likely what your interviewer is looking for especially on this constant space here and the nice uh runtime complexity so that is how you solve merge case sorted lists hopefully you enjoyed the video if you did please consider leaving it a like in the comment it really helps me with the YouTube algorithm if you want to see more content like this subscribe to the channel if you want to join a Discord Community where we talk about all things Fang interview prep systems design you can have your resume reviewed by me you can ask me random questions if that sounds interesting to you join the Discord I'll leave a link in the description below otherwise thanks so much for watching and have a great rest of your day
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order. _Merge all the linked-lists into one sorted linked-list and return it._ **Example 1:** **Input:** lists = \[\[1,4,5\],\[1,3,4\],\[2,6\]\] **Output:** \[1,1,2,3,4,4,5,6\] **Explanation:** The linked-lists are: \[ 1->4->5, 1->3->4, 2->6 \] merging them into one sorted list: 1->1->2->3->4->4->5->6 **Example 2:** **Input:** lists = \[\] **Output:** \[\] **Example 3:** **Input:** lists = \[\[\]\] **Output:** \[\] **Constraints:** * `k == lists.length` * `0 <= k <= 104` * `0 <= lists[i].length <= 500` * `-104 <= lists[i][j] <= 104` * `lists[i]` is sorted in **ascending order**. * The sum of `lists[i].length` will not exceed `104`.
null
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
21,264
1,403
Hello Hi Guys How Are You I Hollywood Doing Good Welcome To The Land Cruiser Gai 100 Dushman Ko Turnoff And Playlist Saudi Se Minimal Subsequently Interact On Increasing Order Qualification I Hope You Are Also Doing So Doing His Words From Website Traffic In This Before Proceeding If You R YouTube Channel Please Like Subscribe &amp; Comment Least Give Darkness Comes Subscribe &amp; Comment Least Give Darkness Comes Subscribe &amp; Comment Least Give Darkness Comes After 10 Substitute Of The Rehearsal Of Elements Previous Greater Than The Sum Of The Known In Cruel Element In WoW Incidence Honge Is Dare Multiple Solution Stunt Subsequent Vida Medium Size Soft-Point Medium Size Soft-Point Medium Size Soft-Point VHP Returned Minimum Size and fair exit more than one solution return sequence with maximum total sum of all its elements that as many sequences of energy can be dropped into the increasing sum possibly zero element from three load solution discussed with unique and returned and Sachin in non increasing order means it has been Decreasing order means from bluetooth model swift is verification to minimum size vein vitamin science which person medium size will get medium size vein is the maximum way element dr will remove tan suite is eight plus 90's symptoms paya plus plan 2030 4 - symptoms paya plus plan 2030 4 - symptoms paya plus plan 2030 4 - tension pick up To 400 units pilgrims and have find the value which decreases total sum up to two alarms extend we delete element date is from time to time potato notification max 98100 can see but disturb a value and VPIP of minor subscribe more than 200 decreases the total Solution and date is that medium size 200 what will u guys will short and will take him measurement and leaders from all and see the it is better than noted and you will just turned on that soumya celebs tweet on kar do hai so let's first taste total Dialogue Total Sum Total Committee Sum Of Names That Boat Shot Must List Is Hunted Not I Will Do I Will Run Tubewell That From Backside Records I'm Here Final Max Element Show The Map Images And 20 Husband Daniel Of Very Solid 102 What Will U Will Take the Meaning of the Minimum Naveen Size Hai Naveen Sahi Sub Sequence Naveen Bhai Sub Sequences and Total Number How to Tell Mon - Mon - Mon - 8 - The Last Element Actors Names of 8 - The Last Element Actors Names of 8 - The Last Element Actors Names of Ideal and What is a Meaning is in that no it's not like that is The means element is tempered glass element and meanings the remaining is not what is yasoda ring in english is a total no hai - - - ek dam saaf this 150 140 degree stanley has set a record date for entries will you have the evening limit will start the meaning of the Evening is this staggering time this is 130 doing some sort of first of these size is the morning with the ground is the morning with the mean is the morning with is amin no. 210 the sum of the is better than the meaning is with the sum divine quite so simply want New Delhi up to date And It's Simply Ajay Ko A Simple What We Have To Return K Laddu One Thing E 108 Vikram Easy Forest Hain To Come Now Just So I Will Run Out From Zero How To Length Of Namaskar Ko Select Remove Bahadur Singh Yesterday morning I have type-2 A show of years my Yesterday morning I have type-2 A show of years my Yesterday morning I have type-2 A show of years my show is or so from 202 i plus one is without oo a local respect including scene size number so hundred a relationship tips total number is so let's rock children vitamin c report is giving sai ram ki naresh total something or on this Total sum soft wilt fat and inside thumb will decrease from total is possible current element and is that December day will find the evening Samdarshi Total - Swimming Twitter - Current Samdarshi Total - Swimming Twitter - Current Samdarshi Total - Swimming Twitter - Current here height will increase tips minute is instant first agunar sweety sums not all is so it's giving Is the correct answer last updated on yesterday morning 2776 packing 7676 365 bullets consumed daily vikram 2006 ok that this painting shows that mistake was making a that I have returned total time and total sub- returned total time and total sub- returned total time and total sub- number for it's wrong it has To 10 Current Elements And 21 Darshan So Let's Get It Now 998 Submitted Its Poster Has Been A Pun In A Video With
Minimum Subsequence in Non-Increasing Order
palindrome-partitioning-iii
Given the array `nums`, obtain a subsequence of the array whose sum of elements is **strictly greater** than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with **minimum size** and if there still exist multiple solutions, return the subsequence with the **maximum total sum** of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be **unique**. Also return the answer sorted in **non-increasing** order. **Example 1:** **Input:** nums = \[4,3,10,9,8\] **Output:** \[10,9\] **Explanation:** The subsequences \[10,9\] and \[10,8\] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence \[10,9\] has the maximum total sum of its elements. **Example 2:** **Input:** nums = \[4,4,7,6,7\] **Output:** \[7,7,6\] **Explanation:** The subsequence \[7,7\] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence \[7,6,7\] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order. **Constraints:** * `1 <= nums.length <= 500` * `1 <= nums[i] <= 100`
For each substring calculate the minimum number of steps to make it palindrome and store it in a table. Create a dp(pos, cnt) which means the minimum number of characters changed for the suffix of s starting on pos splitting the suffix on cnt chunks.
String,Dynamic Programming
Hard
1871
766
hello don't want to miss today's upload so i'm going to set this to easy it's getting late i swear i've done this okay i haven't toplets matrix given the n by n times n matrix return true if the matrix is toplets otherwise return false i measures toe splits if every diagonal from top left to bottom right has the same elements right so nine five one two three four okay nice and simple i like that this is false how do we do that we have to go through the diagonals also easy way to do this actually well i could um do it like a dpe approach and go through each of the elements and then if it's not equal to the top left then return false so go through each of the elements for into i is equal to zero i less than the matrix dot size plus i go through simmer here similar idea but make this j except i want to go through making zero to size and if uh hmm let me think actually i don't need to go through the first row and i also don't need to consider the first column so that means i can start at this index at one index at the first index then i could just go if uh the matrix at i matrix at j is not equal to matrix at i minus 1 j minus 1 and return false y is returned true right okay that seems to work how about this phone let's give that a run awesome all right what's the time complexity it is n is m times n where m is number of rows i guess and n is the number of columns so thanks for watching like and subscribe and i'll see you in the next video
Toeplitz Matrix
flatten-a-multilevel-doubly-linked-list
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above grid, the diagonals are: "\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ". In each diagonal all elements are the same, so the answer is True. **Example 2:** **Input:** matrix = \[\[1,2\],\[2,2\]\] **Output:** false **Explanation:** The diagonal "\[1, 2\] " has different elements. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 20` * `0 <= matrix[i][j] <= 99` **Follow up:** * What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? * What if the `matrix` is so large that you can only load up a partial row into the memory at once?
null
Linked List,Depth-First Search,Doubly-Linked List
Medium
114,1796
448
all right this is leak code 448 find all numbers disappeared in an array in javascript essentially uh what they're asking to do is look through this array of numbers and find the numbers that should be in the sequence that aren't so in this case going from 1 to 7 there's no five and there's no six so the way that i did this was start by declaring a result as an array and then i'm gonna do a for loop and i'm going to set it to 1 because there's no 0 in here and i'm going to loop through the whole length uh plus one and plus one again because there's no zero in here so i'm basically i'm looping through this entire array and then all i'm going to do is i'm going to check to see if the array of nums let's move my mouse includes i so because i right goes starts from one and it'll go all the way up to the number length plus one so one two three four five six seven eight nine so if this array right here does not include whatever i count i'm at so does it include one yeses include two yeses include three s's include four yes does it include five it does not include five so when it does not include that i'm just going to push into my result i which would be five in this case and then at the end return the result so let's give this a run great five and six it found them i hit submit give it a minute this is not the fastest algorithm and it accepted it anyway you should subscribe hope you enjoyed
Find All Numbers Disappeared in an Array
find-all-numbers-disappeared-in-an-array
Given an array `nums` of `n` integers where `nums[i]` is in the range `[1, n]`, return _an array of all the integers in the range_ `[1, n]` _that do not appear in_ `nums`. **Example 1:** **Input:** nums = \[4,3,2,7,8,2,3,1\] **Output:** \[5,6\] **Example 2:** **Input:** nums = \[1,1\] **Output:** \[2\] **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `1 <= nums[i] <= n` **Follow up:** Could you do it without extra space and in `O(n)` runtime? You may assume the returned list does not count as extra space.
This is a really easy problem if you decide to use additional memory. For those trying to write an initial solution using additional memory, think counters! However, the trick really is to not use any additional space than what is already available to use. Sometimes, multiple passes over the input array help find the solution. However, there's an interesting piece of information in this problem that makes it easy to re-use the input array itself for the solution. The problem specifies that the numbers in the array will be in the range [1, n] where n is the number of elements in the array. Can we use this information and modify the array in-place somehow to find what we need?
Array,Hash Table
Easy
41,442,2107,2305
108
Hello Hi Everyone Welcome To My Channel It's All The Problem Convert A Shot At Least To Minor Research Service Problem Do Facebook Microsoft Interview Language Problem In Terms Of Knowledge And Subscribe Key Request To All Notes Values ​​In Celebs Ko Request To All Notes Values ​​In Celebs Ko Request To All Notes Values ​​In Celebs Ko Android You All Subscribe For Every Day For All Subscribe To Different Interview Problems If You Are You This Learning For Every Street Know You Can Solve All Problems York Street From Play List On My Channel Question Solve This Problem Will Solve This Problem Solving Problems Subscribe Problem Ko 108 Number 90 Use Problem Which Will U Will Find The Best 1.0 Apps From Here And Servi Will Move Ahead And 1.0 Apps From Here And Servi Will Move Ahead And 1.0 Apps From Here And Servi Will Move Ahead And Move With Every One Our Channel Like Share And Subscribe Our Come Over And Over Again After B.Sc subscribe The Channel B.Sc subscribe The Channel B.Sc subscribe The Channel and subscribe Saudi Note Ideas Gravity Mist To For The Balance Phase What Mean in case of balance minute me in this fight difference for every notification only 16 side effects of electric and left side and dividing hands free acidity also note from this must subscribe absolut will dhoop se cylinders from 9 Tags page 10 subscribe my channel tho but will also Maintain His Previous Month In Which Light From Regional And Every Time Next In This Process Will Find Previous To The Previous Look And Spirits Will Be Overhead Tank Will Make His Previous Is Not Nal Baikuntha Previous Post Next Flight 20 Not Which Were Already Used For Drought Will No longer be attached with end of the list life in this world will try to life in the middle and lower middle eggs in do the thing will subscribe and subscribe the share and this will v5 and this is the meaning of the Balance finally subscribe this Video plz subscribe Channel and press running 999999999 subscribe our channel subscribe for creating apps and what is the name of the definition of vacancy for every time you were running loop shop in delhi for finding also middle of one liter and history total end Will go through this to-do list of total end Will go through this to-do list of total end Will go through this to-do list of two plus two of India two continue subscribe to bill v2s power minus one * * * Shravan and how many minus one * * * Shravan and how many minus one * * * Shravan and how many states will do subscribe to Ludhiana trying to make balance - tree to Is Ludhiana trying to make balance - tree to Is Ludhiana trying to make balance - tree to Is Obscene Vikram Vo Of Login Basically This Is Nothing But A Similar To The Redeemer And Shot Panchami Ki Divided Into The Road Divide And Chronic And Will Give Every Step And Every State And Its Very Good Solution Interviewer Said Candidate Father Optimization Subscribe Problem Acid Converted Into A Day Landslide The Next Month In Cases Of All In The World Fear Files And Definition For India For This Lesson For Tamil With This Element Mist Element Make Flower Root Will Face Lifting Wash It 1000 Right This Album Of Birth Minus One And Right Leg Subscribe My Channel Subscribe Our Tree Like Share And Subscribe Our Channel Like This Is The First Meeting Railways Should They Can Also Access They Kashmir Don't Know The Number Of Normally Already In Our Daily Use This Is Like You For This Channel Subscribe Our Subscribe comment and Share like subscribe Quiet S Chief Already Phase 250 List of Vintage Cars in To-Do List Se Zor Size Vintage Cars in To-Do List Se Zor Size Vintage Cars in To-Do List Se Zor Size - Wave Thursday Subscribe Must Subscribe Channel Subscribe Our Udayveer Who Ru Cheese New Train Mode of Validated List David Phanda Straight Cold Play List Left and Right Subscribe Similarly Absolutely Subscribe To 116 Likes For This Company Dad Do Is Look Like A Difficulty Of Reservation Centers Balance Egg Subscribe My Channel Like My Channel Subscribe To Bluetooth Nothing But In Terms Of Bj Off And Similarly Space Complexities Of Like Subscribe for Values ​​In and Play The Problem of List Playlist
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
105
welcome back to our Jess today's question is leak code105 construct binary tree from pre-order and in order binary tree from pre-order and in order binary tree from pre-order and in order traversal so given two integer arrays pre-order and in order where pre-order pre-order and in order where pre-order pre-order and in order where pre-order is the pre-order traversal of the binary is the pre-order traversal of the binary is the pre-order traversal of the binary tree and in order is the inorder traversal of the tree construct and return the binary tree so we have pre-order pre-order pre-order we have in order and we need to construct this tree using just those arrays so let's dive into the Warframe okay so this is a really fun question we need to construct this binary tree here using the pre-order traversal which is using the pre-order traversal which is using the pre-order traversal which is root left right and the inner traversal which is left root right so what do we do well we have the root here which we know is three where can you see within pre-order or in order how can we get the pre-order or in order how can we get the pre-order or in order how can we get the root of this well we know pre-order is root of this well we know pre-order is root of this well we know pre-order is root left right so the value at this index the first index within the pre-order list is going to be equal to pre-order list is going to be equal to pre-order list is going to be equal to the root great so we can start constructing it now we need to know the left and right subtreat well if we look in pre-order we can't exactly find out in pre-order we can't exactly find out in pre-order we can't exactly find out what's in their subtree and what's in the right subtree using this pre-order the right subtree using this pre-order the right subtree using this pre-order list however if we look in the in order we've just gotten the root from pre right so if we work out the index of the root from pre-order then as you of the root from pre-order then as you of the root from pre-order then as you can see everything to the left of three is in the left subtree and everything to the right of three is in the right subtree so by using that information we can use recursion in order to build out this tree the only other thing that we need in order to build this tree out is the link from the in order list at position zero all the way up to the root value once we have that we can construct the recursive calls for the left tree and the right tree and build it up now the best way to show you this is to jump into the code so that's exactly what we're going to do so we're going to have a function called recurse right and inside this we are going to need four parameters we're going to need the start of the pre-order so we call it the start of the pre-order so we call it the start of the pre-order so we call it P start we're going to need P end which is going to be the end of the pre-order is going to be the end of the pre-order is going to be the end of the pre-order and we're also going to need the same for in order and when we call this we need to return it so it's going to be for a curse passing in 0 for p start pre-order pre-order pre-order dot length minus one for the end of the pre-order zero for end start and in order dot length minus one for the end but the in order array so all very straightforward to begin with now I've inside the recursive call we need a base case which is going to hop us out of this so at any point if the starting value of pre-order or the starting value of in of pre-order or the starting value of in of pre-order or the starting value of in order is greater than P end always greater than in end we can return null right because we've reached the end of either the left subtree or the right sub tree so if P start is greater than P end or in start is greater than in end we can return null so that's our base case now we need to build up the tree so like we said in the walkthrough we can get the root value right and this is going to be pre-order passing in P start so initially we've got the pre-order at so initially we've got the pre-order at so initially we've got the pre-order at index of zero which is p start this will give us the root value of three now we need to work out the position of that within the in order array so let's call it in index this will be in order index of root file and remember like we said in the walkthrough we need to determine the number of nodes to the left of the root value within the in order array so n left is going to be in index minus in start now we can create the root so root is going to equal a new tree node and we're going to pass in the root value then we can build out the left and right subtree so it's going to be recurse root dot right is also going to be a recursive call and at the end we're going to be returning the root so this is the tricky part right in the left subtree we have nine and within pre-order we know that 9 nine and within pre-order we know that 9 nine and within pre-order we know that 9 is at position one within the pre-order is at position one within the pre-order is at position one within the pre-order array so we are going to pass in to this recurse 4p start P start plus one for the end of the pre-order we are for the end of the pre-order we are for the end of the pre-order we are going to pass in P start plus and left right because we can use the numbers to the left of the root value within in order to work out where the end of pre-order is going to be with of pre-order is going to be with of pre-order is going to be with relation to the left subtree so it's going to be P Star Plus n left then within the left subtree for in order the starting position is still going to be in start right because in order is 9 to begin with and it's going to be in end minus one for an end and that's because we are subtracting a value we're subtracting the root from this and then for the right sub tree we're going from 3 to 20. so in pre-order how do we get 3 to 20. so in pre-order how do we get 3 to 20. so in pre-order how do we get to 20. well if we do pre-start plus one we get well if we do pre-start plus one we get well if we do pre-start plus one we get nine and then if we add n left we get 20. so we'll do p start plus 1 plus and left for the end well we're going up to the end of pre-order the end of pre-order the end of pre-order so it's just going to be PN then for the parameters that we're going to be passing in regards to the in order array it's going to be the index right so this value here the index of this plus and left so we're going to move here so in index Plus 1. and likewise for the in order array we're going to be going up to the end of that array so it's going to be in and that looks good when this runs it's going to return this route and we're going to return it here so let's give this a run submit it and there you go
Construct Binary Tree from Preorder and Inorder Traversal
construct-binary-tree-from-preorder-and-inorder-traversal
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_. **Example 1:** **Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\] **Output:** \[3,9,20,null,null,15,7\] **Example 2:** **Input:** preorder = \[-1\], inorder = \[-1\] **Output:** \[-1\] **Constraints:** * `1 <= preorder.length <= 3000` * `inorder.length == preorder.length` * `-3000 <= preorder[i], inorder[i] <= 3000` * `preorder` and `inorder` consist of **unique** values. * Each value of `inorder` also appears in `preorder`. * `preorder` is **guaranteed** to be the preorder traversal of the tree. * `inorder` is **guaranteed** to be the inorder traversal of the tree.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
106
22
Hello guys welcome to another video Nasbi everything suggestion or any problem generate balance thing with him from let's get started share and subscribe function generate something all combination of wealth from paralysis pluto example think one person generate even more special thing so let's see how Can They Reduce Weight For Parents For Just Means The Meaning Of But For The Thing Which You Should Do The Thing You Have Will Form A So Let's Do This Problem So Let's Start Web Hosting Provider Senior Resident Conditions What is the Worst Condition for Nation S Opening Racket Number Falling Back Have Always Been Laid Down And Where Is The Number Of Address Festivals Info Someone Tells Beam Saudi Simply And Set S You Have To Pay Is Up Ocean Acidification U Number Of Seats Will Always Be Equal To The Industry's Whole To Number Of Opening Of Islam And You Can Always Give One Example A I Let See The Second Connection Number Of Rose But Its History Always No Turning Back And You Can Develop Rose Sex Racket Why Is This See You Can Ever Have According Racket Before Opening Jackets For This Is Not Allowed To Say This Is Not Allowed In This Condition Behavior to your doubts and 120 cylinder close loop back but now a number of two souls can you solve one of the following is not fair of the record chart the software is 1957 different types of the rings number can follow back 2009 day planet Earth 60 And Enjoy As Current Titanic Passed Way Se Input Se This Is The Number Of Seats After Opening And Closing Back It's Not Entered Into An Option Sacrifice Of President And What Is The Meaning Of The Word 900 Subscribe Skin Black Lips The Students Were Added To Bring Back the Right Now No One Should Be Placid in the Middle and Opening Practice to know what you ca n't in Maximum set up to already have to avoid doing so you can't in a mood just not allowed to maximum just see what you will do you will look at the number of turnouts Subscribe to 2012 A Young Man It Gives You Options Open and Close Back It's OK But Can You Really Open Another Racket? S One Only One Closing Rank Last Year And Number Of Opening Backless Is Too So Well S President To You Have One Request Baikuntham 120 Kid A Solid Insult Of Losing Your Parents By Vinay Now Half The Time Apni Profit Centro Shing Battery Cool And Addictive Jo Number For Its Soldiers Will Be Valid For Parents Pc Suite Incident Hai Half Inch Plus Follow Us At Two Places For Remedies Two Times For Which What Exactly Who Wanted To Know What Not To Win But What Is Back To Have Add Pencil Drawing Pencil Jaswant Par Word Used Only Answer You Can Have Lot More Answer And See The Ise Zara Answer For Any Rule Chief Justice For The Subscribe Our Channel Like This Is Not Permitted The Option Of Computer Labs As Shubhendu To School Of This Function Aage Clear All Subject Computer Can I enter dysfunction returns back which will make this function to return back to find a third year back side function was not going to bring to the notice of clothing noted you what is the present in the Middle of nowhere near me is this particular function and what am I going to Maithili Ko directly share and latest change the condition morning wicket internet users developed phone number opening day of its work number for its whole world and shifted from inside her worshipers this particular parameter In Two Parts Of Speech Latest Interviews Of Subscribe Now To Receive New Latest Photo Share 90 Limit Most Pious And Smiled And Asked In Interview On Which Okay Sona Luta Open Loop Condition The Internet And Web Officer Service Is Vegetables With Others On In This Connection What Is The condition suhaag opening back it's poonam ko din backstreet boys request you quintal soybean also you have two options including latest kill option shopping option also you have options to choose from and to print and chatak set up to two to the condition is dam 999 in office Crops and Lag website has this particular types of so they can not take this particular part 1 so let's here five can win for truth in fact the are of course I can vibe x kamaruddin back its one number opening back its food and nurses and kidney Pregnancy Test One Rapid Metro Projects Will Insult And Clothing Resident Evil Point To That 500 Latest Co* Responsible For To That 500 Latest Co* Responsible For To That 500 Latest Co* Responsible For It's Okay Know What Is The Number Of Co Stop Solution For All Elements Select This That And Milk Products Years Back In That Subsidy Talk To Me Tomorrow Hain Chhut Aisa From To Solution Let's Start Backtracking And Gram Saunf Bandhu Hain Yes This Cataracts From Eyes And Function Khol Will Return In The Winter The Function Of This Back Pain No Gain After Losing Battle Tanks Commission's Side Because Close One Open Solve Was Not Rise In This Process Will Bride Service Commission Has Evolved Expert Not To Interpret This Function Call Ok No Problem Year Again When Way To Back Writing For Web Tracking I Will Then Be Destroyed Finally I Am Agree With Us Are Other Slabs Possible And Were Gone Into Practice So Lakshmi insert sim liye computer wa havan lost all the best 1000 subscribe and subscribe the Channel ko tomorrow morning do we sperm business simply declare recive function and even for determining but their toilet SNC shot function and welcome all distic obscene No How To Do It Back To My Channel Subscribe Latest Govind Subscribe To The President And Will Start Show Who Is Gold Award Function And Finally Bigg Boss First Parameter In It's Wake Up Sid And Salim Answer Of What Is Meaning Of Subscribe Like Comment MP4 Latest Start Pimpri Gets Fertilizers By Selling So What's The Best In The Morning Simply Discussed And You Want To Talk You Can Subscribe Now To Stop The Length Off Click Here Subscribe Thank You To Subscribe Simple Tool For the first world were in real sense I am on my back side this lesson number for admission in order to claim third win at all interested used lubricating oil is more then as parents perimeter the answer second chemicals in this world can send to print from rain will Change open with current open plus one pred wi-fi setting open close will see what your open plus one pred wi-fi setting open close will see what your open plus one pred wi-fi setting open close will see what your friends are currently you can with friends pe click thank you the website and united similar condition for clothing surendra aapka introduction to bring back the sacrifice in all its value Of The Real Of Rebel Forces Will Change Subscribe This Point If you have not subscribed to this video channel then please click on the like button which one you have so many returns to all the changes I tweeted this OK I think that since Pine Labs For working tomorrow morning assam compiler and youtube is so is simply life current track sexual a message on this website white and will submit nc this question from now on selected solution thanks publications
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
1,921
hi everyone let's solve today's daily challenge that is eliminate maximum number of monsters so in this question uh it is said that you are playing a video game right where you're defending your City from a group of n monsters and here an AR disc of size n is given to you and distoy is what it is the initial distance in kilometers of the ith monster from the city and then the monster walk towards the city at a constant speed and the speed of each monster is given inside of another array of size n and speed is basically representing the speed of the ath monster in what kilometers per minute so let's draw the situation it's given to us so this is your city okay and inside of the video game you're protecting your city now you're defending your city or protecting your City from whom monsters right let's say these are some monsters here now we are given an array called dist inside of this dist aray so here we have four monsters so we are given four distance inside the dist aray let's take them as 2 4 3 and let's say two again okay these are the distances given to us and okay let's draw these distance let's say this is 2 kilm this is 2 km again this is 4 kilm this is 3 km okay and then we are also given a speed array right inside of the speed array we are being told that these monsters are traveling towards the city at a constant speed right so that speed is given inside of what the speed array so let's take the speeds as one two and one and two okay so corresponding to this particular distance the speed is 1 so that is for 2 kilm there are monsters traveling towards the city at 1 kilm per minute right and then with four distance the speed is going to be two so this monster is traveling at 2 km okay per minute then here the monster with this 3 km distance is traveling at 1 km per minute towards the city and this monster with 2 km distance is traveling at Speed 2 km per minute towards the city now so now we know the situation What's Happening Now what is it that we want to calculate here right so we are given a weapon that once fully charged can eliminate a single Monster however the weapon takes 1 minute to charge and the weapon is fully charged at the very start okay so you lose when any monster reaches your city if a monster reaches the city at the exact moment the weapon is fully charged it counts as a loss and the game ends before you can use your weapon so we need to return the maximum number of monsters that you can eliminate before you lose or n if you can eliminate all the monsters before they reach the city right so what we have to basically do is we have a weapon okay and so you are standing here and you have a gun let's say that is your weapon and you can kill these monsters right but the problem is after you kill one monster let's say you kill this particular monster here after you kill that monster your gun takes 1 minute to fully charge and ready to kill another monster now what we need to tell is the maximum number of monsters that we can kill right or we can kill all monsters also but that depends on a particular uh input case that is given to us right so now let us see how we are going to solve this question so I hope the question is clear to you right so you have a gun you have some monsters you are given their uh distance and speeds and you need to tell the maximum number of monsters that you can kill now um initially you might think that we may take the distances right and sord these distances and according to the distances whichever monster is let's say this is nearer right to the sitting that is 2 km the smallest distance is two among the S so you'll first kill this monster or this monster right and then you will be killing the monster with uh 3 km distance and then 4 km distance right so the problem with that is let's say initially he is here okay so you kill this monster let's say some other monster see this monster is only traveling at 1 kilm per minute and this monster is traveling at 2 kilm per minute that is at T is equal to Z this is the situation at T is equal to 1 this monster will be here but this monster will be at your city right so if you decide to kill this monster first then what will happen this monster will come and destroy the city but can we do better than that yes what we will do is we will kill this monster first because he's traveling at a greater speed right and then we will kill this particular monster because at T is equal to one he will be here and as soon as you kill this monster between 0 to one minute you will charge your gun your weapon and then you will kill this monster right so you have killed two monsters is up to now and then this monster would have traveled up to here that is half the distance because he's traveling at 2 km per minute and this monster would have traveled this distance that is 2 km from here right so which monster will you kill next right so you can choose to kill this monster or either this monster right so the answer in this case is going to be three right so we notice that alone the distance is not going to help us so we need to have a better parameter than that and the better parameter would be nothing but time itself right so how will we calculate time can be calculated by Distance by speed right so that is the where we calculate time so we calculate time is equal to Distance by speed and according to this time parameter right whichever monster so see what we are basically calculating is how much time this monster how many minutes this monster is going to take to reach the city and destroy the city right so according to Time first we'll calculate the time in some um container or data structure we'll store it somewhere and then we'll sort it right we'll sort it and according to this time right whichever value is the lowest right we will keep killing these monsters this way right so this is how we can maximize the number of monsters killed so now I hope you have understood how we will be going to solve this question now another thing to note here is that although the distance and speed are going to be integers but when you calculate time it can be a fractional valuee so what to do in that case right so do we need to include fractions here not at all so what we are going to do is uh let's consider this test case here so here we are given speed 1 2 3 this is the distance and the speeds are 11 1 okay this is not a good okay this one let's take we have distances as 3 2 4 and the speeds given to us is 53 2 speed given to us is 5 3 2 all right now let's draw the situation for this particular test case this is your city these are your monsters and this is 3 km distance this one is 2 kilm and this one is 4 km and the monster with 3 km is traveling at 5 km/ second speed and this traveling at 5 km/ second speed and this traveling at 5 km/ second speed and this particular monster is traveling at what speed 3 kilm per minute and then this monster is traveling at 2 km per minute this is the speed of these monsters now if you see when we'll calculate the time okay the time required for this monster to reach to the city is 3x 5 okay for this monster that is 3x 5 kilm this monster will travel each minute okay and this one is going to be 2x3 and this is going to be 4 by two that is two right now in this situation what we are going to do right so even though this is a fractional value if I take the Seal of this right that is if I divide 3x 5 what am I going to get integer value is zero but if I take the Seal of it of this um fractional value 3x 5 what am I going to get I'm going to get one right so I can say that within this particular time this monster will certainly be killed right because even though he's traveling fractional distance each time that is 3x 5 but we are taking 1 minute to charge the gun right so basically if the monster is killed here right so that is going to take 1 minute right so that is why if I consider the seal I know I will certainly kill this monster so that is what we are going to do in case we are getting fractional values so we are going to store the Seal of this fractional value time right inside of my time uh container that I'm going to make right so I hope things are clear now let us go ahead and try to implement it another thing that here instead of sorting right instead of taking an aray and sorting it I'm going to take a priority Q or a Min Heap right so inside of the Min Heap what I'm going to do is I'm going to take first I'll be storing these times inside of the Min Heap and then I'll keep popping and up to what time I have to keep popping until my time right is less than right uh the time this T is actually whatever time is running so we are at 0 1 2 3 so this is the time that is running right so it is increased after 1 minute right so incremented after 1 minute incremented after one 1 minute so this T if this T is less right then the time that requires the monsters to reach then I can kill that monster right and I have time to kill another monster as well so this is what we are going to do and we'll keep popping the values from in Heap until this condition is true that is time of I or the top of the priority CU or the Min Heap right if this condition is not true we will break out of the loop now let us go ahead and implement first here what I'm going to do is I'm going to make my priority Q or Min Heap right this is how we make our Min Heap in C++ because by default priority Q uh C++ because by default priority Q uh C++ because by default priority Q uh container is an Estel container and it is by default a Max Heap right so this is the syntax to create a Min Heap okay so PQ I have created this is my priority Q now the next thing that I have to take is this integer value T that is I'm increasing the time and I am checking for each and every minute I'm going to check right if I can kill a monster because after every minute my weapon is getting fully charged so now let us go ahead and uh insert values in our priority Q so what are we going to insert in our priority Q we are going to insert Distance by speed that is the time required by monster to reach to the city right so for inti is equal to0 I less than distance do size I ++ and then inside ++ and then inside ++ and then inside of PQ what am I going to push now other thing is that I cannot just push a Distance by speed I have to see if it is a fractional value or if it is an integer value I will simply put it right if it is not an integer value I have to add one to it that is I have to take the seal you can use the seal function or you can also add one by checking if it is a fraction or not right so I'm going to check if this is a fraction value modulo speed of Y if this is zero right then what I have to do I have to store distance of I by speed of I inside of the priority Q otherwise if this is a fractional value what I have to do I have to store distance of I ID speed of I + 1 that is the seal value of the of I + 1 that is the seal value of the of I + 1 that is the seal value of the fraction that I'm getting so I'm going to do what I'm going to store distance of I / speed of I / speed of I / speed of i+ one that is what I'm going to i+ one that is what I'm going to i+ one that is what I'm going to store so my priority Q is now made now what I'm going to do I'm going to iterate inside this priority CU and I'm going to take the top element each time and I'm going to check it against the time that I have right so if the time that is running and a monster is you know um is going to be killed after some more time right the monster should take more time than this te time to reach to the city only then the monster will be killed right so my condition is going to be let's write PQ do empty either that priority Q will get empty or we will break out of the loop before it get gets empty so the condition is T should be less than PQ do top right the monster should always take more time to reach then the time that is we are currently at the minute that we are currently at right only then we'll be able to kill the monster so in this case I have to pop right otherwise break and we will also increase our time each in each iteration okay and after this I can simply return this T value right because each minute I'm killing a monster right if I'm not able to kill definitely after that all the values will be greater and I will not be able to protect the city so I have to return the T value only okay so this is accepted so this is basically how we need to solve this question right
Eliminate Maximum Number of Monsters
eliminate-maximum-number-of-monsters
You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city. The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon. Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._ **Example 1:** **Input:** dist = \[1,3,4\], speed = \[1,1,1\] **Output:** 3 **Explanation:** In the beginning, the distances of the monsters are \[1,3,4\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,2,3\]. You eliminate the second monster. After a minute, the distances of the monsters are \[X,X,2\]. You eliminate the thrid monster. All 3 monsters can be eliminated. **Example 2:** **Input:** dist = \[1,1,2,3\], speed = \[1,1,1,1\] **Output:** 1 **Explanation:** In the beginning, the distances of the monsters are \[1,1,2,3\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,0,1,2\], so you lose. You can only eliminate 1 monster. **Example 3:** **Input:** dist = \[3,2,4\], speed = \[5,3,2\] **Output:** 1 **Explanation:** In the beginning, the distances of the monsters are \[3,2,4\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,0,2\], so you lose. You can only eliminate 1 monster. **Constraints:** * `n == dist.length == speed.length` * `1 <= n <= 105` * `1 <= dist[i], speed[i] <= 105`
null
null
Medium
null
1,616
Hello Hi Everyone Welcome To My Channel In This Video Will Fall Key Problem So To Speak To Make Paper Enron So Posted Key Problem Statement Opportunity Shoulder Basic The Problem Is Given Two Strings In This Can Be Split String Exams Page Subscribe Video subscribe The Channel Please subscribe and subscribe A Plus A Suffix Dhundh Check If Any One Of The Following Is Not Fair Of The Spelling Of Hai So This Is The Problem And Have To Died So First Proof And Solution Speed ​​Come To Your So First Proof And Solution Speed ​​Come To Your So First Proof And Solution Speed ​​Come To Your Mind Which Can Start Voting This Split Like First Over Share in President Vikram PT String Plus the Meaning of Chief Chaff Ki and Next Week and Tried As One and Destroyed Due to Be Tried All Possible Places at All Possible Places and Check Efficiency of These Two Strings Is Form of Land from Using Simple Pendulum Check So planning springs rid from both and is am sorry 512 quiz painter mode switch executives from starting to 0.8 executives from starting to 0.8 executives from starting to 0.8 degrees point when skin pimples to elements this video and morning hair oil implemented with support and tried and time of a perfect being caused due time complexity of dissolution Percent a running one for you for trying every possible speed and baking very different from or not using other side of running and share subscribe like this is the impossible checking subscribe Video to like Share and subscribe the let's check the example of 202 decided to give one Example Dushwari For Dinner Time Case Hair Soft Sydney Places In This Part Subscribe Rotten Eggs Subscribe And Of But Will Keep Doing Them And Keep Increasing From This Point To Left Side Par Ka Vikas To Beg Padharo Lineage Introduction Display You And Eggs Subscribe And The Continued her first day responsibility over and over all desires to avoid all the meaning of a gift to change from the next shop comes from 20th and second's scan be given this hair morning have to continue this mapping this from noida and from over 100 disconnect Show Will Try Verdict Se 100 Ep Is Matching Busy Danveer Matching With Chief And Sorry Then Olive Oil This Is Meeting All The Characters Which Mins Five Vriddhi Condition Before Deleting Interpreter Dainik Ullu Adi Se Reply Employees And 3500 Mix Trick Similarly The Case Minute With this is not fair in the values ​​in is this is not fair in the values ​​in is this is not fair in the values ​​in condition and tribe school and navdeep started taking exams page subscribe like it is the sister this is the solution will come in your awareness fair skin just once distinctive planning to avoid so let's start implementations for implementation 200 First Will Check Will Right Helper Like Ka Third So Let's A Private And Will Be Written Boys College Check Soidi String In String Vi With Vip Will Return From Subscribe Our Check Will Start To Delhi From Left Side 0 That Artists From Being Widowed Language A Minus one 100MB and offspring somvanshi started will run until this is lunar and characters in a great deal is equal to be without 800 subscribe screen dheerwale-dheerwale chat is like this is vivek otherwise subscribe and over and subscribe the Channel subscribe school wash that another method Say spelling of but it seems a palindrome for the morning try many cases like string s with string from all to 8 plus one measure serving method ons considered the last one should not be benefited with all due to his co-workers benefited with all due to his co-workers benefited with all due to his co-workers are one's will be benefited From subscribe The Channel subscribe The From the subscribe id 154 Sweden here the definition of our first in right method show private bullion a spell in this will get a string only 100 ko's spelling off but the string gas is more than that or and will milk Same thing basically l plus 10 will be the condition and veer simplex implementation of liquid working so delayed compilation because of ayush wing eto vishwa s noida end subscribe co king voice messages working for the first time previous striver test cases Are the inspiring species note first basin area or co select compilers custom test's only 19 feet smoking some time this of typo proven pasting riots case has happened so now custom test cases working navya confident submit decoding see that Nitish accepted and different times one act subscribe to subscribe person subscribe and subscribe the Channel thanks for watching
Split Two Strings to Make Palindrome
minimum-difference-between-largest-and-smallest-value-in-three-moves
You are given two strings `a` and `b` of the same length. Choose an index and split both strings **at the same index**, splitting `a` into two strings: `aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into two strings: `bprefix` and `bsuffix` where `b = bprefix + bsuffix`. Check if `aprefix + bsuffix` or `bprefix + asuffix` forms a palindrome. When you split a string `s` into `sprefix` and `ssuffix`, either `ssuffix` or `sprefix` is allowed to be empty. For example, if `s = "abc "`, then `" " + "abc "`, `"a " + "bc "`, `"ab " + "c "` , and `"abc " + " "` are valid splits. Return `true` _if it is possible to form_ _a palindrome string, otherwise return_ `false`. **Notice** that `x + y` denotes the concatenation of strings `x` and `y`. **Example 1:** **Input:** a = "x ", b = "y " **Output:** true **Explaination:** If either a or b are palindromes the answer is true since you can split in the following way: aprefix = " ", asuffix = "x " bprefix = " ", bsuffix = "y " Then, aprefix + bsuffix = " " + "y " = "y ", which is a palindrome. **Example 2:** **Input:** a = "xbdef ", b = "xecab " **Output:** false **Example 3:** **Input:** a = "ulacfd ", b = "jizalu " **Output:** true **Explaination:** Split them at index 3: aprefix = "ula ", asuffix = "cfd " bprefix = "jiz ", bsuffix = "alu " Then, aprefix + bsuffix = "ula " + "alu " = "ulaalu ", which is a palindrome. **Constraints:** * `1 <= a.length, b.length <= 105` * `a.length == b.length` * `a` and `b` consist of lowercase English letters
The minimum difference possible is is obtained by removing 3 elements between the 3 smallest and 3 largest values in the array.
Array,Greedy,Sorting
Medium
null
1,723
hey what's up guys this is jung so this time 1723 find the minimum time to finish all jobs so you're given like an integer array jobs and where jobs i is the amount of time it takes to complete the ice job and you're also given like a case work k workers that you can assign jobs to and each job should be assigned to exactly one worker and the working time for worker is the sum of the time it takes to complete all jobs and you need to find at the minimum possible maximum working time of any assignment so the maximum working time is like the it's for among all the workers and what's the maximum working time and then you need to find the minimum possible number of any of the arrangement right to get the minimum of the maximum working time so some examples right the uh so if we have like three jobs right and then three or three workers obviously you know each worker will be assigned to uh sign to one drop that's why the maximum is three and for example two here right i mean the uh oh we have eleven because here's the best assignment right so which means that you know the uh the working time for worker one is one plus two plus eight is which is eleven and this first second one is it's also eleven that's why the output is eleven and the constraints is like it's very small basically not the uh the jobs is the length it's jobs and the workers they're only within 12. so this one is actually a strong hint right so which means that there is no polynomial solution for this problem right otherwise it would have been like the 10 to the power of 4 or 10 to the power of 5 but for this one it's 12. only 12. so 12 means that it's a this one is like complete problem which means that at each of the job you can assign the job to any of the workers right so which means that you know that's going to be the 12 power 12 to the power of 12. right because the both the jobs and the k they all they're both like uh up to 12. so that's the total time complexity for this one and all right so that's why i did so this problem is more like the uh it's all about cutting the branches and how and also how to do the pruning because the main logic for this problem is pretty straightforward it's just like the backtracking right basically at each of the uh at each of the jobs uh we will try we try to assign the job to other to each of the workers and then in the end we get the minimum after of the maximum time so let's talk about the strategies of cutting the branches i think some of there are like some common strategy to cutting to cut the branch i think uh at least for this problem i think one of the ways to cutting the branch is that you know let's say we have um some workers right at once at one state we have some workers that have the same uh have the same numbers same currently have the same working time the total work the working time let's say we have worker one marker one worker two request three and work four let's see all of them have the time turn so for this case we can we all we need we can just uh try to assign the job to any of them we don't have to try off them because each of the workers they're all identical so that's the first way to cut the branch which means that if there's like the multiple workers have the same working time we just need to try one of them so that's the first one and the second one so what's the second way to cut the branches here and it's that you know since we're trying to get them the minimum possible maximum answers right so which means that we're going to have like global uh global variables that to keep track of the current uh best the current minimum answer right and if the current one if the current branch the total working the maximum working number that's our the maximum working time is greater than the car than this answer then we don't have we don't need to continue we can simply stop there because you know if we continue the current the maximum working them time will only become bigger and bigger since we are getting the maximum out of all the workers and each workers uh time can only be increasing not decreasing yeah and that's basically two strategy to cut the branch for this problem and yeah so let's start coding here uh so first i know we have a backtrack right that's the basic idea here so and we're gonna have like the indices and then i'm gonna have like current um time so this one actually is the current it's the current the biggest time right current maximum time max time yeah and then that's that and we have like a n let's define some like look global variables right and then we have a workers right so the workers i'm the length at the beginning they're all zero right and then we have a k here so this one's going to be the global variables and then we have the uh the answer is the system.max the system.max the system.max starting with system max size and we have backtrack we start from the first the zero index and then start with zero max time and then in the end we return the answer okay so um the uh the exit condition is like this so the first one is if the i is equal to n right so which means that okay we have find an arrangement right and for this one we just need to update the final answer which is going to be the minimum of the answer after that what um current max time right and then we just need to return and so i'll try to finish the uh the backtracking part so and then i and then we can start adding the pruning or the branch cutting logic so we have a range of k right so since we have a case workers and the uh so w j jobs i right and then we have like the back track of i plus one and then we have like the uh max of current of w j right and we have w j uh we have the back track yeah and then and here i think that's it right i mean and that's the basic uh backtracking logic here and so let's try to add the first uh branch cutting logic which is the uh if there's any uh jobs or i'm sorry if there's any workers that have the same uh working times which we simply skip that so i think one way of doing this i just uh introduced a time set here right so here and i simply do this right basically if the current worker j is not in the time set and then i just do the following otherwise i just skip because we have seen this time before and then in the end i simply add the time set dot add w j okay so that's the first um the first uh pruning and the second one is the uh oh so here i need to define a non-local oh so here i need to define a non-local oh so here i need to define a non-local concert so the second one is this right so if the current one has reached is greater or equal than the answer right and then we can simply return the answer yeah because here basically like i said if not current if the current max has is bigger right then the best the minimum right then no need to continue yeah so i think that's it so let me try to run the code okay yeah uh current max time okay cool so yeah i mean that's it for this problem you know the i mean the basic logic for this one is very straightforward it's just like a simple backtracking and actually for this problem you know i was trying to use the uh the greedy method like maybe i was trying to use it like a priority queue try to and then sort these drops from the biggest to the smallest and then i'm trying to see if i can use the uh like custom greedy approach solve it even though i was i saw this one but i was like hoping that if that the greedy works right but obviously that one for some test cases it gave me uh the wrong on to give me the wrong answer so and then i had to go back to the very basic back tracking which is the mp uh complete solutions here right and then the next thing is that how can we uh cut the branch right so i mean this one you know i mean this like uh technique is pretty common for many of the backtracking method you know because if they're like a multiple like candidates that have this exactly the same uh conditions right and then we can just keep the uh we can only try one of them so that's the first one and the second one is somehow you have to be realize that right so this one needs a little bit of observation and thinking um because you know once you have like uh have already accumulated a big enough uh current the max time there's really no need to continue if we have already have like a better answer than the current one right since we're getting the minimum and yeah i think that's the basic the two uh technique to cut the branch for this problem and yeah i think that's all about it thank you for watching the video guys stay tuned see you guys soon bye
Find Minimum Time to Finish All Jobs
maximum-number-of-achievable-transfer-requests
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. _Return the **minimum** possible **maximum working time** of any assignment._ **Example 1:** **Input:** jobs = \[3,2,3\], k = 3 **Output:** 3 **Explanation:** By assigning each person one job, the maximum time is 3. **Example 2:** **Input:** jobs = \[1,2,4,7,8\], k = 2 **Output:** 11 **Explanation:** Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. **Constraints:** * `1 <= k <= jobs.length <= 12` * `1 <= jobs[i] <= 107`
Think brute force When is a subset of requests okay?
Array,Backtracking,Bit Manipulation,Enumeration
Hard
null
336
welcome to june 13th leco challenge palindrome pairs given a list of unique words return all the pairs of distinct indices i j in the given list so that the concatenation of the two words worded i and worded jay is a palindrome so let's go to our first example here so let's see we have um all right let's go we have a word list here we have index zero one two three four and then we have our output which is telling you zero and x zero and next one are palindrome pairs so what that means is that if we concatenate index zero or the next one then we get a power drone pair as for example we get right here right this doesn't have to be in the correct order but we have concatenate um index zero and index one and we have itself is a palindrome pair and we have except this example here one zero so if we concatenate word index one right here which is db this one right here and then we concatenate with zero we also get palindrome pair let's go for this example over here we've got three two so i was telling you we concatenate in x3 which is s and index two we also get palindrome pair which is right here and two four if we concatenate the um index 2 position in the list which is 0 1 2 so lls with index 4 we get this palindrome right here so notice how the palindromes are part of the list that we concatenate i with j and uh and either in specific orders either this goes first or this goes first then we make we should be able to make a palindrome pair out of it so um so notice how each of them have a something called a prefix so words in the beginning right and we have something called a suffix these are things at the end and all the prefix and suffix come from the word list so approach this would be to um since we know that our word length itself is under 300 why don't we go about generating all the possible candidates for the palindrome pairs we're going to be able to generate this list and from and then from this list we're going to see what of these possible calendar um generate all the palindromes possible from these i'm going to see which ones will make a palindrome out of it right and we will fit our criteria so that's how we're going to approach this question i'm going to use this uh word length to our advantage right this is only under 300 while the length of the actual list itself is quite long so it's 5 000. all right let's go about doing this so the first thing i think would be useful to be restoring our list of palindromes would be i would be using a dictionary so um you want to be able to store our information in a dictionary because it's um we want to be able to not only one increased decrease in time complexity but also it's nice to have it ordered in a way where could we actually retrieve by index another way then next thing we're going to do is we want to um so we know that we're looking for prefixes in suffixes but we also know that powernumbers work by having it in the order that you see it in and but also the word in reverse as well have to be able to make a palindrome out of it so let's create something to be able to look for all the reverse words within your words list so we're going to say 4i word and enumerate word so we're going to enumerate it in order to make a uh pairing out of it in words what we're going to do is that we're going to store the um the information into our dictionary a dictionary i should say so word and it's going to be a reverse dictionary so what we're going to do is we're going to do that equals index i all right so we have that going on now we have our word list in reverse order and a pound um in uh what enumerated into a reverse word in our dictionary so this will be easy to grab here so notice right here we're enumerating through words using a for loop so far we have every if we were to call this n and this m it will be we're looping through it n times i should say yes yeah it'll be uh m times right here okay so next thing we want to do is um let's store a result in a set let's see why are we doing a set if we scroll back up here it says return all the pairs of distinct indices it's highlighted and italicized so distinct it means you want to be uh unique and you want to be um showing up once right so we want to store everything all the possible powers we have and sometimes you might get double so we don't want that to be the case so the next thing you want to do is we have a list in reverse now uh in the dictionary next thing we want to do is loop through it in the forward order so before i word and enumerate words so notice how you're using the same function same looping through here same looping mechanism through in the beginning it's um not very efficient but it's kind of a must in this uh this solution here let's see we want to find so for each word and that we're looking for in terms of our um the length of our work and for each word in here what we're gonna do is that we're gonna loop through for each element j in the range of our length of words word i should say plus one what we're going to do is that we're going to fire prefix and our suffix so we do prefix is equal to where assigned to let's see so everything from the beginning of our uh of our word to j and we're looking for something called suffix which is everything after j so be j cole there you go so we have we were able to loop through each of our words for each word we have to find prefix and our suffix that we're looking for these are possible candidates that are first to make their list so how do you know of our candidate is fits our criteria in order to be added to our results so for that we want to look at three main conditions so the first condition is we want to see for prefix is in our dictionary we want to know this is even possible to make our prefix from the words we have right that's uh that's the first one if our prefix is in our dictionary our next condition is and that has to be also satisfied is that if our element i is not equal to our dictionary at the prefix location right because we don't want um our next other word to be already in our dictionary to begin with because that's the actual word itself and also the also thing we want is we want to know that if our suffix is equal it's a palindrome itself because we want to know if the word itself is a palindrome then we're able to do to branch from that point and make it make add i think a prefix as a prefix to the front of it as well so if our suffix is a palindrome then we are able to add a prefix to it so we want to know uh if we want to know our suffix is a palindrome this is how we do it so you want to know if the reverse of the suffix is equal to the suffix itself okay if that's the case then we know our prefix our candidate prefix is good to go and add to our results so results.add results so results.add results so results.add so we want to do is we want to add our pairing into there so element i want to add their dictionary at the prefix there you go okay now we have a prefix solved let's do the same thing a similar idea for a suffix so if our suffix is in our dictionary and we won't want let's say i to equal to the uh not equal to your dictionary at the of the suffix i should say and we also want to know if our prefix is itself a palindrome and therefore we can branch from that point is equal to prefix what we want to do is this makes it a suitable suffix a suitable candidate to be added to our list results dot add um so remember this is our suffix so we want to add it from the reverse direction right we want to add it from reverse so we want to do is uh dictionary at suffix comma i alright what do you want to return now so you want to return screw up all the pairs of distinct indices in the given list so in order to do that we want to we have every single results already we have everything in a set so in order to expand that out let's do some list comprehension to be able to list all of our um palindrome let's say characters for p and results all right so now that we're turning that in a list it's going gonna be a uh it's gonna be a pair of a pair listing within the list let's run the code and see how that works let's see all right i forgot a is inbox syntax hmm what line is this oh i forgot to come up right there that's not it oh now white at the word location mobbed okay finished and it looks so yeah it looks the same uh the same just not the worst non uh the pairing and not in the same order so let's submit see if it works crossing my fingers okay accepted awesome so in terms of time complexity let's see what we're working with so let's say if given our word length is um n and our each element in our word length so the length of each word is 300 so let's go over here we in we do for loop right here which enumerates it so this would be um uh it would be n times right we also do another for loop here it's for numerating words so it'll be n times so it'll be two at two n so two times n right then we do a for loop again for a word length right here so we have uh m now so it'll be two n so for two times this times um our word length so far m and then we do a list comprehension to make a list of it as well so we do not for the break here because the list is uh of constant time so what we do is we do two for loops um that are nested for this for m and we have two times the enumerate function for a for loop for our n function so b so the overall time complexity would be a big o of n times m squared and space complexity what we're doing is we're keeping actually uh let's see we're keeping a dictionary and a set right but the set is unique so the dictionary will give us the every single so it would be um basically we enumerate through so it'll be big o of n plus a uh the set where we store everything inside as well and also the list that we're returning so yeah i think it'll be uh a lot bigger than that uh probably uh big of n times m all right that's uh that's it's accepted uh this is a night i like this one it's pretty uh deep thinking all right have this ever a nice weekend our day
Palindrome Pairs
palindrome-pairs
You are given a **0-indexed** array of **unique** strings `words`. A **palindrome pair** is a pair of integers `(i, j)` such that: * `0 <= i, j < words.length`, * `i != j`, and * `words[i] + words[j]` (the concatenation of the two strings) is a palindrome. Return _an array of all the **palindrome pairs** of_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\] **Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\] **Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\] **Example 2:** **Input:** words = \[ "bat ", "tab ", "cat "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "battab ", "tabbat "\] **Example 3:** **Input:** words = \[ "a ", " "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "a ", "a "\] **Constraints:** * `1 <= words.length <= 5000` * `0 <= words[i].length <= 300` * `words[i]` consists of lowercase English letters.
null
Array,Hash Table,String,Trie
Hard
5,214,2237
474
Jhaal Hello Viewers Welcome Tak Bharat Middling Question Adhir Van subscribe and subscribe And subscribe The Amazing Loot-Loot It's More Vinod The Amazing Loot-Loot It's More Vinod The Amazing Loot-Loot It's More Vinod Kushwah How To Find Largest Subscribe Button Adhir Way Possible Loot Subscribe subscribe this Video give and old and in the recent subscribe and subscribe our Channel subscribe this will have accepted festival leather industry mid value will continue till the end of this train will dhesh approve subscribe do not contradict to avoid my tab induct head the length of the Thursday no 10 Nov 09 video2018 Loot subscribe Video Subscribe Hai Loot Main To Idhar Bhi To Saravana Das Tragedy To Chief Bureau Phase Subscribe Loot-Pit Thursday Subscribe And Loot-Pit Thursday Subscribe And Loot-Pit Thursday Subscribe And Skimming 1.5 Thursday Fog Subscribe Skimming 1.5 Thursday Fog Subscribe Skimming 1.5 Thursday Fog Subscribe Bill Dhung App Quick Same Festival 00 - 10 - Sid Find Value Subscribe Withdrawal 019 Sexual Lies in the subscribe to subscribe our A Question Bright Result Sense Test Cases But When His Mother Loves You Will Get Time Limit Exceeded Apna Duke of York magazine1 Subscribe Valentines Appointed subscribe Video Subscribe Note 510 Ki Subscribe Our Video Shubhendu Vyakti Saravana * R You Will Be Shubhendu Vyakti Saravana * R You Will Be Shubhendu Vyakti Saravana * R You Will Be Amazed With Festival mid-2012 Id Amazed With Festival mid-2012 Id Amazed With Festival mid-2012 Id Subscribe &amp; Share Topics Id Subscribe &amp; Share Topics Id Subscribe &amp; Share Topics Id Appointed Returning Velluvae 2017 K Notes By Tourists Co Dog In Sydney For The Mid Point Of 108 Na Lecture So Let's Submit Subscribe Interview And Subscribe Now To Receive Thursday will be id am id step number Shravan 1.god reduce by the number of Vivo Shravan 1.god reduce by the number of Vivo Shravan 1.god reduce by the number of Vivo v11 present in the string value of the number 90 which can reach from minor which is 204 120 which and similarly the value of one can reach from anywhere between - Account of 1000 Dark Vaikuntha Find Thursday Subscribe My Channel 251 Subscribe To That SDO Putting The Value Of 0n 1.2 That SDO Putting The Value Of 0n 1.2 That SDO Putting The Value Of 0n 1.2 Index Into The Bare Midriff Vivaah Value Research Labs' Idli Nothing But The Mid Point Of Time The Value Of Root From Value Withdrawn Its president is built in cases suvvi subscribe button subscribe to vid oo do
Ones and Zeroes
ones-and-zeroes
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:** strs = \[ "10 ", "0001 ", "111001 ", "1 ", "0 "\], m = 5, n = 3 **Output:** 4 **Explanation:** The largest subset with at most 5 0's and 3 1's is { "10 ", "0001 ", "1 ", "0 "}, so the answer is 4. Other valid but smaller subsets include { "0001 ", "1 "} and { "10 ", "1 ", "0 "}. { "111001 "} is an invalid subset because it contains 4 1's, greater than the maximum of 3. **Example 2:** **Input:** strs = \[ "10 ", "0 ", "1 "\], m = 1, n = 1 **Output:** 2 **Explanation:** The largest subset is { "0 ", "1 "}, so the answer is 2. **Constraints:** * `1 <= strs.length <= 600` * `1 <= strs[i].length <= 100` * `strs[i]` consists only of digits `'0'` and `'1'`. * `1 <= m, n <= 100`
null
Array,String,Dynamic Programming
Medium
510,600,2261
7
if you are preparing for a coding interview make sure to check out these videos you will find it helpful hi everybody welcome back let's dive into today's leeco problem reverse integer we're given a signed 32-bit integer x we're given a signed 32-bit integer x we're given a signed 32-bit integer x and we have to return x with its digits reversed if reversing x causes the value to go outside the sine 32-bit integer to go outside the sine 32-bit integer to go outside the sine 32-bit integer then we have to return zero now let's take -123 as an example now let's take -123 as an example now let's take -123 as an example we have to reverse the digits of this integer but we cannot pick one digit at a time from the integer and reverse the order so we're going to convert that into a string and let's call that string str is equal to string value of x now we have created str of -123 now we can pick one character at a -123 now we can pick one character at a -123 now we can pick one character at a time and reverse the string so the reversal would be 3 2 1 minus but you see we don't really want the minus here we want the minus to remain here so we're going to check if the given number is a negative number so first let's take a boolean call negative and let's set it to false now if x is less than zero in that case we will set negative equal to true meaning the number is negative so we don't want to reverse the entire minus 123. we only want to reverse the numbers right so we will exclude this minus sign before we start the reversal so let's say str is equal to str.substring is equal to str.substring is equal to str.substring starting from character one okay now str is equal to 123. okay now let's reverse it so let's declare a string builder and let's call it reverse string equal to new string builder now let's reverse the string using the for loop so for int i equal to str dot length minus one i greater than or equal to zero i minus and then reverse string dot append string dot character at i okay so now we have received a reverse string of three two one now we can convert this into an integer and check if there is any overflow occurring or not but before that we have to account for the negative numbers now let's go ahead and account for the negative sign okay so we're going to say reverse string equal to we're going to use the ternary operator and check for the boolean variable negative if negative is set to true then we're going to insert the minus sign in the beginning of the string so we're going to say reverse string dot insert minus sign on 0th position and if negative is set to false then reverse string will remain as it is now we're going to convert this reverse string into a long variable let's declare variable long call it reverse and set to zero we are using long here because if we were to directly convert the string into an integer and if there was any overflow that occurred and we lost some digits then we wouldn't know so let's say reversed is equal to long dot parse long of reversed string dot 2 string we're converting the string builder object into a string and comma 10 because we want to use the conversion using base 10. okay now let's check if the number reversed is within the integer range meaning the number reverse should be greater than or equal to a minimum integer value and less than or equal to maximum integer value so let's say if reverse is less than or equal to integer dot max value and reverse greater than or equal to integer dot min value meaning if this condition is satisfied that means that reverse number is also within the integer range and we can simply return the integer value for that number so let's return integer dot value of reverse string dot to string else return zero okay now let's go ahead and run the code and there we have our solution accepted if you are enjoying these videos give it a thumbs up so that i get motivated to create more videos for you guys
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
1,941
welcome back everyone we're gonna be solving Elite code 1941 check if all characters have an equal number of occurrences so we're given a string s and we want to return true if that string is considered a good string or false otherwise and they consider a string good if all the characters that appear in s have the same number of occurrences so let's take a look at our example a b a CBC should return true because a b and c all occur twice within the string and yep okay all right so we could actually the simplest way to do this would probably just to be use the counter uh method from collection so from collections import counter and let's see here so let's just say our dictionary is going to be counter of s now what is this doing this is just going to Loop through our string and give a representation like so with the character being the key and how many times that character occurs within the string as the value let's print this out so you can see for sure so we'll print out D and run this so a occurs twice B occurs twice C occurs twice right so we have our mapping so now what well what we want to do is make sure that all of the values are the same right how can we do this well we could get the maximum value from all the values by doing Max of d dot values and we could do the same for the minimum equals to the Min of d dot values and then all we would have to do is just return uh maximum is equal to minimum and that should give us the correct output let's run that and find out okay so we pass both test cases let's submit and it does work okay so what is the time complexity for what we just wrote well we know that this first line is going to run in O of n time because it is looping through our string and grabbing all the counts so at most we're going to Traverse each character once right so that's o of N and then Max and Min are also both of these are also going to run an O of n because it has to Traverse all of the values in order to find the maximum and the minimum so our time complexity for this problem or what we wrote anyways is going to be o of n and our space complexity is going to be we're only using D for the counter so it's going to be whatever the length of D is so we can say o of d dot length and that'll be that
Check if All Characters Have Equal Number of Occurrences
minimum-number-of-operations-to-make-string-sorted
Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_. A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency). **Example 1:** **Input:** s = "abacbc " **Output:** true **Explanation:** The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s. **Example 2:** **Input:** s = "aaabb " **Output:** false **Explanation:** The characters that appear in s are 'a' and 'b'. 'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times. **Constraints:** * `1 <= s.length <= 1000` * `s` consists of lowercase English letters.
Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately
Math,String,Combinatorics
Hard
null
68
hello and welcome to another video in this video we're going to be working on test justification so in this problem you're given an array of strings words and a width Max width and you want to format such that the line is possibly matched with characters and is fully left and right Justified entry Packard is an ingredient approach packs many words as you can each line pad Extra Spaces when necessary so each line has exactly Max with characters extra spaces between words should be defined as evenly as possible if the number of spaces on a line does not divide words evenly the empty slots and the love should be assigned more and then for the last line of text should be less left Justified no extra space and inserted between words and uh yeah and a word is defined as a character sequence consisting of non-space sequence consisting of non-space sequence consisting of non-space characters only each word length is guaranteed to be greater than zero and not exceed Max width and the input array of words contains at least one word okay so we're gonna go through this there's a lot of examples here so let's start with this first one so we have this and we have Max width equals 16. so the way this works is basically what you want to do is in each line you want to put you want to be a greedy you want to put in as many words as possible but keep in mind every single word has to have a space after it so if we have 16 it's going to be hard to fit our stuff but let's actually draw that for 16 and let's show this essentially let's just make a box of 16 so then two and we're going to reuse this for five six seven eight let's make this a little smaller nine ten eleven twelve thirteen fourteen I think that's 16 voltage double check okay so for each word essentially we're going to be greeting we're just going to be writing letters in as we can and like if we can fit it so essentially we're gonna have two functions one is going to see like how many can we actually fit and then the second one is actually going to make the string so essentially all you're doing is this so like you're just starting here and you're just trying to write in the words and every time you can fit in a word into this you're going to add it into a result array so for example for this we're going to write like this then we need a space then is that's another important thing is you need a space after all these so even though you can fit more in the first line you need to make sure you have a space and then here you can see that example where it would run out of space so what we want to do in this case is we actually want to uh we want to actually return an array of this is an like each string is a different word and then we're going to have another function that will build up the word so for this is and that'll be the first line then if you see if we try to draw the next line we're going to have example sample and then of and then text will fit but then the next word won't right so example of text would be the next uh array that we send back and then finally justification is going to fit and same thing here so what must be would be what must be and then the next word uh acknowledgment won't fit and then so on and then if you only have one word what you want to do is you actually want to justify the words if you only have one word in here you will left justify and also the last line is left Justified as well where there's only one space between the words so that's essentially kind of what's going on here and that's like what our stuff is the same thing here you can see there's like even spacing between words and if there is a difference then you're going to want to have more in the left and the last one is left Justified so let's focus on making two functions we're going to have one function called like output Builder and then we're going to have another one called string Builder so especially all the output Builder will have is it will have an array and yeah this is a hard problem but I think it's not too hard it's more just can you do like a real life problem not a natural algorithm so you're not super concerned about I mean you are a little bit concerned about complexity but it's more of just a real life problem so if we have 16 characters essentially what we're going to have is we are going to have the way we're going to do this is pretty straightforward we don't need this array but what we're going to do in this uh res Builder thing let's call let's just build it up here so yeah we're going to call output Builder here uh yeah so we're gonna say output filter what we are going to do is we are actually going to have count of how many characters we have available and then for every word we'll just say like can that fit in an array and if it does let's add it and if not let's just return what we have okay and so output Builder will take an index and I believe that's actually oh yeah that's it and then we can get the we can get like the max width from just the function outside so let's say in this example our number of values let's call that V is 16 and then we'll have our res via empty array and so we'll take this first word this and we'll say like do we have enough space in 16 for this yes we do so we'll add this into our array and how many letters do we have left so we had enough space for this but we also need the space we're actually gonna have 11 letters left then we're going to have do we have enough space for is yes we do so we're going to add is and then we just use three letters because we need the space so now we have eight letters left and now and we have enough and we're going to use three letters again so we're at five and now we don't have enough for example so that's kind of how you do it you just keep subtracting letters from your how many you have left until you don't have enough for the word and then what we're going to return is we're going to return this array of like the words we could have used we're just uh an array with all the words we don't have to worry about the spaces and then we'll also return like the next index of the next word right so let's say this is on index zero we wanted to turn this array and then what's the next word we're going to be using it's going to be this example so that's going to be index three that's essentially what we'll return is we'll return this array of words and an index it's pretty straightforward algorithm you just check do you have enough and remember for the word you need to check if you have enough space for the word and then if you do you also need to add the zero but you can if like let's say your word length is like eight and your word is an eight character word you can fit it here right whatever this word would be that would be an a character word you don't need a space at the end but if you try to add another word then you would have to subtract one for that space so you fit in the word then you subtract one for that space for the word okay so that's how we do the output Builder pretty straightforward function now the main function we have to focus on is the string Builder right that's going to build the string for every single line like this line and so on okay and how are we going to do that first of all we're going to pass in a couple things we're going to pass in uh a value that will tell us is it left Justified we can call that left or whatever we want how do we know if it's love Justified well there's two cases one when we call this output Builder the index we will be on will be out of bounds right like let's say we just ran through all these words we're going to be over here now is our next available index which means we have our final output wherever that is right that's one case another case is the length of our output array is only one word so for length of our output arrays only one word we also want to make it left Justified so if this like last character so for this uh left or whatever or sorry let's call this last so if this last character last is true then we just want to return the array uh joined on space and then we want to left justify it right so we wanted to turn the whole array joined with spaces and then whatever's left over we'll just add spaces at the end so for example for the shall be you would just write shall space b and then the rest of it will just be spaces to fill up whatever your max word is and there is actually the rest to join with left Justified so we're going to use that so that's one case and it's pretty easy we're just going to pass that in what if it's not then what do we actually need to do so let's say we have this what must be right so our array is what must be so there's a couple things right first of all we need to figure out how many spaces are actually needed so for what must be we have a space here and a space here so we're going to create a variable called spaces I forgot what I call the macro function but let's just call it spaces and that's going to be the length of the words minus one right this is like the space this is that we need so this is going to be length of the word minus one in this case it's going to be two okay well our Max width is 16. so how many spaces do we actually like what so this is the spaces available it's called let's actually rename this let's call this uh something else so let's call this like maybe gaps or something yeah let's call this gaps or whatever you want to call it and that's going to be two and now space is needed will be what so if you think about it space is needed this we need to have this and then the rest of it needs to be spaces so we have four characters and two characters so we have 10 characters total but we need 16 so space is needed will be six so in this and this is pretty straightforward right if you have six spaces you have two gaps you just distribute like so if you haven't one we have a couple more variables so you have spaces per Gap pretty straightforward right it's just going to be spaces needed over Gap and it's going to be a like integer divide so in this case it would be three which were pretty straightforward so we just write like what with three spaces must with three spaces and B with three spaces and it's pretty easy to do right we can just add three spaces to this and three spaces to that and that'll give us our thing but let's say we didn't have something even right like let's say we had something else so let's actually go back to this but let's get another example just to make something harder like maybe some more words or something well let's just actually write our own array so let's just say our array is like what must be said and let's say we have like 25 width or something let's see what this is yeah I'll say we have 25 so max with equals 25 just to get a tougher example okay there we go so how many gaps do we have here where we have three gaps how many spaces are needed well let's figure that out right so how many spaces do we have total so we have four twelve fourteen so we need 11 spaces so our space is per Gap here is space is needed divided by gaps which is 11 lower divide three so it's going to be three and now we will have remaining spaces and that will be spaces needed mod gaps and that will be two right so now that we have the spaces needed per Gap that means there is going to be three spaces between each of these so we can just add three spaces to the end of these three words but now we also have two extras and where do we put those two extras that's pretty straightforward all we're gonna do is we're gonna take the spaces per Gap automatically add those to every word so every word will have three spaces added on plus these spaces needed we're just going to do a first come first serve so like for the first word We'll add a space for the second word We'll add a space and then we're out of spaces so because they said add it to the leftwards first so then our array will look like at the end what with four spaces so four spaces then it's going to be must with four spaces and then it's going to be B with three spaces and then set and that's what our final array looks like that's essentially all you need to do is you just need to make sure like is it a one word or the last word and if it's not let's just get the spaces per Gap can easily figure out the gaps like how many gaps there need to be by number of words minus one easily figure out the spaces per Gap that's how many you need to go in each one and then these exters you just do a com first come first serve where you just go through each word and you add another one and that's pretty much it for this functions and then all we have to do now that you think about it is we just have to Loop through our words and then we call as long as our index exists we just call output Builder we'll keep calling Apple Builder that'll keep giving us an array and then we check is that the last line by either the index or there's only one word so we just keep calling output Builder and skill Builder to keep building each of these things in the array and you keep doing that until you're finally out of bounds right so you keep getting words until you're finally out of bounds and that's pretty much it so with these helper functions it's going to be really nice because you can have both of them so yeah that's gonna be it so let's take a look at the code okay and so here it is let's just full screen this essentially yeah you have two helper functions you have words online that will take all the words on the line and make an array just like I showed right so you have a result array and then you say while letters you make letters left equals to Max with and you just keep saying okay either I'm out of bounds or I don't have enough letters left and every time I use a word I need to subtract the amount of letters I used if my number is negative that means I don't have enough letters and then I want to return the result array and the index of the next word I'm on and then you want to otherwise you want to just append the array you want to add the index and you want to subtract one more letter for that space and then finally you return the result and the index and then we have the create string that will actually take this elements array and this is last is just a Boolean saying like if it's true that's the last word you have or it's a one word array and either way you want to make sure it's left Justified and so this is how you left Justified you can return uh space join elements and then you just do left justify with a space and then that will ensure that this will ensure that with the left justify the rest of your stuff is going to be filled with spaces up until the whole string is equal to length Max width and then we want to get the total length of all the letters so we're just going to sum the length of every word in elements and then we're going to get the spaces which is just the how many total spaces we need so this is the spaces we need and then space count is those gaps and so like I said you have a Min spaces which is like this is how many minimum spaces you need and then the Extra Spaces are the ones that are left over that you're going to be using then you just go through your elements and then for every single element you append the word and then if I is less than space count you add Min the Min spaces you need and then you also add one if one's available otherwise you add zero so it's a first come first serve and then essentially you're taking your word and you are pending so actually here you're appending the word and then you're pending spaces so essentially it'll look like you're basically just the pending spaces in between every word so it'll be like word some number of spaces and so on and then you will finally join that at the end to give you the actual string then you just initialize the result you initialize the index and you're essentially just looping through your code you get so every time you call words online index believe that's this right yeah so words online index will return the element and the next index of where to search and then you check for is last meaning is that the last string or it's a one word string and then finally what you need to do is you need to uh append that creates string to the result and you need to update the index to the next index that was returned from words online then you finally return the result and check this run it and you can see that it does work and it's reasonably efficient so let's go through the time and space is going to be a little tricky we'll try to do that so let's just go through this like step by step essentially for Words online how long does that take so words online is essentially checking like as many letters as it can up to Max index so this is basically gonna uh actually I guess worst case scenario every word is like one character so worst case scenario it will take Max with time right like let's say every word is one character you're gonna have to keep checking one character at a time essentially so that's going to be so this words online is going to be o of Max with every time okay what about this create string with elements so this create string with elements let's look what we're doing so we're joining up the elements which is um essentially you're like making a new string which is all the letters and all the elements pretty much yeah I think you have to like build a new string so that's going to be something like length of all the characters and elements somewhere along that and then you're also getting the total length Which is less than that uh you're getting the spaces which are less than that you're getting this it's less than that yeah so essentially it's roughly for this create string it's roughly all of the letters in the elements that you have right so every time you call create string it's going to be roughly the length of all your characters so essentially if you keep calling create string that's going to be roughly let's say we have words so we can just say like o of words times like or we could just say this is like total characters right essentially total characters of every word combined to do the create string and then also this is going to be Max with every single time but I think that's going to be less than uh all the words well I guess it kind of depends now let me think if the words is like a really short array and Max width is really big what would happen we just go out of bounds right yeah so we're kind of capped by this words because if Max with us like a million the words there's only two words we're just gonna run out of bounds really fast so essentially I believe it's something along the lines okay you can tell me if I'm wrong but it's something along the lines of total characters that you have in every single word combined something along those lines you know you'll just be multiplying that by a few times because you're just going to be like creating the string a few times but yeah essentially we are just like looping through our word and remaking it again so that should be fine okay now let's look for the space so not counting our output spring result what else are we using so let's take a look so in this result technically you can store every single character in every single word so that would also be like because every single character and every single word can fit on one line so that would be o of like the same thing and then create string um you are returning a new string which I guess is technically going to your output so you could argue like you need that for your output but I probably wouldn't so yeah I'd say it's roughly this is also of total characters because you could create a string or you could use this to make an array to make a array of letters that's basically like if all your words are on one line then you're making an array of every single character total so I would say it's something like this where oh the time is O of total characters and the spaces of total characters um yeah so that's gonna be all for this problem hopefully you liked it and if you did please like the video and subscribe to the channel definitely not like a standard hard problem but you know a good one to try so I would recommend it and I'll see in the next one thanks for watching
Text Justification
text-justification
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. **Note:** * A word is defined as a character sequence consisting of non-space characters only. * Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`. * The input array `words` contains at least one word. **Example 1:** **Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16 **Output:** \[ "This is an ", "example of text ", "justification. " \] **Example 2:** **Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16 **Output:** \[ "What must be ", "acknowledgment ", "shall be " \] **Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified because it contains only one word. **Example 3:** **Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20 **Output:** \[ "Science is what we ", "understand well ", "enough to explain to ", "a computer. Art is ", "everything else we ", "do " \] **Constraints:** * `1 <= words.length <= 300` * `1 <= words[i].length <= 20` * `words[i]` consists of only English letters and symbols. * `1 <= maxWidth <= 100` * `words[i].length <= maxWidth`
null
Array,String,Simulation
Hard
1714,2260
135
all right so this question is candy you have any children and then you want to give out all of candy to the children and you choose a massive candy at least one candy and children with a higher rating get more candy so return the minimum number for candies you need to distribute right so this question is straightforward enough so imagine the children the first children is what the ratings one the second children is rating of zero and the next one would be like the two so that would be the highest one so you definitely need what each children must have this one candy so I can actually say one over here and then for the neighbor I can have increasing by one right so their action now they're actually not uh valid uh concern right children with higher rating get more candy so these children since it is lower than I mean lower than the neighborhood right so this has to be well this has to be one and even though they got too candy even though they have different ratings it doesn't matter like you just have to know that the lowest one will get one and the next one so this is two right it's greater than what it's greater than the neighbor so it has to be two and this is what these are two I mean they're they have the same rating so you have to be greater if not greater you can know what you have to be lower right so this is the idea right so I can actually Traverse from the red left to right and basically just keep checking the pier right I'm going to compare the peer by peer so this will be one period this will be second peer and then if I'm going to compare the left the current index comparing width left and then I'm going to increment by one every single time right and then list will be only like one-way direction list will be only like one-way direction list will be only like one-way direction right I need to thing about that how about you have to compare the right so in this comparing with the right so I will have peer back here again so peer by peers so in this one from period with the right and then I need to find out the current maximum between what the current uh index so I'm going to say DP because I'm storing the value right so DV with I or what on the DPI plus one so this is a idea and I'm just before I call I want to talk about something so I'm going to just allocate a memory I'm going to call DP and I'm going to set everything with one so every student have a candy so I'm going to say okay I'm comparing with the left so I'm saying this one the current index comparing with the left Index right so does zero greater than one no so let's move on so there's two greater than zero yes so increment by one so right now is one two and I need to go the other way right two and zero right so I'm going to say is the current is zero uh Grill and two no so I skip so if current one greater than zero yes so I'm from so I increment so I can say increment or I take the current value so this will be one or increment right so increment by what but at least about it so one comma one plus two you have to find out the maximum which is going to be two so this will be our answer so um I'm gonna stop holding so PP new range so the length would be exactly as in and then I need to fill the array DV equal to one right I need to Traverse from 1 to the end so I'm comparing with the current value with the what the left and minus one and if this is true I'm going to say DPI you know even the DPI plus as I minus one sorry M minus one plus one you complain with the left right now you want to compare with the right but you want to start from the end either equal to zero and minus so if the ratings at all and ratings and I personally I'm sorry you want to um either increment or you want to find another current maximum value so I would say Okay DPI to the next Max API okay so later on all of the value in the DP are all the uh all the candy you want to return right so you can basically say okay uh you feel the results you Traverse wall in DP and then you basically add in right this is actually okay uh you can also you know write a code in a in your online so array a stream I'm going to say d beta sum so I'm going to declare every single number so this is also doable so you submit that this is the answer so let's talk about the timing space for the time this is also a time to the complexity is simple it's going to be from uh index zero basically in this zero to the end so it's going to be all of all representative ratings and the space you know space is this one all of them right so uh time is special the same so I'm going to just make some crazy number and yeah basically I'm going to put some debug and you will see what just happened that's good just look at the windows on the left and then make sure you understand everything all right so this is the answer right you pause every single second when I click right and then you understand what just happened and then if you want to say okay DVR equal to what PPI plus one this is not okay this is definite enough but even though you pass a test case but for some Corner cases right you are now going to give the correct answer so this is a solution so if you feel helpful subscribe like and comment if you have any question and I will see you later bye
Candy
candy
There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`. You are giving candies to these children subjected to the following requirements: * Each child must have at least one candy. * Children with a higher rating get more candies than their neighbors. Return _the minimum number of candies you need to have to distribute the candies to the children_. **Example 1:** **Input:** ratings = \[1,0,2\] **Output:** 5 **Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively. **Example 2:** **Input:** ratings = \[1,2,2\] **Output:** 4 **Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions. **Constraints:** * `n == ratings.length` * `1 <= n <= 2 * 104` * `0 <= ratings[i] <= 2 * 104`
null
Array,Greedy
Hard
null
1,903
hey everybody this is lry this is day seven Leo day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's far I'm here in kenting National Park in a cave that's all I have so let's get to the problem yeah uh hope you like the intro I'm actually now in uh Kash um yeah just enjoying myself so uh my internet's a little bit dubious I booked a price for a Wi-Fi for some booked a price for a Wi-Fi for some booked a price for a Wi-Fi for some reason uh didn't even think about uh the possibility that an Airbnb can not have a Wi-Fi these days so uh can not have a Wi-Fi these days so uh can not have a Wi-Fi these days so uh yeah so going we'll see what happens I'm uh tethering off my laptop um off my um SIM card we'll see if I get to soon so uh hopefully everything's good but today seems to be easy one so we should be okay today's Farm is 1903 largest art number in string you're given a string num we% a string you're given a string num we% a string you're given a string num we% a large integer we return the largest rout at integer that is non empty substring of nums or an empty substring empty string if no odd integer exist so the largest odd integer so basically this just means that the last digit has to be uh an odd and of course after that you just greedily take everything you can because the more digit the better right I think that's pretty much it uh so if there are any numbers uh yeah the O the length is 10 to the 5ifth not to be confused if the number is 10 to the 5ifth but yeah so basically you just take the prefix where the last character the longest prefix where the last character is an odd character or odd number sorry and that should be good because you want to keep every number it's very easy greedy uh and yeah that's pretty much it right so basically let's say last is you go to length of num right uh well last is greater than zero maybe uh if num of last I guess this is equal to uh if this is an odd number then we're good right then we do stuff otherwise we return empty string uh decrement and yeah and basically we'll return the prefix where it goes to last right this just including last so I think this is it right looks good let's give it submit yeah that was pretty good uh yeah I don't have much to say about this one I think it's just about recognizing greedy and long big characters this is a easy app to us so I'm not going to uh waste any more time here um I think the one thing that you have to be careful is that n of course is 10 to the 5th which is the length of nums so you have you want to be careful that you don't do anything n square and as long as you don't do anything n Square you should be okay uh like I said I have to upload this and D is an issue so I'm just going to stop it today uh let me know what you think stay good stay healthy to good mental health I'll see youall later and take care byebye
Largest Odd Number in String
design-most-recently-used-queue
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** num = "52 " **Output:** "5 " **Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number. **Example 2:** **Input:** num = "4206 " **Output:** " " **Explanation:** There are no odd numbers in "4206 ". **Example 3:** **Input:** num = "35427 " **Output:** "35427 " **Explanation:** "35427 " is already an odd number. **Constraints:** * `1 <= num.length <= 105` * `num` only consists of digits and does not contain any leading zeros.
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
Medium
146
48
hello boys and girls and welcome to another episode of your favorite algorithm channel my name is Ryan powers and today I'm gonna be taking you through leet code 48 rotate image so this is gonna be a fun problem depending on where your mind goes when you start this it could be extremely frustrating or really easy I don't know which way it's gonna go for you but I definitely recommend you try it yourself first but let's introduce the problem here real quick okay so you're given an N by n 2d matrix representing an image so that's kind of what this square is here and we need to rotate the image clockwise by 90 degrees so you have to rotate the image in place which means we can't do a map and return a new 2d matrix we need to do this in place we can't use any extra space okay so you have to rotate the image in place which means you have to modify the input the 2d matrix directly do not allocate another 2d matrix and do the rotation they really don't want to see that so we're not gonna do that okay awesome so let's just take a look at a couple examples here so you can see here we have an in this is representing an image right so it's one two three four five six seven eight nine okay and if we rotated this clockwise you can see kind of like where these numbers are ending up right so this one is moving from here to this other corner the three is moving here down to this bottom right corner the nine is moving here down to this bottom left corner and then the one and then okay and then the seven right so the seven was on this bottom left corner and now it's on the top left corner and then you can see that these numbers are all kind of rotating around you know it's kind of just turning you can just imagine that if you just took the whole matrix and you just rotated it 90 degrees that's what we're trying to do so this five here in the middle stays in the middle right but everything around it gets rotated clockwise and I think it's a little bit better to look at example like this which is a 4x4 2d matrix because there's actually two levels of rotation happening but you can see there's no like middle value like there is on this one up here right so these four values in the middle do get rotated if we look at this picture here and then actually I think maybe even going working with an example that's one a one index larger would actually be a little bit more helpful because you would see kind of three maybe three layers of rotation happening but that's kind of the gist of the problem it's a programmatically kind of shifting things around which if you really enjoy doing that then you're gonna love this problem it can be kind of challenging to come up with some sound concise clear logic for making this rotation happen but it's totally doable and I challenge you to try to do this actually in under 40 minutes I think is a really good challenge because you know the idea of it isn't too challenging right it's more about the implementation this is more about the implementation of like how do I rotate this thing and get my logic just right so that's the challenge for today and as always please try it first and if you get stuck or you just want to see how I solved it then check out the video otherwise if you're ready to get started come with me the whiteboard so on the screen here you'll see a 2d matrix so it's numbers 1 through 36 and so it's a little bit bigger matrix it's 36 spaces but I want to show like a couple rotations of how this thing is actually working and how to actually think about this structure in a way that's simple to kind of reason about and that's why I wanted to challenge you to do this problem in under 40 minutes because I don't think it's too difficult to actually you know on a piece of paper move these things around you can kind of come up with an idea of how these things should move the challenging part is actually implementing all of this movement right and coming up with kind of a clean simple approach to actually implementing this rotate image function so that's what I want to do I wanted to challenge you to do in 40 minutes to see if you can just get your thoughts into code in a reasonable amount of time so anyways there are many different ways to solve this problem this the way that I'm going to do it is not it's not the only way to solve it's the way that I thought about this problem so I'm just going to share with you kind of my strategy it's not the only strategy but I'll share with you kind of how I think about this problem so I think one of the big kind of concepts about this rotating image thing is when we think about iterating through an array we always think about iterating through an in each index right we think about it as kind of like a linear thing right but I think the best way to think about this problem is in rings right so we're iterating through the Rings and I each phase we're going in deeper right and then we go through this next ring and then we go through this final ring right so that's kind of the way to think about it right we're not iterating through lines of the matrix right we're iterating through the rings that the edges and we're rotating each one as we go so how would this look well so what we want to do is we want to grab these kind of these four spots and we want to just shift them right so we're going to shift them and what we're going to do to actually make that happen is use this first index is kind of like a pivot point right so we're so we would switch the one in the six and then we would then use that same index to switch these two indices and then at the very end once we swap these two everything will kind of fall into place so that's kind of the way that I think about it we'll use this kind of starting index or this first top left corner we'll use that as kind of the swapping index and then that way we'll be able to kind of just move our numbers back and forth in this kind of rotating fashion and our numbers will kind of end up in the right place right so that's kind of the first way that I think about it and how we're gonna move around so then we'll just kind of move around you know the outside like so right but I wanted to point out that the most important index is this first one right here right this is the most important index because this is the swapping index and then as we move through our swapping index is always going to be on this first row right and we're going to be swapping with all the other rows in this index so let's kind of go through how it looks just to give you a better idea of my thought process so what kind of start over here cleaning this up and we're gonna start with these first two indices right and we're gonna swap these two so we'll swap these two and now one is in its place so if it's blue we're gonna say that it's done we don't need to move it again and if it's red well that means that we need to keep swapping it right so now our six is in this first place and we're gonna swap it with 36 okay great so now six is where it needs to be in 36 is now in the swapping index and now we'll swap 31 and 36 okay so now these four have been swapped and we're just going to kind of work our way around the ring like this right swapping these index and keeping that first part of the array as the swapping index so we'll go through again swapping out all the numbers and just working our way kind of around the circle like this ok so now we've got a swap for and 24 and now I have 24 we're swapping 24 33 and now we're swapping 33 with 13 okay now those numbers are where they're supposed to be and then we swap five or thirty swap 31 32 and then swap 32 with seven okay so now we have successfully rotated this entire outer ring right and now we need to move into the next ring right we need to me to squeeze in from both sides and from the top right redefining the our iteration space right so which is going to be this next ring so we start swapping an 8 and 11 and then we swap 11 with 29 swapping 29 with 26 and then those numbers are where they're supposed to be so then we saw up 9 with 17 swap 17 with 28 swap 28 with 20 and now those numbers are where they need to be and we move on to the next index swapping 10 with 23 swabbing 23 to 27 then swapping 27 with 14 okay so now we've finished two rings and now all we have is this inner ring where we just swap basically these four numbers right so 16 with 22 and then 22 with 21 so it's really just about how do i define this kind of ring right like how do i define my iteration through this ring and that's gonna be a it's conceptually I think easier to think about then maybe to code but I want to point out that we have successfully rotated this matrix if we go through and we look at these they're in order right 1 2 3 4 5 6 7 8 9 10 11 12 right so we've we basically rotate this whole thing clockwise one time right and so what's the time complexity of this problem well it's a Big O of n right and n is equal to the size of the matrix okay so basically we have to go through the entire matrix one time touching every single index right we have to swap every index so it's Big O big of and in terms of the size of the matrix or I guess you could say it's a Big O of I don't know and plus and but really like the dimensions are the same right we if we treat all of these inputs like each one is an item within the matrix then we can just say it's a Big O of N in terms of the matrix but I think that the main takeaways here are just thinking about it in terms of the rings right like I'm iterating through a ring at a time until I reach the center and once I reach the center I'm done right and we're squeezing in from both sides uh-uh squeezing in from both sides uh-uh squeezing in from both sides uh-uh every time we complete a ring we're kind of we're smashing our search space down one level right until we get down into the middle so that to me is kind of the simplest way to think about this problem it's maybe a little bit easier to think about that it is to implement but if you're a now that you know kind of the concept or the idea to solve this let's see what it looks like in code on the screen here I have a helper function a swap function so we're going to define a swap function to do our swapping for us and then we're going to do all the logic for the rotation inside of this rotate function so the first thing that we're going to do is we're going to create a couple variables so we're going to create a low variable and then we're going to create a high variable so what's lo going to be well we're just going to initialize load to zero and then high is just going to be equal to this is basically just the dimensions of our matrix right so it's going to be equal to the matrix dot length minus one so that's going to be the last index in our matrix and then what do we want to do well we want to keep rotating we want to keep doing our rotation work while low is less than high as soon as low is greater than or equal to two high well then that means that we've kind of like terminated all the way to the middle right we're not in an outer ring anymore we're in the middle so there's no more rotating around the image that we actually need to do so we'll say that while low is less than high well we want to keep doing our rotation so what we'll do is we will add two low at every iteration and we will subtract from high at every iteration and so the other thing that we need to know is we need to know what is the distance between our low and high right because as we're iterating through those rings we need to know what is the width of this ring like how far across the ring do I need to go what are the dimensions of the string so we'll create a length variable to be the length or the dimensions of our ring and that's just going to be high minus low so that's going to give us the dimensions of our ring which will be very helpful to us in actually iterating through this so of course now what we need to do is we need to actually do a loop around this ring so we will set up a loop here for this so we'll let I be zero and while I is less than length we will keep looping okay so now we're going to loop around our ring we're going to do a ring around the image here and we need to do three total swaps right with that first index to move that number so we'll do a swap and we'll set up three of those swaps and we want to swap the top left corner with each one of the corners at every iteration right so that's thus the three straps we're doing we're swapping here and then we're finally swapping on the left side so what so of course we need to pass the matrix into all of these swaps so we'll do that first passing in the matrix and then so what is this top left corner well that's going to be 0 right so our low bound is the first index we're going to pass the index in to this swap function so for that top right corner right that's going to be the first row on the last column so that's going to be our low bound and our high bound for that column index and then for actually passing we need to also pass in the location of our top left because that's where we're swapping with every single time so that's going to be the low and then we'll create a variable called index so we actually want to we can calculate this out of here so we'll create a Const index and we'll set that equal to low plus the plus I okay so what is low plus I well our first index is going to be at the zeroth row right and then as we iterate through it's going to be zero plus our plus I is going to be the swapping position so that's low plus index or low plus I is going to be equal to index we're going to pass that in to every call to our swap function and then how is that top right corner going to move well it's going to move down that right side right so we're going to be incrementing the row each time as we're iterating so that's going to be we want to increment the row right so that's low plus I okay great we're not changing the column right we're just changing the row so what about the bottom right corner right what about that one well we're starting at the bottom right corner and we're kind of moving along the bottom like back toward the beginning right so that's going to be a bottom right corner so that's going to be our high bound and our high bound right so that's going to be like the last row and the last column so that's high down in high bound and then of course you want to pass in low and index for our what we're swapping with okay so we want to not change the row but we want to change the column so we'll subtract i from the column as we're moving through and then finally what about that last so that's the bottom left corner well that's going to be high for the row the last row and then it's going to be low for the column the first column and then we actually want to move up subtract from the row we want to move back toward that zero position right so we'll subtract I from that and then well of course pass in the location of our swapping index which is going to be low and index that we calculated right here which is just low plus I because we're starting it at zero and we're adding i2 to the column okay so now we need to do the swapping part of this so the swapping part this is just a basic swap function so we just need to define a temp and we'll set that equal to the swapping index which is going to be the last two variables to Pasadena so that's going to be K and L and then we want to set this location K and L we want to set it equal to the first two indices that were passing it which is going to be and the GA okay and then we want to set I and J so the matrix at I and J we want to set that equal to 10 the value that we stored so this is basically it right we need to of course we need to return the matrix at the very end okay so we'll return the matrix awesome so that's basically it that's all the logic so what are we doing here well we created this swapping function which just swaps two indices in our matrix in our 2d matrix and then we created this rotate function so we just established a low bound and a high bound which is basically the dimensions of our 2d matrix right and we're going to decrement the size of that at each iteration till we get down to the middle and we can't we don't want to rotate it anymore like once lo is greater than or equal to high well then we know that there's no we've rotated everything right we've reached the center of the picture the image or whatever you want to call it and then at each iteration we want to iterate through the ring we want to go all the way around the ring and how are we going around the ring well we have this length variable that were that we're calculating here which is high minus low that's just telling me what is the length of one side right and I'm iterating through each side as we go around swapping kind of having this motion happening swapping the indices and we're doing that using our swap function and then we are shrinking the size of our ring at each iteration and then returning the matrix at the very end so let's see if we have any bugs okay great 72 milliseconds let's see if we can do sweeping it a little bit better I can't keep trying let's see give it one more try okay awesome 60 percent leak code I think they you know they don't like me just bad-mouthing them all the time just bad-mouthing them all the time just bad-mouthing them all the time about how they're purposely slowing to my runtime so it looks like they fixed a problem I don't know what the problem was I don't know what they were doing but they definitely were trying to make me look bad but it seems like that's all over with now cuz look we just got a hundred percent on one of our problems but anyways this algorithm or this function this problem it can be really tricky just kind of getting that logic right for that rotation it's not terribly tough in concept but definitely challenging in implementation especially to do it in a clean concise way so if you were able to achieve that goal of actually implementing this function in under 40 minutes congratulations to you I didn't quite get there myself it took me a little bit longer to clean it up and get this looking in a presentable way record actually show it to you guys but anyway I hope you enjoy this video I hope you learn something and I hope to see you in 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
168
hey everybody today we'll be doing another lead cod18168 excel sheet column title this is an easy one given an integer column number return its corresponding column title as it appears in excel sheet so they are giving us an integer like this in an example we can see here 28 we have to return it in the form of excel sheet column title and that's it like 701 will represent z and y so first of all we'll be making a list you can say capital letters list capital letters so to make a character list we have to type cast it first because we cannot just go for i in range uh for characters we have to just type casters for example hi here i and for i am range will be giving the ascii number of the starting element and also giving the ascii number of the stopping point plus one because obviously we want to include our set this will have all the characters 26 but the indices are different from the numbers itself for example we have 26 as a number uh and it will represent that is on 26 number but in this array it is on 25 because we are including zero also so you know how in array things work with the undersize so while our column number is greater than zero we will just add it to our result like kept let kepler and now column number minus one first because obviously we do not want to go out of bounds this will if we do not minus one then we will go out of bounds and i will not have a 26 digit in it or some or something like that there is a not out of bounds but there is always like if you can see in our arrays we have a at 0 location and b at c b and c and d so as a number they will be represented as 1 2 3 4 but in array they are 0 1 2 3 that's why minus 1 and that's it and we are done on in this line uh yes so now we will just remove the last element from our column number is equal to column number minus one and doing ground division on it will be 26 and that's it this should work now and after doing all of this we will just return our result by reversing it and that's it this should work there is a compiler runtime error column number not number this was just a spelling mistake nothing more and this works that's it
Excel Sheet Column Title
excel-sheet-column-title
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnNumber = 1 **Output:** "A " **Example 2:** **Input:** columnNumber = 28 **Output:** "AB " **Example 3:** **Input:** columnNumber = 701 **Output:** "ZY " **Constraints:** * `1 <= columnNumber <= 231 - 1`
null
Math,String
Easy
171,2304
72
uh today we're gonna be working on youth code question number 72 edit added distance now given two strings word one and word to return the minimum number of operations required to convert word one to word two you have the following three operations permitted on a word insert a character delete a character and replace a character so in the first example if the word one is the horse and the word two is ross where you can do these operations replacing age with r removing odd and removing e in order to make the horse equals to ross so the output is going to be equal to 3 yeah in this second example if the word one is intention or two is execution so the operations we can do are removing t replacing i with e replace n with x replace n with c and insert u in order to make the intention equals to execution so the way we're going to be doing it is using the dynamic programming so if we have a word basically if the word both of the word are the same we're going to be taking the diagonal one whatever that's the value so basically we're going to be first of all preparing a matrix like the matrix and then we're going to be filling it out from the top left to the bottom right so we are initializing our matrix called dp as like basically empty basically the empty elements of the size basically the size matters here so the size is going to be equal to the size of the word one length across the size of the world too and we're just filling everything with the empty elements so our row is gonna traverse from row zero of that matrix uh to the last row which is basically the word one length and our column c is gonna traverse from uh zero to the uh to the last column which is the word two dot length so the operations we can have is let's say if there is the first row in that case we are basically filling up the first row uh whatever is the value we are gonna initialize at the value of the column so whichever so in the first row you're gonna just fill it up with uh if it is the first column fill it with zero if it is second column fill it with one just like that similarly if we are working on the first column we're gonna fill the whole column with whatever is the value of the row so it will be 0 1 2 3 so on and so forth otherwise if the index representing index of word one the character represented by the index of word one is equal to the character represented by the other index represented by the uh by the column of word two if they are equal all we have to take is the uh the diagonal value so basically we are saying that uh ignore uh what you have right now and just go uh take the top left value so r minus 1 c minus 1 is the top left value and in case it is not equal this is the final case if it is not equal then we're going to be taking the math dot minimum of all three above left and top left we're gonna say that this one column is the left value dp of rc minus one and then uh dp of r minus one c as c minus 1 is the top left and then dp of r minus 1 c is the top value so whichever is the minimum value we're gonna take that plus one and in the end we're gonna be returning the last element of that matrix which is the bottom right element of that matrix which is equal to the dp of word uh word1.length and word2.length yep and that works
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
1,819
Hello friends small in this video will be going through and problems from list to return for latest weekly contest to three 500 heart problem net problem number of different sub sequence like piece this statement is not difficult to understand but understood in these countries will lead you find The answer is very simple form from the left side give different numbers and it is commented on Devisive Oil Number click here know what you how to find the test content subscribe and subscribe the Difference possible number of different fields with the no entry subscribe Video then Quit From This 6036 Ok Dowry Deposit Sequences 1060 Doctor Different Sure To 8 And Work Towards Life And Different Issues Related To Reduce Uric Acid Subscribe Now To Do Subscribe To Work With Synonyms And Name Maximum Kar Do Is Number Sampann 225 And Find If CD December Is The validity and width answer is that this option find where did not fixed deposit hair at all not only 2525 chicken i got on whatsapp a darkness of the size and amount and office number switch off present in this not but him loud option boys or f-35 Ok involve work out option boys or f-35 Ok involve work out option boys or f-35 Ok involve work out the number is president subscribe 23456 subscribe now to three do the number incident of the year subscription is more a college student this Vivo of water from pm only two days free leg here Jatin Yadav sequence liquid user any subscription Video not black suit For Answers Issues Will Be Coming To The Number subscribe to subscribe our Channel subscribe The Number 2 And Will Definitely Want To See A Text And Office Number One Withdrawal Want To Have But Little But IF The Numbers Decorated 9483 Number Two Not Want To Give To Show Width Problem You How To Do Sole Number To Take Only From This Point Number To Take Into Account For Not Fall subscribe to the Page if you liked The Video then subscribe to the Page Pimp Check Out Weather Supaul Office Number Aditya But All The Best Pattern Bigg Boss Acid Deep Study subscribe The Video then subscribe to the Page if you liked The Chittor 600 800 On Only Platform Upto 10 Number Make Up Chief and Mid Term Number Subscribe Button Incomplete Video then subscribe to the Page if you liked The Amazing Number 1090 Quiet Over All the Number Vishal Multiple Update Number Industrial Area And You Would You For The President Number To The Number Only subscribe The Video then subscribe to the Page if you liked The Video then subscribe to subscribe the Channel Please subscribe and subscribe the Channel If Acid Citric Acid is valid for Android then we are in Center your only diet number is president of way directly possibility of its troops withdraw residence acid possible youtube over all the multiple subscribe liquid not just all the number subscribe must subscribe to
Number of Different Subsequences GCDs
construct-the-lexicographically-largest-valid-sequence
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
Array,Backtracking
Medium
null
1,208
See, in this video we are going to do the question of Lead Co, Get Equal Substance with in Budget, you will be given two strings and a max cost integer will be given, the question is you have to convert one string into another string, now like mother, I will convert another one. If I am in B, what will be its cost? The difference of their today's values ​​is correct of their today's values ​​is correct of their today's values ​​is correct and that too the absolute difference i.e. the and that too the absolute difference i.e. the and that too the absolute difference i.e. the modules of their values ​​i.e. the modules of their values ​​i.e. the modules of their values ​​i.e. the value of S - its and its mode i.e. value of S - its and its mode i.e. value of S - its and its mode i.e. positive value. What is the question? What is happening is, look, you have two strings and your max cost is, keep the max cost in mind and tell me, I can convert so many s from the biggest, you understand, like here the max cost is three, okay and if I If I convert the string from here to here then how much will it cost to convert A into B, one cost to B into C, one cost to C into D, there will be a cost to convert Di into F i.e. Puri Di into F i.e. Puri Di into F i.e. Puri of Puri Sting, if I want to convert, then the cost will be one, two, three, five, but the question is not that you have to stay within the maximum cost, that is, the cost should not be higher than this, what does it mean, find out the maximum which can be converted. The power is with in this Mexicos and if I see the length of ABC is three which is the power to be converted into ABCD with in this max is okay so this is our question if I will not be able to convert it like here. You will see A B C D A C D Max cost is zero but the style I am looking for is A and A Se i.e. U are already A and A Se i.e. U are already A and A Se i.e. U are already equal, what does it mean, output is one, why is the length calculated, for this N length is calculated. How many m have I been able to convert, so one tax, like this here, if there were three taxes, then what was the output, three, let's do our question, I am taking one n, which will convert its length into days, or will it convert its length into days, let us know. The length of both of them will be similar. Okay, let's take some variables, let's take the answer, this is equal to zero, let's take the window, let's take zero and because this is a question of everything, we have seen that all the distinguishing things are the same, it is a question of string. What this means is that we have to do the sliding window approach, so let's take two painters, one will take the left and the other will take the right. Let's initialize the right inside the loop. Right is equal to zero and right is equal to n right plus. Now we have Do you know what we do in the sliding window? What will we do last? We will return the answer. What do we do in the sliding window? First of all we prepare the window. If we prepare the window then window plus it is equal. You will put something here, okay then. Let's check if the window is not beautiful i.e. the window if the window is not beautiful i.e. the window if the window is not beautiful i.e. the window is there, see what I am doing in the window, in this question, what will we add in the window, this - this is ok, then I write - this is ok, then I write - this is ok, then I write here on the right of s dot, ok -3 is ok. here on the right of s dot, ok -3 is ok. here on the right of s dot, ok -3 is ok. And its absolute value i.e. Math dot And its absolute value i.e. Math dot And its absolute value i.e. Math dot abs is okay, so what is in the window at this time is one, A - B one is okay, then I can say, then one, A - B one is okay, then I can say, then one, A - B one is okay, then I can say, then I check whether this window created is satisfying my condition, okay. So, if the window is not to be done, if the window is greater, give the max cost, then I had made it beautiful here, now see again, let's see that I am in the middle of the story, what is the shape of the window, that I have already done this too. I have also done it, how will it happen, let me tell you once, see this loop will run, one reader has been given in the window, here I have given one reader, given on A-B, okay I have given one reader, given on A-B, okay I have given one reader, given on A-B, okay then I checked, see that it is greater than the max cost. What did you see, one is greater, give three, otherwise this will not work, okay, then we will go back to the top, what will Window do again on this same statement, plus B minus C, that is, now the value of window will be one, that is correct, okay, will check again. Is two greater than three? If not then again A will go back to this statement. Then it will add C - D to the Then it will add C - D to the Then it will add C - D to the window. Ok now what will we see? Again three &gt; 3 No. Again we will go back to A again three &gt; 3 No. Again we will go back to A again three &gt; 3 No. Again we will go back to A again in this statement. Window plus the - F means two means now it becomes - F means two means now it becomes - F means two means now it becomes five for the window. Now what will he do? What is five &gt; 3? Yes, what does it mean? five &gt; 3? Yes, what does it mean? five &gt; 3? Yes, what does it mean? The window is no longer beautiful. So what will we do? Look, we have completed it. It is okay with the help of right key, I know what to do in sliding window, right make capsule, destroy from left, from behind i.e. now we will give A from the window, it is behind i.e. now we will give A from the window, it is behind i.e. now we will give A from the window, it is okay and B will be window minus this. Equal, you will copy it to the left and here also we will keep destroying it from left to left until the window becomes good. Our caste is fine and left plus is good and what we will do every time, we will also update the answer. It is obvious that math.maxsimum Length Dot Max Previous Answer Comma Current Length math.maxsimum Length Dot Max Previous Answer Comma Current Length math.maxsimum Length Dot Max Previous Answer Comma Current Length How to find Right Minus Left Okay and the answer is right, I am taking -1 to the answer Okay, I took the answer to minus right, I am taking -1 to the answer Okay, I took the answer to minus right, I am taking -1 to the answer Okay, I took the answer to minus one because we are finding the max, let's run, accepted, submitted Let's try it brother, now what is its time less black city? It is the big one. You know, all the sliding windows are different and we have not taken any space. The big one is time complexity.
Get Equal Substrings Within Budget
maximum-nesting-depth-of-two-valid-parentheses-strings
You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters). Return _the maximum length of a substring of_ `s` _that can be changed to be the same as the corresponding substring of_ `t` _with a cost less than or equal to_ `maxCost`. If there is no substring from `s` that can be changed to its corresponding substring from `t`, return `0`. **Example 1:** **Input:** s = "abcd ", t = "bcdf ", maxCost = 3 **Output:** 3 **Explanation:** "abc " of s can change to "bcd ". That costs 3, so the maximum length is 3. **Example 2:** **Input:** s = "abcd ", t = "cdef ", maxCost = 3 **Output:** 1 **Explanation:** Each character in s costs 2 to change to character in t, so the maximum length is 1. **Example 3:** **Input:** s = "abcd ", t = "acde ", maxCost = 0 **Output:** 1 **Explanation:** You cannot make any change, so the maximum length is 1. **Constraints:** * `1 <= s.length <= 105` * `t.length == s.length` * `0 <= maxCost <= 106` * `s` and `t` consist of only lowercase English letters.
null
String,Stack
Medium
1737
347
Hello guys welcome back kids in english useful proven top frequent element problem write that system number three four 700 latest real problem statement in this problem give non-tariff barriers and give non-tariff barriers and give non-tariff barriers and win the most frequent element constraints very important this is always where is equal to two Questions for Number of Units Time Complexity and Width Body 10 Top Frequent Elements of Obscuritism Subscribe Top Most Frequently Asked Questions School in This Case The Fixed Elements One Has Been Repeated Three Times Two Has Been Repeated Two Times Entry Has Been Repeated One Time OK So Effigy of Moderate and Find the Top Most Frequent Elements in You Will See What One is the Most Frequent Element The Second Most Frequent Element S2 Need Only the Top Two Most Frequent Elements with Just One to Take an Example for Example Number Two Three One Two Three To talk to you can see all one to three do it is the meaning of the day in this problem will never be discussed records they have already mentioned at the top free content s always you will always love you to the number of units Unique Number Three Leg Race Two Elements And Two The Journey To The Third One Is Placid Between Dhone Hebbs Thursday Simple Solution How To Solve subscribe Video then subscribe to Billu Near So Even Vighn Can Be Used To Store Frequency Of Elements With Its Frequency Should Not Be Too Will Need A To End Tours And E Will Give Water Will Change Its Already Present In The Map Will Increase The Frequency Of All Elements And All Its Frequency Subscribe And No One Will Be Quote Element To Will Come After One Sharif Badal City Shopping Amazon Frequency You Can Even User Instituted Of Using Up And Will Also Work So After Starting You Can Just Stop Elements Like Subscribe Just One To You Can Just To Entertain You Are The Longest Born In Which Give Me the end of the time complexity of Buddha Vihar is tips university's ingredients in modern times for shopping author of long and subscribe maximum times and within two years setting on elements which will reduce the number of elements and possibilities and when skin problem it Possible to give the element can be stored in the form of an element and values ​​but its element and values ​​but its element and values ​​but its own frequency they can just for a structure ok fuel will be used once you have represented all elements in the form of node for multiple node to offer requests to Stop this process will be data structure to get top elements of elements when they subscribe then this property will always keep track of maximum elemental states root maximum will always be present at the event will be available on God and they can expect in order of long and Time When is the Number of Element Seervi Playlist So To-Do Solve This Problem Element Seervi Playlist So To-Do Solve This Problem Element Seervi Playlist So To-Do Solve This Problem Not To Top Spot Key Elements Is Option Key Elements Swapping Elements Will Get The Top And Don't See The Volume To The Number Subscribe My Channel Like This Is The Giver 123 Aadhaar Bina Right Side OK No One Chiffon In Singh 2818 Time Not Helping You Can Zoom Subscribe 12303 12-12-12 Just Zoom Subscribe 12303 12-12-12 Just Zoom Subscribe 12303 12-12-12 Just For This Element subscribe The Big Subscribe Top Element Ko Must Subscribe Playlist subscribe The Channel and subscribe the Mostly 9 News Room Report OK Elements Which Will Stop This Root Element OK Su Will Apply Extra Call To The First To The Value Of Notes In The Form Of You Can See The Time Of Elements Total Time Complexity Of Algorithm In Confusion Regarding Playlist Suna Do Ka Anand Ise Saare Jo Piya Aavan Restore Desh Ke Log And Right Some Wasted Time Complexity Yeh Singh Author Of Birds On The Next Flight Max's Times And Off's People Fan Total Time Complexity Will Be In Place And Plus People Android Know The Most cases of this creation can go to end 14 total time complexity can go again to log in the case will be very rare 110 complexity of years since we are using map of science and we also using this will take you can just try to reduce the First Woman Will Be There Will Be No Britain's Tenderly And Build And Hiphop Size So Let's Celebrate After Watching This Is A Map 90 Numbers Three Eyes Only Request Top subscribe The Video then subscribe to the Difference Subscribe All the way Unique Number Subscribe to And Forget About This Number 123 Number Also Unique 16 Secretary Dharambir and Five Elements and Frequency Value subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the same element which will give me one to three six pisces value ONLY IF IT'S 5V BOARD NOT HAVE ACCEPTED INTO 24 HOUR THREE ELEMENTS WITH RECORD 2367 FREQUENCY 230 EXPERT OK SO THIS ELEMENT WHICH CAN ONLY BE INSERTED INTO WHE IT'S FREQUENCY GREATER THAN AT LEAST ONE A LIMIT PRESENT IN THE PLACE FREQUENCY OF AND FREQUENCY OF 510 This is greater than at least one element so its greatest 230 gold will be setting this point to will be reduced to 100 traversing all the - k reduced to 100 traversing all the - k reduced to 100 traversing all the - k elements - elements in to the element will elements - elements in to the element will elements - elements in to the element will just - element will apply to just - element will apply to just - element will apply to quite as well as pop this is the Worst Case Scenario Might Not Be Required to Apply Post and Total Time Complexity and - K Lock Sliding Window Technique for and - K Lock Sliding Window Technique for and - K Lock Sliding Window Technique for the Time Complexity subscribe and subscribe the Channel and subscribe this Video Use This is the First Time Complexity and Subscribe and Like This People's Behavior People And Value You Will Find The Value Of Log In Values ​​Are Always Available Having A Good Time To Do With This Post With Facebook Log In Very Small But Very Much Better I Just Got An End Value Request Loot Se Z10 Not Right To Unlock K Add Key Login Which Will Give You Will Give Me The First Time Complexity And Will Not Storing The Video then Jhal Because When Will Be Creating A Node And Will Be Passing Buddha Unique Number S Well S Is Trick Vency Sonth Bill Gates And Year Basis Of Computer Function Which Will Be Used To Maintain The Property Of The Giver Numbers Value Channel To Subscribe To Our That New Year This Phone Dahi Updates Tattoo From Year Done The Third Step Is Top Order Top Elements From This Maximum And push that unique element which is the phone number of this is the answer will be written in the answer is on the top of the center code simple and comparison between the two and leave a comment if possible please do and channel the question is the video thanks
Top K Frequent Elements
top-k-frequent-elements
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\], k = 2 **Output:** \[1,2\] **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `k` is in the range `[1, the number of unique elements in the array]`. * It is **guaranteed** that the answer is **unique**. **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
null
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
Medium
192,215,451,659,692,1014,1919
94
today we're going to be going over the Java solution for lead code 94 binary tree and Order traversal given the root of a binary tree return the inorder traversal of its node's values so here we're just going to be given a binary tree and we're going to perform the inner traversal of it and add the values of the nodes into our list as and as we're going through it and then that's why we're returning so for example one right here we have this sort of binary tree and here we're gonna return the output which is going to be one three and two as like if we're going through the inner traversal of it that's what we would get I got another example here as well so with this binary tree specifically the way in order traversal works is that we're going to keep looking on to the left and then um after we've reached the end of all of it we're gonna add the that left Val that left uh route and then we're gonna add the root above it and now we're going to look for the right so for example um I'm gonna add our list of elements so this is what we would be outputting we have this one right here we are looking at it um we can see that we can go to the left so we're going to go to the left and now with this two we can also see that we can go to the left again so we're gonna go to this four and now with this four we can't go to the left so we're gonna add the four and then after that we're gonna try to see if we could go to the right we cannot so now we move back up to a two now we have to add the two since we've checked all of its left and now that we have the two right here we're going to look at to the right and we see the five now we're gonna look for the left of the five that doesn't exist so we now we add the five instead and now we're gonna look for the right of the five it doesn't exist so now we go back up to the one and now since we checked all of it's left of the one we're gonna now finally add that one and now we're gonna look for the right with this three right here we're gonna call on to its left we see there's a six we're gonna see um it's left and it's a null so now we go back and we add the six and now we're gonna look for its right there's nothing there so that means we could go back all the way up to the three and since we've checked all of the lefts of the three we can add the three and then we could look for the right of it that nothing exists so this would be our final um integer list that would we would be returning so hopefully that gave um that was a good explanation but basically for in order traversal there's two ways of approaching it we could either go for a recursive or an iterative solution with recursive Solutions it's usually easier to implement and then iterative solutions they are usually more efficient in general so we're going to be doing both of them um starting with the recursive solution so with the recursive solution we're going to have a helper method that we're going to recursively call to look for the left and um and then keep looking for the left and then right and then node and yeah so first we're gonna initialize our list so we're gonna have list integer I'll just call it list and that's going to equal to a new array list up list and now I'm going to call the helper and the helper is going to take in the root and the list and then after the helper has recursively called itself over and over we've added stuff to the list we can return the list at the very end so now let's actually go on and Implement our method our helper method so public void helper it's going to take in a tree node root and it's going to take in a list integers on this list so what do we do with the helper method well first we're going to see if root is not equal to null so this means the root does exist so we're going to check on its left so we're going to call helper um root dot left and uh we're also going to put in the list so we're going to check on all that's left and then if um the left isn't a null it's going to keep looking on the left and over until um we have a null on the left in which case we could go up and then the add um that element to our list so we can do list dot add uh root dot value and then after that we've added that we're gonna now look at to the right so we're going to do helper root dot right and then the list so let me see if it works if there's no complete come compiling errors oh great so it does work let me actually go on to explain how this would work so first we have the whole list and everything like that we've Gonna put in this root at the start we can see that it is not equal to null so then this helper is gonna Now call the left of that so we can see that's not null as well and we can go to the left so we're going to go to the left and it also sees it's not null so it's going to call even more to the left but in that one it does see its null so um going back to the four it's going to add the four and then it is going to look for the right and it doesn't see anything to the right so this whole iteration of the four is done so we move up to the two so now the two has called all of the lefts the whole left side is um basically finished so now we can add the two finally and then we could go look at the right and then we see the right it has a five it's going to call the left um and then it doesn't it has a null so then we add the five um with the list.ad and then we're gonna um with the list.ad and then we're gonna um with the list.ad and then we're gonna Rook to the right of it and we're not gonna find anything so then we go all the way back up now this whole two section is done since we have looked through the left we have add all the elements we have added the two and we've added all of the roots on the right as well so we go back to the one and here we have finally finished all of the left side of the one so now we could finally add the one and now we're gonna look for the right so now we're at the three is gonna look for the left of it and the season six if that's gonna look for the left of it's gonna be null so that helper is done for the six and now we can add the six now we're going to look for the right there's nothing there so now we're done the whole left side of the three so we could finally add the three to our list and then we're going to look to the right we don't see anything and after that we are basically done we have traversed through everything so that's how it works let's submit it and there we go so that was recursive solution um now I'm gonna go over the iterative solution so actually I'm gonna go back I do need I'm still gonna keep the list but with the iterative solution I will have a stack and stick I'll have a stack along with it and the stats actually going to be pre-node I'm just actually going to be pre-node I'm just actually going to be pre-node I'm just going to take in three notes so stack equals new stack and now also I am also going to keep track of my tree node current and that's going to equal um the root the current that root of it so now while um current is not equal to null or uh the stack isn't empty so dot stack is empty so it's not empty so while it's not empty and while the current isn't equal to null we're going to Loop through one more time so while current is not equal to null so here with this is that if we go back to the example right here what we have is that with this one we're gonna now look to the left of it we're going to actually add that we're going to do stack.push um current we're gonna push that current and now current is going to equal current dot left so now this current so what we did is that we pushed in the one to our stack and now our current um root right here is going to equal this left one right here and we see that still will trigger the while loop since the current isn't null so then we're going to push 2 to our stack and now we're gonna go down to the four and now we're gonna push the four to our stack then we're gonna go down and we say uh oh um the current value is null so what we can do is that after we break through this Loop we have a null value we can do uh current is going to eat current is going to equal stack dot pull and or stack.pop I meant or stack.pop I meant or stack.pop I meant stack.pop and what we can do is that we stack.pop and what we can do is that we stack.pop and what we can do is that we could add that to our list so current dot val and now current is going to equal dot right so here what we have is that we have looked through the um left of the four we see it's null so we go back now we're going to pop it so the last element we added was a four so we can pop that and then add that to our list and now we're gonna have current be the right one so it's going to trigger this while loop still it's going to see the right and that right is also null so um we're gonna go back and we're gonna pop the last element we added which we've already popped the four so the last element after that was the two so now we've added the two to our list and now that's gonna um call to the right here so now it's going to look at the five it's see it's not empty and now we're gonna push that onto the stack and now we're going to look to it's the left of that we see there is nothing in there it's null so we're gonna pop the last element we added which was the five and add that to our list and now we're going to call the right of it we see there's nothing there so now we're going to pop it again and the last element that was added so we've popped the four we've popped the two we've popped the five so the last element actually is all the way up here at the one so now you can see how like we would go look at the three and then the six and then eventually we would have everything there so when everything is done we can then return our list at the very end so now let's see if there's a compiling error okay nope no there isn't so now we could submit it and there we go so that was both the recursive and iterative solutions of binary tree in order to
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
98,144,145,173,230,272,285,758,799
70
hello and welcome today we're doing a question from lee code called climbing stairs it isn't easy let's get right into it you are climbing a staircase it takes n steps to reach the top each time you can either climb one or two steps in how many distinct ways can you climb to the top example one we want to reach step two and there are two ways to do that we either go step one and then another step from there so one plus one or we go straight from the ground floor right to step two and these are our two ways example two we wanna reach step three there are three ways to do that we go one plus one or we go to step one straight to three or we go to step two and then to three but we can actually notice something here right to get to step two we go from step one and then go another step or we go straight to two and these are being used here again right one plus one and two this is to get to two and then an additional step will bring us to three and this makes sense because it's not asking us how many steps does it take to reach the top it's asking how many distinct ways can we climb to the top so let's say i had n equaling five how many ways can i get to step number five well before that how many ways can i get to step zero to one two three four and then five if i am on step zero i'm on the ground floor there is there are zero steps needed to get to zero right so that means there is one way to get to zero there's just a step of zero that means there's one way to do it how many ways are there to get to step one i can only ever take one step or two that means i will have to do a step from ground to my current one because there's no negative there's no basement i can't take two steps this means that there will be a total of one way to get to one how many ways are there to get to two i can take a step of one or a step of two if i take a step of one i go from one and then to two and we know there's one way to get to one or i can go from zero to two and there's one way to do that as well so there are a total of two ways to get to two what about three how many ways can i get to step three well i already know i can only climb one or two steps so to get to three i can only come from one or from two if there is one way to get to one there is at least one way to get to three because i take two steps from one get to three if there are two ways to get to two an additional one to whatever those weights are would get us a three so all we have to do is add these two numbers together and that's how many ways we can get to three to visualize this a little bit better let's say to get to one i only need to take one step and that's going to be a step of one to get to step two i can either take the ground floor up to two so i just take two steps or i go from one and then an additional of one to get to two how many ways can i get to three i can either go from one all the ways to get to one plus an additional one step which will bring me to three or i take all the ways to get two sorry this should have been step of two to go from one to three and then from two it just takes an additional step of one to get to three so there are three ways to get to three how many ways are there to get to four all we have to do is add two plus three and we get five there are five ways to get there so for four if we go from step two all we have to do is add two to go from there to four and then if we go from three all we have to do is take an additional step to go from three to four that means there are one two three four five ways to get to four and same with five again all we have to do is take whatever index we are on the index before that and two before that add those together will equal the value at our current index so there are eight ways to get to step five and we can see that from here we know there are three ways to get to three two steps from three will get us to five and we can also get to five from four by taking one step from four so all we have to do is plus one and these are all distinct ways to do that so this is all we are doing this is going to be the logic for this in our list we are going to store all the distinct ways to get to a certain step where the steps are represented by the indices we know in the beginning the steps or let's call this ways this is going to store a list of all the ways we can get to a certain step so for index zero it's one for index one index two these are some things we know but anything three up until n we will have to loop through and calculate so for index in range three to n plus one because it's not inclusive and instead of calling this index let's call this step all we have to do is add two ways whatever is the step before us and the step two before us so ways of a step minus one plus ways of step minus two all we do is return step of n so how does this look like if we use the example we were using right here n equals five let's go line by line right ways is currently weighs currently one two now fourth step in range three two six let's loop through ways dot of pen so we start with three first step minus one step minus two so three minus one is two whatever is that index two and whatever is at index one so this is index zero one two so we add to that two ways so two plus one is three and this is index three now we go in this loop again and now we are in step four so four minus one is three four minus two is two what are the values of those indices we add them together and append that two ways so three plus two is five and we have that over here this is for step four now for step five you do the same thing what is that index four and what is that index three add those together we get eight and all we have to do is return step at n we return eight right here and you know if n was two we actually wouldn't even have to go in this for loop all we would do is return at index two zero one two we know there are two ways to do that so let's go ahead and run this code one time error this is not step this should be ways we return at the index for the list accepted and submit and accepted as well so for space and time complexity because we go through from 0 to n our time is going to be o of n and for space as well we store an entire list of ways ranging from 0 to n so this is also o of n for space but can we do better than o of n for time and better than o of n for space what do you notice here right this sequence right here one two three five eight does this ring a bell this is something called the fibonacci sequence all the fibonacci sequence is you take two numbers that were right before you so the number before you and two before you add them together to get your current number and that's exactly what this problem was right climbing stairs with the fibonacci sequence you probably heard of something called the golden ratio it's about 1.618 and if you ratio it's about 1.618 and if you ratio it's about 1.618 and if you multiply your current number by the golden ratio you get the next fibonacci number in that sequence and since there is a formula for that there is also a formula to find the end fibonacci number and i have that listed down below so if we plug in our n to this formula we will get the fibonacci number at that index and the real fibonacci number goes 0 1 2 3 5 8 13 so forth but the thing is it starts at zero here we start at one so we wanna instead at finding position and we want to find it at position n plus one we're just shifting everything down so if we plug in n plus one for this formula we can return the answer in o of one space and of one time because it's just an arithmetic expression that needs to be evaluated and if you want to look up this formula you can definitely look it up online but if we run this code it is accepted and if we submit it is also accepted as well and this solution is actually constant space and constant time so if you have any questions either with the solution or the one we did previously let me know down below otherwise i will see you next time
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236
116
hey everybody this is larry this is day 13 of the leeco day challenge hit the like button hit the subscribe button join me on discord and let me know what you think about today's form populating next right pointers in each note okay you give it a perfect binary tree that's something to notice i misread this at some point where all leaves are the same level and every parent has two child okay um okay assuming that it is perfect we should be able to do oh it's constant extra space i was going to say you can do something like a binaries oh extra space uh i was going to say something that you could do something like a breakfast search my first actually my first incarnation is death for search because i do every death research to be honest but i don't think that makes sense in this case having done variants ideally what you want from a recursive um solution is that every sub problem is a is solvable by itself in a self-contained way but in by itself in a self-contained way but in by itself in a self-contained way but in this case you have to kind of manipulate the left and the right together so i don't think that makes sense i think what i would do is some kind of bread first search in theory but in this case can i do some sort of level first search in extra space um so let's say we have a pointer at each level right can i construct the rest of the pointers in a straightforward way oh it is a perfect i forgot that it is a perfect binary tree so maybe there's some assumptions that we can make there with respect to some controversial but then i don't know how that could be not linear space even though maybe we do some kind of crazy recursive thing but hmm um i would also maybe use this time uh while i'm thinking about this as a disclaimer that i solve these farms live and this is me looking at it for the first time so sometimes it's gonna be a little bit slow before i get to the answer uh if that's not you know uh feel free to watch this on 2x until i get to that part or skip ahead or watch other videos if you like i wouldn't feel that bad about it i just want to give y'all a reasonable expectation because sometimes people do it this way uh and to be honest um this is uh this is a little bit of a weak point in my interviewing problem solving i guess because the constraint is that we have extra constant space which is something that doesn't come up that much in competitive programming because you always have a lot of space at least a lot more than constant and so for me i have to think about this a little bit because it is a different problem type and i would also say that um yeah these kind of problems and linked list problems are some of my weaker prompt types for that reason but and there are really linkery stuff to it uh so we want to set next so we can go one at a time hmm i don't know but i'm thinking something like um okay i think i get it i think what i would need to do is uh look at each do essentially a level first search where you have a point on a previous level and a point on this level and then uh the point on the previous level will just kind of be um the pointer to the previous notes and because you've already done the previous level then you can just move that to the right while kind of pointing okay i think i get that idea uh implementation may be a little bit tricky uh so bear with me um so i will explain this idea after i write the code i think this is easier to illustrate with code so you know stay tuned yet if you like but the idea is that um actually i'm gonna let me pull up my paintbrush so that i can visualize this a little bit better okay so say you have something like this right so what i want to do is okay at some point is okay actually i don't need to draw those circles individually i could just do this right that's a terrible circle but in any case so you have something like this let's say we already did the first level and now we're on the second level so this is our previous level pointer and then we start out our current level pointer uh and because the previous level we have already done so we already have this pointer that goes this way and so on the top pointer we're going to go to the left and the right or we connect the left to the right and then just keep on um shifting the top point of from left to right while connecting to the bottom pointer uh um next pointer as well so that's kind of the strategy i'm gonna do um yeah let me take a look at that uh okay and now this is the coding time so let's figure it out and i'm getting message so i have to figure out how to turn that off um okay so let's just say uh the previous level pointer current level pointer so those are the two things we need i like to kind of save things out so my code is not as like it's not just me typing it in it's me typing it in the order that my mind ranks hopefully that's helpful because for me this problem for me is not a cell problem but for some problems i already know exactly how and what i want to do so you just see me kind of type it in really quickly but this is not one of those problems so previous pointer will be let's just start at the root we don't need to do the root because the root dot next is none right so this is equal to root that left so we start at it here and then now while current level pointer is not none we look at the previous pointer so okay if current level pointer i'm trying to think about how to do this precisely because i think there are two edge cases that i have in my head so if this dot next well it is going to be equal to none so first of all um in the beginning of every loop the first pointer is going to be and i'm missing a while loop so this may be a little bit awkward uh and i'll put it in a second but the first point is going to be me the current level pointer is going to be the left pointer and we want it to point to the right so we do something like this um next is equal to previous level pointer dot right okay and then yeah so now while previous level pointer is not none we do at least one step of this and then now we want to get to the invariant at the end of this loop which is that now um well first move the current pointer to the next so current level pointer is equal to current level 0.2.next and then now level 0.2.next and then now level 0.2.next and then now we want to move the top pointer the previous level pointer to the next so previous level pointer is equal to previous level 0.2.nex 0.2.nex 0.2.nex and then now we want the current level pointer to be looking at the new left so um if no that's okay i was going to say i think we have to make sure that this is not done so if previous level pointer is not none current level pointer.next is equal to current level pointer.next is equal to current level pointer.next is equal to previous level pointer.left and then current level pointer is equal to current level pointer dot next because then now we just move the bottom point all right and then now the so what you know you probably hear the term loop in variant a lot and this is what the lupine variant is right is that at the end of each loop the preconditions is still true which is that the previous pointer is at any point i guess and then the next level pointer is on the left of that previous pointer and in this case this will always be true and you know you could prove to yourself why this is true uh by stepping through it but yeah i think this is good for this one so now just end the level what happens at the next level well at the next level we have to start at the next level obviously and then the current level point at next right so because we're already at the end of the pointer so that means that we just have to keep track of one more thing which is that okay um so previous level pointer head maybe uh so this is the beginning of that pointer is your previous level pointer and then now at the end of these loops we want to move them down one so what that means in code is that previous level pointer is equal to previous level pointer head it's left right and this is always going to be not none by the invariant that this is not none and then current level pointer is equal to previous level pointer this is a new level pointer dot left and this could be none but that's what the while loop does for us and that's pretty much it there's no return statement right because we just manipulate this uh let's see i don't actually know the format that the problem was so let's run this and see if that gives us the right answer uh no we have to return it what are we supposed to return maybe just a root okay let's return the route then it's not very clear okay cool so this looks okay i think it's uh let's try another case is this okay nope missing a note and also let's say no elements and one element to the elements oh see there we go um oh yeah if boot is none and i don't know if it's in the test case but it i feel like i've been bitten by something similar recently where i'm just making assumes and you know what they say about assumptions cool uh so what is the running time of this algorithm to go over it so it's linear time because we look at each pointer or with each node a constant amount of time in this case i think two or three times if you want to count it exactly and in terms of space we only have three pointers i think you have a pointer here and you have a pointer here so it's going to be constant space uh it's a very tricky problem especially for me because it's new to me let me know what you think let me know if you have any questions and how did you solve it maybe there's another way to solve it to be honest i don't know um yeah let me know uh hit the like button in the subscribe button and i will see y'all the next day bye
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. Initially, all next pointers are set to `NULL`. **Example 1:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[1,#,2,3,#,4,5,6,7,#\] **Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 212 - 1]`. * `-1000 <= Node.val <= 1000` **Follow-up:** * You may only use constant extra space. * The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
null
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
117,199
204
hello everyone in this video we are going to solve the lead code question number 204 count primes given an integer n return the number of prime numbers that are strictly less than n the prime numbers which are less than 10 are 2 3 5 and 7 so the output should be 4 in the second example n is zero so the output should be zero in the third example n is 1 so there are no prime numbers less than one so the output should be zero I hope the question is clear now let's get into the implementation a number is a prime number if it is divisible by one and by itself in this diagram the numbers marked in blue are prime numbers for example 5 is divisible by 5 and by one so five is a prime number whereas 6 is not a prime number because it is divisible by 1 2 3 and 6 we are going to solve this problem using C of aristois algorithm in this example we are going to take the number as 20 initially we are declaring a list of size 20 and we are assuming all the numbers are prime so we are marking true for all the numbers in the next step we know that 0 and 1 are not prime so for the index position 0 and 1 we are changing it to false now from the index position two if the value is true we are considering two as Prime and we are marking all the multiples of two as not prime now we are moving to the next element which is three and we are checking if the value is true so three is a prime number now we are changing all the multiples of three as not prime so in this case six 9 12 15 and 18 are not prime now we are moving to the next element which is four and we see that the value is already marked as false the next now the next element which has true is five we see that multiples of five which is 10 15 are already marked as false so we are stopping the iteration at four in this example the square root of 4 is 16 Which is less than 20 whereas for the next element five the square root of 5 is 25 which is greater than our number 20 so we can stop the iteration at 4 which has the square root less than 20 I hope the approach is clear here now let's get into the implementation first we are going to declare the array and Mark all the values as true array equals to a list of value true of size n if the number is zero or 1 we can immediately return n if n = to 0 or if n = to 0 or if n = to 0 or n equals to 1 we can return Zer if not we can mark the array of index 0 and 1 as false array of Zer comma array of 1 equals to false now we are iterating from the index position two to the number which has the square root of n let's do that for I in range of second index to integer of number square root of 0.5 we are going to iterate through this 0.5 we are going to iterate through this 0.5 we are going to iterate through this last element so I'm going to add + one last element so I'm going to add + one last element so I'm going to add + one if array of I is true we are going to change all the multiples of that number to false let's do that for J in range of I + I of I + I of I + I and we are incrementing every I and we are marking array of J equals to false now we are returning the sum of array return sum of array let's submit it the solution got accepted I hope you like this coach I will see you in the next video thank you
Count Primes
count-primes
Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`. **Example 1:** **Input:** n = 10 **Output:** 4 **Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7. **Example 2:** **Input:** n = 0 **Output:** 0 **Example 3:** **Input:** n = 1 **Output:** 0 **Constraints:** * `0 <= n <= 5 * 106`
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors: 2 × 6 = 12 3 × 4 = 12 4 × 3 = 12 6 × 2 = 12 As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n. Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach? public int countPrimes(int n) { int count = 0; for (int i = 1; i < n; i++) { if (isPrime(i)) count++; } return count; } private boolean isPrime(int num) { if (num <= 1) return false; // Loop's ending condition is i * i <= num instead of i <= sqrt(num) // to avoid repeatedly calling an expensive function sqrt(). for (int i = 2; i * i <= num; i++) { if (num % i == 0) return false; } return true; } The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple. Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0. We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime. The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia. public int countPrimes(int n) { boolean[] isPrime = new boolean[n]; for (int i = 2; i < n; i++) { isPrime[i] = true; } // Loop's ending condition is i * i < n instead of i < sqrt(n) // to avoid repeatedly calling an expensive function sqrt(). for (int i = 2; i * i < n; i++) { if (!isPrime[i]) continue; for (int j = i * i; j < n; j += i) { isPrime[j] = false; } } int count = 0; for (int i = 2; i < n; i++) { if (isPrime[i]) count++; } return count; }
Array,Math,Enumeration,Number Theory
Medium
263,264,279
98
hello everyone welcome to pseudocoder my name is raveena and today we are going to solve problem number 98 that is validate binary search tree so let's start by reading the problem statement it says that given the root of the binary tree determine if it's a valid binary search tree a weld binary search tree is defined as follows the left subtree of the node contains only nodes with keys less than the nodes key the right subtree of the node contains only nodes with keys greater than the nodes key both the left and the right subtrees must also be binary search trees so what does it mean let's go to a notepad now let's take an example so first of all what is a binary search tree is the tree where you know your node is for example here I have five all the nodes on the left of your tree so all the branches that go on the left side will be less so it can be either 4 3 2 1 0 minus 1 whatever all the nodes to the right of the root so considering this is the root all the nodes to the right of the node root will be greater so it will be say 8. okay so this is what a binary valid binary search tree is and it also means that um all of its branches so four can also have two branches left and right and those should also follow the same rules and we have to do to get away from the given binary tree whether if it's a valid binary tree or not so let's see how we will be able to solve this we are going to make use of upper bound limits and lower bound limits to solve this question so the first thing that we have to do is we have to Define upper bounds and lower bounds for our root so for us to start with the lower bound is going to be minus infinity and the upper bound is going to be plus infinity what does it mean is that 5 should always be greater than my lower bound which is minus infinity and 5 at the same time should be less than my upper bound which is plus infinity so since we have that determined now we are going to explore our tree so to explore our tree we have five we are going to explore the left hand side first so when we go to the left hand side what's gonna happen whenever we are exploring the left part the left node of particular root node that means that it has to be smaller than what is there than my root node is that right remember all the nodes to the left of the binary tree are less than the node since we are going left we are going to change our upper Bound for this particular Node 1 the upper bound is going to be now 5 because it is coming all from root 5. and what about the lower bound stays the same no one touches the lower bound so my lower bound stays minus infinity now we do the check is 1 greater than minus infinity yes it is 1 less than 5 yes it is okay that checks out so it will return true now we will explore the right hand side of the tree so when we go on the right hand side of the tree that means that the note that we are exploring should be actually greater than my root node is that right so since it has to be greater than your root node that means your lower bound is going to change so if I am going to the right my lower bound changes to 5 and my upper bound actually stays the same now I check is my 4 actually greater than my five no it's not so we actually found something here which is the arrow and then we are gonna return false and this means that this is not actually a valid binary tree now let's take a example take a look at the example where it's is a binary tree so for example you can see this 1 2 and 3. we are going to start by two limits which is plus and minus infinity we explore the left hand side since we are going on the left we are exploring the left part of the tree that means my upper bound changes so my upper bound actually becomes my root which is 2. and then my lower bound stays minus infinity I check is my 1 greater than minus infinity yes it is okay is my 1 less than my 2 yes it is okay so it returns true now it explores the right inside of the binary tree since we are exploring the right hand side of the binary tree my left limit should change because I am so this lower bound becomes 2 and my upper bound stays the same which is plus infinity then I check is 3 greater than 2 yes it is okay is 3 less than minus infinity yes it is so it passes and it returns true so this means that this is actually a valid binary tree so let's see how we can convert this into code I'm gonna write a new method to validate if that is going to be a binary tree or not so I'll do this I'll check is valid tree let me do is valid binary tree and then I'm gonna pass it my root my left bound and then my right bound the first thing I'm going to check is I'm gonna check if my root is not null if my root is null then it's a valid binary tree so that means I have reached the end of the root there is nothing in it and I did not see any false coming any false from any of the nodes that means I have successfully traversed the whole tree and there are no um there is no incorrect number in there so that means that if I get null root that means it's a binary tree so I'll return true the next condition I want to do is I'll check if my root dot value is less than equal to my left node or my root dot value is greater than equal to my right node that's what we were doing when we took our left and right we were just comparing it with the root node and that's what's going to happen if that if any of these are true then we just return false that means that there is a glitch in the binary tree and we just written false lastly we are going to call we are going to do a recursive call to the same method is valid binary tree and then for the first part what did we do if we are going left uh we changed the right limit so since we are going left the root will become root dot left so that becomes root dot left and then since we are going left the left limit stays the same but the right changes what is going to be the right is going to be the current root value and I'm gonna call it again for my right note right so it's gonna be rooted right if you are going to the right your right stays the same and your left limit changes so my left limit is going to be actually my root and then I'm gonna pass in my right limit in the end what I have to do I just have to call my binary search tree method so I'm gonna call it I'm gonna pass in root I'm gonna pass my left node initially as minus infinity so that's going to be minus INF and then my right node right limit is gonna be plus infinity so I'm just gonna pass plus infinity so let's see if we can run it okay I think I did something oh is it a float I just wrote a float so let me run it again okay submit so as you see this solution is accepted now let's talk about the space and time complexity of this problem uh the time complexity of this problem is actually o of n since we are going through each and every node once it is O of N and about the space complexity it's taking o of n time and we are keeping all the nodes in memory when we are doing this recursive call and so the space complexity of this algorithm is also going to be off I hope this explanation was helpful if you like my videos give it a thumbs up and comment below you can also subscribe to it so that you'll be able to see any new videos coming up the code for this is going to be on my GitHub repository and the link I'll share in the description below if you don't know how to calculate space or time complexity I have already a video on that I'll include the link of that in the description and also I have a video on depth first search and breadth first search if you have a prop if you don't know how to Traverse through the binary search tree or you don't know how to get started so you can have a look at that video as well thank you so much for watching and I will see you next time
Validate Binary Search Tree
validate-binary-search-tree
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_. A **valid BST** is defined as follows: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[2,1,3\] **Output:** true **Example 2:** **Input:** root = \[5,1,4,null,null,3,6\] **Output:** false **Explanation:** The root node's value is 5 but its right child's value is 4. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,501
1,653
hey everybody this is larry this is me going over to two of the bi-weekly contest 39 two of the bi-weekly contest 39 two of the bi-weekly contest 39 uh minimum deletion to make string balance so this one is a little bit tricky to unders to i mean the understanding is not that hard uh and i actually can clean up the code a little bit but and this code is really short it's one of those things that kind of tricked you into under thinking that is easy it's actually a little bit trickier than that the key thing to note is so um so for this problem the first thing to notice is that n is equal to 10 to the fifth so you cannot do anything before i mean you can't do anything n squared at least you can maybe do n you can definitely do n log n but that's not good um my solution is gonna be linear time o n so basically you have some string here right and we the idea is that we split we brew force in a way in a clever way just every possibility of splitting the string and what i what do i mean by splitting the string i mean splitting the string such that everything to that left of the split are going to be a's and everything to the right is going to be b's so that's basically what i do i have just i start from all the way to the left and then order one to the right and so forth right so from that the thing to kind of keep track of are the invariants right so the thing to notice is that as you kind of move this pointer from left to right and i'm going to just be a little bit exhaustive here is that okay as you go from left to right well if the character that you're changing if it's an a then there's one fuel ace to the right and nothing changes to the left because you want an a anyway if the character you shift is a b in this case well that means that there's one more beef to the left and one less b to the right so that's kind of obvious so you can actually keep track of it if you want to write this more naively uh and i probably should have during the contest because i was thinking too much uh so what you can do is actually keep track of four things which is a left uh b left which is zero and then a right b right which is well you know we have just this collection thing so let's just say total sub a total sub b right and my code is going to be exactly the same and then now you we just do the minimum by first we look at it from scratch um or actually so at the beginning what is the worst answer right it's actually just the number of a's in on the right side so this is going to be a sub right and then now we've every string we pause uh well we take a look at the best and then we it is basically the number of b's on the left side plus the number of a's on the right side right so it'll be something like this right and then if x is equal to a we do what we said right which is that a to the right we subtract one and then we moved it to the left side we don't use this so that's why i took it out and if it's a b then we again do the same thing we just move b from left to or from right to left right and then at the very end we just wanted to make sure that we keep track of the last possibility which is um oops which is this right so now we just keep track of min of best one more time just to make sure after we process the entire string so that's pretty much it i voted during the contest in this way so that it's um i wouldn't encounter in this way because i was able to kind of skip some steps and visualize it but to be honest it took me a long time uh longer time because i had to make sure that i was right and it was kind of a little bit you know you don't have that symmetry of code though this is you know shorter code and prettier uh i think this code is actually oh well we have to return best but this code is uh easier to read in terms of understanding how to understand this problem uh let me know how what do you think um hit the like button hit the subscribe button drop me a discord all that stuff and you could watch me solve it live during the contest now you hmm you i don't think that's fine you that is um hey uh thanks for watching uh hit the like button hit the subscribe button join me on discord let me know if you have any more questions about this problem or another problem uh i will see y'all next problem bye
Minimum Deletions to Make String Balanced
number-of-good-leaf-nodes-pairs
You are given a string `s` consisting only of characters `'a'` and `'b'`​​​​. You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`. Return _the **minimum** number of deletions needed to make_ `s` _**balanced**_. **Example 1:** **Input:** s = "aababbab " **Output:** 2 **Explanation:** You can either: Delete the characters at 0-indexed positions 2 and 6 ( "aababbab " -> "aaabbb "), or Delete the characters at 0-indexed positions 3 and 6 ( "aababbab " -> "aabbbb "). **Example 2:** **Input:** s = "bbaaaaabb " **Output:** 2 **Explanation:** The only solution is to delete the first two characters. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is `'a'` or `'b'`​​.
Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2.
Tree,Depth-First Search,Binary Tree
Medium
null
1,840
hello everyone let's take a look at this lego problem maximum building height it's the last question in the weekly context and it's a hard problem let's take a look like how to solve this problem the problem is like the description is pretty long so if you haven't read the description you can read it basically like we want to build a new buildings in a city the new buildings will be built in a line and a label from one to one like there are some rules for example the height of each building must be a non-negative each building must be a non-negative each building must be a non-negative integer the height of the first building must be zero and the height difference between any two adjacent buildings cannot exceed one additionally there are city restrictions on the maximum height of specific buildings these restrictions are given as a two-dimensional integer with two-dimensional integer with two-dimensional integer with restrictions where restriction is and idn maximum height indicates that building id must have a height less than or equal to maximum height it's guaranteed that each building will appear at most once in restrictions and building one will not be in restrictions so we need to return the maximum possible height of the tallest building for example like n is 10 so we need to build 10 new buildings and we know the first building is zero like the height is zero and we have these restrictions for example uh for the building 10 the maximum height is three so if we don't have these restrictions we know the building type can be taller okay so our task is to like find the tallest building given these risk restrictions okay so the first questions um coming to our mind is can we get the like higher highest building i think those restrictions point for example in point five to seven ten can i know like what's the highest building in this um position okay let's take a look at one simple example if we only have one restriction to one we know um the height of two must be like at most one right so the height of two is uh is one that the tallest billions the highest building at point two is one like what if we have another restriction ni what's the highest building that can we put in point eight like we know it's seven since nine is useless here two is one then three is two point four is three so point eight is seven okay now let's change the restrictions from nine to two and let's add another restriction six eleven so the question is what's the highest building can we build on six is it 11 of course not let's take a look at the left name a neighbor of 6 2 is 1 so 3 is 2 which means like for 6 it should be 5 right is it five no let's take a look at the right knee table which is eight h is two so we know in seven three is tallest so in six four is tallest so it will become four so to determine the tallest building on a restriction point we need to take a look at left point and take a look at the red points so we can build code like this to make our coding easier we push 1 0 and -1 to our restrictions 1 0 and -1 to our restrictions 1 0 and -1 to our restrictions and then we just sort them since these points are not sorted unsorted at first so we have this first for loop so we just iterate from left to right to update our restrictions like based on the previous restriction then we iterate from right to left so we get a maximum height of like building six okay after this for loop we get the like highest for each restriction point now we just need to for loop like each of them to get the highest building that between these restriction points okay for example we have a restriction point x and y and for their highest building c which is four so what's the highest building can we build between x and y it's very simple the answer is 4 plus y minus x divided by 2. since we need to let go up then go down okay what if the height is not same it's also very simple since for x we can just go one step further to make it like we have x plus one four then we can use the previous algorithm highest is four plus uh y minus like x minus 1 then divided by 2. okay so we have a result that for each iteration we just calculate the highest building between these two like restriction points then we update our results finally we just return this result okay so as time complexity is very obvious since we have a sort here so if n is uh so if um as a k is a size of restrictions then our algorithm uh time complexity is like k log k okay that's it thanks so much
Maximum Building Height
minimize-hamming-distance-after-swap-operations
You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`. However, there are city restrictions on the heights of the new buildings: * The height of each building must be a non-negative integer. * The height of the first building **must** be `0`. * The height difference between any two adjacent buildings **cannot exceed** `1`. Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`. It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`. Return _the **maximum possible height** of the **tallest** building_. **Example 1:** **Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\] **Output:** 2 **Explanation:** The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2. **Example 2:** **Input:** n = 6, restrictions = \[\] **Output:** 5 **Explanation:** The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5. **Example 3:** **Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\] **Output:** 5 **Explanation:** The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5. **Constraints:** * `2 <= n <= 109` * `0 <= restrictions.length <= min(n - 1, 105)` * `2 <= idi <= n` * `idi` is **unique**. * `0 <= maxHeighti <= 109`
The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.
Array,Depth-First Search,Union Find
Medium
1308
825
hey everybody this is Larry this is March 8th of the Leo day challenge hit the like button hit the subscri oh I mean it's not the daily challenge but it's the extra PR that I'm doing so hit the like button hit the Subscribe button join me on Discord let me know what you think about this one uh RNG take me to a good problem and today we have a25 friends of appropriate ages a lot of downloads I don't know why that is but uh but it is a medium problem so let's get to it hope you having a good day here I'm excited uh the red is a little bit nice I um maybe you could tell from my voice or just my excitement I have a lot more energy than I did a couple of days ago with the fast so uh yeah we'll see how that goes all right there are end persons so okay there are n people on a social media website you're giv an integer away ages where ages surv the age of the eye person a person X will not send a friend request to a person y if any of what is this okay AG sub y is okay some formulas otherwise X will send a friend request to y not that X sends a friend request to y will not necessarily send a request to X also a person will not send a friend request to themselves okay fair enough uh return to no total number of friend request made all right the first thing I wanted to do is check n okay just to make sure that n cannot be um what's it you know if we could do n Square we'll do n Square um so yeah I don't know why which X will send to Y okay will not okay I mean we have to pause this but a lot of these are just relative things right and each of these we can binary search so it should be pretty straightforward to be honest uh in terms of idea I mean sometimes code is easy to mess up and stuff like this but yeah uh so because we want to find a we want to create a structure from the input the first thing we're going to do is sorting and we already kind of have that idea of binary search so we should sort it anyway right and then now um uh these formulas are like very weird so let's kind of paste it here and then rewrite them in um in a way that we want to get I don't know I just like so we want to send X from X to Y so that means that okay so if this is X um this is y right uh I don't know why they so X will not send to Y will not if any of these are true okay which is very weird to be honest the way that they phrase it I mean the problem okay so I mean yeah so we can if x is so we can rewrite these as um I don't know just thinking about it right uh so let's actually rewrite this one a little bit right because we have X I mean you can also do it two ways you I guess you can I mean the way that I was thinking is that for every X how many request do does person X sent you can also do it the other way where for every y how many person that uh how many requests does person why get right so you could it's in this problem the end will be symmetric to how you solve that um because it's just number friend request made as long as you're consistent right but I really kind of went up this way so yeah we'll do it minus 7 and then maybe I should have done it the other way just so I don't have to uh yeah and then it's dived by 0.5 I guess yeah and then it's dived by 0.5 I guess yeah and then it's dived by 0.5 I guess that's easier actually by 05 is times two right what is this like that weird um like dating age thing did I make that up is it like a plus 7id by two or something like oh yeah what the what is this problem this so weird Okay in any case uh all right anyway uh there's a lot of things about this problem anyway total z then for I in range of n so we want to find so that means so this is will not right um okay so this one is you know easier in a way because now we can bound that right this is just weird or like so what I'm oh sorry uh yeah I'm just kind of like a little bit not weird but just like it's a weird way to put it because um and I'll explain in a sec which is that basically this one and this one kind of overlaps right like we should not have to wor or care about this one because this one would already be through right because you have this you know and you can kind of just right like so we don't have to worry about this one at all that's why I was like a little bit like huh right and then okay and then now maybe I do I made a mistake in kind of doing it this way but uh oops right I'm just writing it this way um this is definitely a little bit awkward okay right fine I'll just write this way so something like this right so it's the formula that we're looking at um the AG of Y part I mean that's pretty straightforward so then we just have to binary search for this part which is um yeah I me we just have to binary search for this part and I know that I reot it in a weird way but that is just of course you go to this part so we can actually just do that right um and where so then now uh and I was going to I thought we have to do like a you know two binary search to be honest to get a range but here we don't even have to because it's strictly smaller than and you have to Upper bound being oh no this is the lower bound right because basically when this happens we don't send it so I kind of wrote this in a funky way I think because it should instead of an it should be an or so it's either this or this we don't set so then we kind of like need a uh um and this one we can you know it's easy to kind of do the logic on but this one it means that we want something that's at least this number or bigger right because if it's yeah because if age of Y is too low we don't send it yeah okay I that's not that bad I mean okay so we do have to do the two things kind of um but should be okay um we have to care about the EOS sign so we have to do okay so uh let's just say smaller is you go to a of I um the do by 2 is a little bit awkward that's why I'm like thinking if I should handle it in a good way but I guess it doesn't really matter we can use uh fractions uh for this one just because it shouldn't matter for this one that's not true uh maybe I should just okay I mean things get uh things do get weird but divided by two is actually the one case where fractions are fine or like doubles are fine because basically when you deop things by two um you know you have a binary number in folding points and doubles notation you do not have rounding errors because it is not a repeating number it is a whole number in fractions in binary right I don't know if that makes sense but uh but I'm sticking to it all right so then now we have ages we have something like B that b so we want something that's strictly greater than this so we want to B ages by smaller right so index left is you're going to be go this because that's and then index right um so you basically just get what Index this is but the thing that we have to do a second binary search on is because um because you can have tide right like if two people at the same age like this one I think it would get it wrong for if you just kind of look at previous people you can because um there may be a you know cuz X may send a message to Y and Y may send SE tox so you have to be careful about it but yeah so then BCT right of Ages of agis of I and then this is going to be the insertion part I think so yeah so then now total Index right minus index left and I think that's fine um inside of that we have to maybe minus one for itself but I think we add one to include the other numbers or I don't know something like this but yeah so that's why I'm going to give it a spin and then just double check uh I'll buy a lot actually uh let's see this should go from zero to two that's fine yeah um so I guess here we zero is the insertion point two is not the index so then minus one and then you plus one to include it but then you minus one for itself okay I think this is more right but uh but oh actually I guess that was it I thought I had to do an extra thing that's why I want to be careful of this one first um yeah and we don't have to care about the other one because it's just yeah I mean it's overse superseded by this one so I don't know let's give a submit Maybe miss a case maybe oh I did miss a case huh I hope I didn't just I don't know what I hope to be honest but uh all right let's see I um I mean the idea should be right unless I misread some stuff which is very easy to do to be frank uh okay five we don't send anyone okay that's fair 24 we don't send it to anyone no we send to one person and that is five that doesn't seem right do I oh when this is zero it's still okay fine I see I kind I thought that hm why would this return oh no one is fine what is smaller is 5 2. oh because the seven I expected index left to be strictly um less than Index right because of this um but ah I did miss that H minus because this number for Five is 9.5 so then that's why you have Five is 9.5 so then that's why you have Five is 9.5 so then that's why you have this thing okay wow that is a sloppy case I mean me handling the or not handling I guess it's a sloppy handling of that case all right okay so the idea is right but I huh I mean it is what it is um but yeah as you can see this is going to be n log n the Loop is all of n two binary um searches inside the loop so log n each um oh and log in and there we have it um I think you can do a little bit better maybe if you really want to kind of upserve this uh because basically it's kind of like binary search but it takes advantage of this dird constraint that I kind of thought about but I didn't want to get I don't know if this is kind of cool or not but uh so if you know really if you want to pause the video and try to figure out this other way yourself you can do that uh but yeah but basically the other way and I am not going to do it cuz I'm lazy but uh maybe is pretty straightforward but it's the same idea it's just you know instead of using binary search you can use a prefix sum array to hand to kind of count the number of things in each age and because you only have 120 ages um you know it's just one iteration of 120 and then there you know this will be linear time here plus over of a or whatever where a is the um you know the ban of Ages for ex um and you know that's fine too I think that's not that bad and if you didn't do it that way you know maybe you can uh now that you know the answer it's still worth it to implement yourself from the idea even I'm not going to show you the code for it uh but yeah that's all I have for this one let me know what you think and yeah stay good stay healthy to a mental health have a great weekend everybody I'll see you all later and take care byebye
Friends Of Appropriate Ages
max-increase-to-keep-city-skyline
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
Array,Greedy,Matrix
Medium
null
295
so let's do this question find medium from data stream as you probably would know the median is the middle value in an ordered into your list but for this question we're not given an integer list we're given just an add num function so how do we find the median if we're only given add num well the input is a bunch of calls to these functions and at any point they will they could call find median given the numbers they've given us so far so i guess you could just keep track of a uh a set or something and as whenever they call adnam add to the set but there could be duplicates so you could maybe use a multiset or just a vector if use a multiset you could add it in and multisets already sorted for you so when you go find the median you just get the size and find the middle one iterate through until you find the middle and you can't find it in constant time because it's uh implemented as a tree the alternative is if you use a vector and every time you add a num you add to the vector and then you sort the vector which is n log n for a single add num and the other one was just n for the fine median let's see there are at most five times 10 to power four calls to add number and find median so that's not good because we that would mean we have a n squared at least n squared for those approaches we need to find a faster approach and one way is to keep track of two sets um so give you keep track of the median and then you keep track and whenever you add a number uh you either update the median to be the value before or after that can't be done with one set because if you add a number to a set or something like that we can't compare values uh can i compare the positions of the iterators in this set i know definitely that the value of one iterator is less than the value of the other iterator that only works for contiguous arrays so we need to keep check two sets two multisets where the left set contains all the elements less than or equal to the median and the right set and the right multiset should be everything greater than the median so for example if we have a 2 3 4 here we add say 3 here in this case this is okay there's an odd number of elements and so the median in this case is going to be the greatest element of the left multiset and that's fine if we add the two now so we see that the two is less than the median or less than the greatest element less than or equal to the greatest element of the left multiset then we add it to the left side we see that the two arrays are unbalanced because the median is 2 plus 3 divided by 2 so 2.5 we actually want the three to be in here not there so we can do a shift to achieve that so whenever we whenever it's odd basically when whenever we have an odd number of elements and we insert to the left side we need to shift to the right but what if we inserted the 4 first now what if we inserted 2 and then inserted three and then we inserted four so if it's even and then we insert a number to the right set that will cause it to be uneven so we need to shift to the left causing it to look like this and that's the general idea so we can try and implement that i've already defined a multiset left and right here when we add a number um we also have to take care of the fact that if there are no elements in the set there is no median to compare with so could you say if the left the empty if it's empty then add it to the left set or if the number is less than the greatest element of the left's end the left n is the one beyond the end uh one beyond the last element so wait to say decrement that then we can insert to the left set that now the case was because we're inserting to the left only when it's odd size of the left side is greater than the right set so it's doing this would cause it to be uneven so if it's odd now let's keep track of the number of elements here so left dot size let's write the size if n moles just 2 is equal to 1 then we need to shift to the right shifting to the right so let's grab the greatest element of the left like that no need to brackets actually and then we could uh the insert it to the right before we delete it so right don't insert the value start it and then erase it from the left cool in the case where we insert it to the right we want to shift to the left only if the number of elements is even so right.insert right.insert right.insert number like for example if we have three um you have three two three i mean instead of four you definitely need to shift to the left by doing but inserting a three here and then erasing it from this one so that's it and mod just two because zero and grab the smallest element of the right set do the left dot insert value and right dot erase that okay now the median would just be if it's odd the greatest handle on the left set otherwise if it's even it'll be the average of greatest element of the left set and the least element of the right set so if okay we're going to calculate the number of elements if n modulus 2 is equal to 1 so if it's odd then just return left dot and minus and let's also dereference it and because returning a double is casted to a double else return this costs uh this basically this whole thing again plus um double of star of rights begin and divide the whole thing by 2. see if that works this should be just equals okay oh this should be begin there we go yeah it should be begin because we need the least element of the right set not there that is very slow um i'll try and prove it next time but hey that's the basic idea of how to do it
Find Median from Data Stream
find-median-from-data-stream
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. * For example, for `arr = [2,3,4]`, the median is `3`. * For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`. Implement the MedianFinder class: * `MedianFinder()` initializes the `MedianFinder` object. * `void addNum(int num)` adds the integer `num` from the data stream to the data structure. * `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input** \[ "MedianFinder ", "addNum ", "addNum ", "findMedian ", "addNum ", "findMedian "\] \[\[\], \[1\], \[2\], \[\], \[3\], \[\]\] **Output** \[null, null, null, 1.5, null, 2.0\] **Explanation** MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = \[1\] medianFinder.addNum(2); // arr = \[1, 2\] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr\[1, 2, 3\] medianFinder.findMedian(); // return 2.0 **Constraints:** * `-105 <= num <= 105` * There will be at least one element in the data structure before calling `findMedian`. * At most `5 * 104` calls will be made to `addNum` and `findMedian`. **Follow up:** * If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution? * If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
null
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
Hard
480,1953,2207
1,852
well hello fans this is texas tim continuing my project to grind through leak code as you can see i've got some different seasons where i've been more involved in grinding and less involved depends on what's going on and i hope that i'm beginning to do some more grinding and i'm happy to have you along for the ride so let's see where i'm at 19 000 and let's go to the problems i've cleaned out the easy let's double check right so there's no easy ones available under algorithms which is what i'm working on so let's move on to medium and i like to sort from easiest to hardest so that would be this one 1852 distinct numbers in each sub array interesting given an integer array nums and an integer k you are asked to construct the array ands of size n minus k plus 1 where ands is the number of distinct numbers in the subarray and what is n i am having a bit of a tricky time wrapping my head around this one right hand of size n minus distinct numbers from the sub array okay so there's got we've got overlapping sub oh okay i got you i gotcha okay so if the input array has a size of seven and k is three then the output will be five so nums length minus k plus one okay and then that's what returned hey we're halfway done i just have to fill in the middle bits let's do it so we're going i'm okay i am thinking got a couple of ways we could do this we could do nested loop we could have an outer loop that goes from index 0 to like you know index num's length minus k some of that and then the inner loop would be to run out to the plus 0 to the plus k offset within you know of that outer loop index um the big o of that would not be necessarily super great uh alternatively sometimes you can um sort of keep track of the current uh subarray of interest by adding a number to the front and taking a number off the back and let's see if i can do that distinct numbers uh i could get a little tricky like you might use a set or something to get distinct numbers um but then it gets harder to remove the element of the subray that's leaving to make sure you remove it without removing every element of the sub like later elements in the subarray that would have that same value because you lose information when you put things into a set you lose info like well how many of this number were there to begin with so what i sometimes like to do is just make a naive solution just get something out there even if i know the big o is not optimal but it gives us a starting point let's try that and sometimes to remind myself i'll even say naive solution so it's going to be hey scotty boy it's my dog scotty boy come in here he's kind of deaf so he doesn't mind the fireworks too much but i may have to cut this video short so i can go snuggle with them alright so this would be the outer and then minus k off by one errors man freaking a okay plus i okay i had to use my fingers to make sure the nums length minus k was right i mean off by one that's like the bane right those fence post errors all right now inner loop j equals zero these are like the offsets of that variable i index j equals zero j is less than k and you can see we're getting this is going to be some huge big o here let's um set integer cursor this is going to be terrible performance oh actually this is gonna have to go out here okay and that would go through first subarray add nums i plus j and then ands all right equals cursive array size okay let's take a look for stupid mistakes like missing semicolons incorrect fences or braces let's see what we got here yes i could just hit run code and let the compiler catch my mistakes for me but i like the practice of inspecting my own code being my first qa and it also gives me a chance to catch my own mistakes instead of offloading that or delegating that to a computer especially in an interview type situation you want to demonstrate that you know how to spot things you've got good attention to detail okay well let's run it dang it all right what happened huh okay i'm doing some spaghetti action man i figured it was an off by one but like i did not actually like mentally grok that was what it was i cheated i did i looked at the output and saw it wasn't catching it so i just extended it by one i feel a little bit dirty all right well let's submit it let's see where we land performance wise and actually i should have looked at the constraints look at this 10 to the fifth so that's an that's a no-go that is not going to work that's a no-go that is not going to work that's a no-go that is not going to work we're spending a lot of time adding elements to a set so how about okay so the code is correct but it is severely underperformed so naive solution is not going to work let's try to maintain a list um a list representing the current subarray and the interface we can make list and the underlying data structure let's do linked list and that'll be super easy to just delete the first element and then add an element onto the tail so we'll just be deleting the head adding the tail and in terms of counting unique elements i'm thinking we just dump it into a set and count the size and you know retrieve the size property i think that would be let's try it so instead of adding the whole subarray each time of which length of suburban minus one would be numbers that were in the previous subarray uh well length of subarray minus two only the yeah because we're taking one off and anyone this way we're preserving a lot of those numbers and that should save us some cycles so list integer curve subarray equals new linked list diamond operator and i think i have to prime the pump here because inside the loop is going to be code to just take off the first element and add the next one it won't have actually the code to add in the first uh to populate that sub array for the first time so we'll do that so this is we're priming the pump here zero eyes less than k plus i add nums i okay so we've got our first list and zero before i forget i'm gonna forget that n zero equals new hash set integer i think that'll work let's just make sure that this kind of composite okay good okay and now we want to and i'm going to storyboard the i'm going to pseudo code it with comments so remove first element add new element store size of set and hands and i don't deal a whole lot with linked lists so let me just take a gander at the api here probably like a remove yep removing an index good so cursob away remove i minus one and then curse break add hmm trailing index equals i kind of like this i'm sort of making this up a little bit as i go remove zero and add so this will be k plus one so we'll remove i like this because the code documents itself right so we're going to remove trailing index and then decrement that and then add leading index and increment that and then we'll do our fancy and actually let's see well that's fine this will be i kind of like that trailing index and leading index let's do add next element alrighty zero through k so i think that might actually be that index out of bounds some of those fireworks sound like gunshots okay index minus one oh my goodness um no the trailing index is also increasing heavens dear heavens now the reason i'm using two indices because i could just have a single index and then calculate the offset every time but i'm just thinking of all those additions you know like you know we could just make this um you know this would be i minus one actually no we're gonna always remove the first one i'm like rubber ducking right now i'm like talking to my monitor and it's oh my goodness a little bit embarrassing if we were working on the input array itself then yes our leading and trailing index would be moving like that but we're doing something a little bit different so we're going to remove the front the first one and then add the next one which will be nums of the leading index let's run it good but is it performant let's see if we can even get on the board not let's see how big this thing is if you are yeah that's a pretty big input array okay well it is medium but a lot of people did get it right number of distinct elements uh okay let's think let's have ourselves a think scintillating watching isn't it you hmm i am a little bit stuck was there any hints let's see constraints let's look at hint frequency map the elements in each window frequency map okay so here i'm operating on a brand new i'm having to consider every element in the subarray every time okay that's good frequency map what are the constraints so the values could be up in the ten up to ten thousand sorry am i bouncing that i'm bouncing a little bit sorry okay this might be a little bit of a naive frequency map or frequency table because i did the same mapper table yeah caught a table um yeah not that big a lot of space oh yeah map would be better yeah okay integer frequency map um okay and we will um initially populate frequency map i like to use markdown formatting in the comments partly just helps me to you know see the variables okay so frequents actually for the initial population let's do merge the key is nums i initial value is one what is this i'm gonna have to address that later life happens even when you're coding and then okay that will give us our initial map and i guess i'm gonna make a little function oh actually we could get a key set and get this size frequency map key set right let's verify that the key set just returns a regular old set yeah so boomsies okay we're not really gonna do that so here now we are going to remove the previous what we're going to from frequency map remove the first element from frequency map and we know that it is so i don't have to do some of the guard clauses or checking because we know that the i minus one element must have been in the map because we would have added it earlier so frequency map get i minus one okay and then subtract it so i know that now that's otherwise actually i wonder if i can do merge i minus one well the nums i minus one element minus one i think that should work and if we can see matt get numbs i minus one uh was terrible zero then remove it because we don't want it to count toward the key set size even if the value of the key value pair is zero well especially in that case and then ns1 equals and i'm going to delete that code below that's cruft as they say okay and this will be hands i alright let's see what we got so we got our frequency map thanks to the hint i usually try not to use the hints but i was really stuck on this one frequency map and then populate it initially and then store the first value in ands and then we run through oh i have to add the new number and there's a lot going i also need to update the for loop parameters because now i am going all the way up to the end less than there we go merge nums current one and then we grab the key set size hmm i think i'm gonna start at k there we go kind of embarrassing revealing just how much editing goes on when i'm writing an algorithm all right initially populate and then here let's close that up i think it is going to work let's give it a shot run code yes oh my goodness but is it performant well i hope so we use the hint let's see wrong okay let's uh let's do some debugging why not let's do some debugging that's why we pay for the that's why i pay for the premium all right i added it now let's debug can i get more room no it's not adjustable okay let's see what we got here nums is that k it's three okay so these are our this is what we're given ans is our empty answer frequency map for the first three there's one two one three okay and we're gonna do the step over we've got step over step into step out what's this oh continue we'll be doing stepovers i'm not averse to a little uh printf um debugging or in this case system out println but uh the debugger it's very handy you get you don't have to set up all these you know all the print statements for all these variables and probably just looks more professional to be honest to show familiarity with the debugger so let's go through i might i want to kind of oh i hope that's not too small is that too small um oh gosh that's what am i doing here i wanted to see the whole loop in there um oh okay maybe that'll work okay step over so we added three pi equals 3 so 0 1 2 and 3. um oh i see we're actually removing i okay there you go so i'm going to call this trailing element and we are removing i minus k and then k i minus k that's how we debug we write and then we check and we find out what we got to do let me run it now okay so it is running and working now let's submit hooray nice uh placement right in the middle not too bad time complexity uh o n since we traverse the input all right once space complexity i guess is then since we maintain a frequency table of input well hold on it is k yeah the frequency well the table of signs less than k if it was all distinct integers in the subarray of k elements then the frequency table would be of size k but if there's any duplicates then there'll be fewer entries of size k less than or equal to k yeah i probably should learn that better okay so we're on the board with something approaching performance so can we make it better add next element to frequency map record okay let me run it again just to see if we get anything significantly better it's about the same let me update this memory usage i like to get a sense of where it is it's not it's probably not going to vary very much but i do like to sort of keep track of the best i've seen uh the best score i've seen for memory and for runtime independently all right i'm not sure let's take a look how could we improve it to get it up higher okay we're using this frequency map we could kind of roll our own frequency map with a giant integer array and then keep track of the number of array the number of um elements of that array that we're actually using we'd have to keep track on the way because we wouldn't want to have to do an inventory of that giant array we'd want to be maintaining that as we go let's see kind of making our own little map let's oh why not let's see um map why not how many what are the val what's the value range ten thousand and one now we gotta make kind of a little api so add to map um remove from map and get key set size this would be returning a variable that we're maintaining called key set size which is going to be out here case it's not equal to zero all right so when we add to map first we check do we have anything already so if and what's the name of our map is just map so if map of n equals zero then not only do we increment the count there which really you can just say it equals one and then we increment the key set size otherwise and what i like to do is to put a comment after the else to indicate what it is that um what condition so the so it's not zero then we just increment whatever is there and then we return i mean we could do that i see that i'm kind of duplicating some code here i'm saying map you know increment from zero to one and the versus um incrementing whatever's there so why don't we let's so here if we know this is a number we haven't been tracking before in our map then we do want to increment the key set size and then in any event we're going to increment the value there so it could be going from zero to one or it could be going from any non-zero number to from any non-zero number to from any non-zero number to you know plus one so remove from map now here's where we could do some error checking boundary checking because if you remove from map we could verify that there's something there to remove and throw an error if it doesn't i think we're going to do a little quick and dirty here and i'm going to trust that any number i'm removing is legit probably was added before so remove from map um so decrement it there and then get our little reverse check here checking at the end of the beginning if map n is now zero then decrement the key set size okay and then here we can get the key set size so that's our little these are our methods for our little api here's our data underlying data structure we need that as a important variable to keep and turn the debug off so now we don't need this guy anymore and now we're going to add to map nums i yes and then ants index that's fine and then we're gonna get what's the get key set size why not roll your own map why not okay now here and look at this so what we're removing is this guy right there let's comment those out remove from map that one and then we're adding this one i do like how because we made our own methods it's this code is super self-documented and i this code is super self-documented and i this code is super self-documented and i do like that add to map and now we get key set size boom and i'm feeling so confident i'm just going to delete the old code here although it could well if it ends up that this code is less performant than you know using the inbuilt map hash map then i can always leak code lets you go back to a previous submission so i could always grab one of these previous ones and get my code from there no problem let's get rid of this two and this so we have nice clean code all right let's run it i think it looks good so it did work we're using a map so the performance should be not too bad hooray index out of bounds okay oh that's 10 to the fourth that's 10 to the fifth right okay ooh i like that speed i like it very cool yeah that is not too shabby i'll take that in a heartbeat still o of n and our map actually let's call it frequency table so it's a little bit better self-documenting self-documenting self-documenting and the other nice thing is i don't have to change anything in here because i've got it nicely abstracted away so i just got to go down here and make sure i update these guys and then key set size let's run it again just to make sure submit it again and um it's all comparable all righty well i think because i rolled my own map i think it is worth adding to the discussion over here so let's go over there sliding window hash map that's cool so they did use a hash map let's just take a little look at this person's yeah hash map we did that one but i mean i did that and i found that it was like solidly in the middle right it was like 50 beats 50 so this is i think a little bit better let's see java and eight milliseconds beats ninety one yes um uses do people still say hand rolled when you do your own data structure or anything um let's see hand rolled algorithm like roll your own hand rolled loops hand rolled let's see eight and a half million i wonder do people hyphenate it eight and a half million versus just one million what about roll your own where's that fall in 2 million roll your own algorithm roll your own crypto that seems to be a pretty common co-location is to say roll your own co-location is to say roll your own co-location is to say roll your own in reference to cryptography although people also say that in reference to user authentication and random numbers there's actually quite a few areas it seems like people say don't roll your own hand rolled frequency tail maybe i'll hyphenate it because get rid of that little squiggly red line all right let's post it i hope that helps somebody and it also shows that you can write your own data structure and api for the data structure if you need to get some performance boom all right hey thank you for watching and that was a lot of fun and i'll catch you the next time bye-bye
Distinct Numbers in Each Subarray
biggest-window-between-visits
Given an integer array `nums` and an integer `k`, you are asked to construct the array `ans` of size `n-k+1` where `ans[i]` is the number of **distinct** numbers in the subarray `nums[i:i+k-1] = [nums[i], nums[i+1], ..., nums[i+k-1]]`. Return _the array_ `ans`. **Example 1:** **Input:** nums = \[1,2,3,2,2,1,3\], k = 3 **Output:** \[3,2,2,2,3\] **Explanation:** The number of distinct elements in each subarray goes as follows: - nums\[0:2\] = \[1,2,3\] so ans\[0\] = 3 - nums\[1:3\] = \[2,3,2\] so ans\[1\] = 2 - nums\[2:4\] = \[3,2,2\] so ans\[2\] = 2 - nums\[3:5\] = \[2,2,1\] so ans\[3\] = 2 - nums\[4:6\] = \[2,1,3\] so ans\[4\] = 3 **Example 2:** **Input:** nums = \[1,1,1,1,2,3,4\], k = 4 **Output:** \[1,2,3,4\] **Explanation:** The number of distinct elements in each subarray goes as follows: - nums\[0:3\] = \[1,1,1,1\] so ans\[0\] = 1 - nums\[1:4\] = \[1,1,1,2\] so ans\[1\] = 2 - nums\[2:5\] = \[1,1,2,3\] so ans\[2\] = 3 - nums\[3:6\] = \[1,2,3,4\] so ans\[3\] = 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `1 <= nums[i] <= 105`
null
Database
Medium
2370
735
hello everyone welcome back uh here's when I'm saying and today we are going to tackle a fascinating problem uh involving asteroid collision and this time in JavaScript so let's dive into the problem we are given an array of integer that represent asteroids in a row and the absolute value of asteroid represents its size and sign represents its direction positive means it's moving right negative means it's moving left so each asteroid moves at the same speed our task is to determine the state of the asteroid after all collisions so if two asteroids means the smaller one will explode if ball are the same size both will explode so and asteroid moving in the same direction will never emit so it's a medium level problem on lead code but I think we are going to solve it so now that we understand the problem let's discuss the solution and then implement it so to keep track of asteroids moving right and left uh the collision with left uh moving once we will be using a stack data structure so we will iterate through the asteroid pushing any Right Moving once onto the stack and when we encounter a left moving asteroid we will check the top of the stack that's the rightmost moving asteroid and if it's smaller we will pop it off the stacks and continue the comparison so if it's larger we will ignore the current asteroid if they are of equal size we will pop the stacks and ignore occurrence so uh let's Implement our logic and if something I will explain right away so let stack be stack and 4 i 0 ILS then asteroid length I plus let asteroid I and if asteroid greater than zero attack push asteroid else while stuck length greater than zero and tag uh stack length minus 1 greater than zero and stack length minus one less than math absolute of asteroid so then stack pop so in all those cases we pop the uh mentioned asteroid so if stack land equals zero or stack length minus one Less Than Zero so stack push asteroid else if back length minus one equals math absolute that's right Stack Up and return finally the stack okay so this is our implementation let's run it to verify it's working so I have previously solved it in Python so yes everything's work logic is the same uh quite interesting so all right uh we have got our function ready so now uh the moment of the truth so let's test our solution and submit it for unsynthesis cases so hopefully it will pass I'm running it so we get a green success message and yeah our implementation is quite good we bid 92 with respect to uh runtime and also 75 with respect to memory so it's both uh memory and runtime efficient so as you can see understanding the problem and knowing your data structure well can make a seemingly complex problem quite manageable so I hope you have enjoyed this journey through the asteroids and if you have any questions or ideas for future video please drop a comment below and don't forget to like share and subscribe for more coding Adventures until next time keep practicing happy coding
Asteroid Collision
asteroid-collision
We are given an array `asteroids` of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. **Example 1:** **Input:** asteroids = \[5,10,-5\] **Output:** \[5,10\] **Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide. **Example 2:** **Input:** asteroids = \[8,-8\] **Output:** \[\] **Explanation:** The 8 and -8 collide exploding each other. **Example 3:** **Input:** asteroids = \[10,2,-5\] **Output:** \[10\] **Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. **Constraints:** * `2 <= asteroids.length <= 104` * `-1000 <= asteroids[i] <= 1000` * `asteroids[i] != 0`
Say a row of asteroids is stable. What happens when a new asteroid is added on the right?
Array,Stack
Medium
605,2245,2317
349
hey guys welcome back to my channel and in today's video we are going to solve one more leadid question that is question number 349 intersections of two arrays so this is an easy level question and this has been asked by these many companies you can see there is a lot of companies which are interested in this question so let's see what this question is all about so in this question we are given nums one and nums two and we have to return an array of their intersection where intersection refers to the elements which exist in both the arrays so if we see this these two arrays that is number one and num2 we can see that two is present in both the arrays that's why we have return returned two we don't have to take care of the frequency of these numbers in both the arrays we just need to check that at least once this number is been occurred in both the arrays if the number is present in both the arrays and stre frequency is one or more than that then we are going to take that number in our resultant array and we will return it because that's an intersection so each element in result must be unique and you may return the result in any order so this is the question and there are so many ways by which we can solve this question but we are going to focus on only two ways so first one is the built-in method so in first one is the built-in method so in first one is the built-in method so in built-in method we built-in method we built-in method we will be using this op operator this intersection operator so in Python if we were using this operator so for that firstly we need to create set of both the arrays or the even if we are using an array then we need to eradicate the repetition so rather than doing that what we would have done we have created set of nums one and set of Ls two and uh by mistake but uh I have wrote the exact solution and this is the solution so this is the only thing that we would have done if we were solving this question using this operator so what we would have done is firstly we have created set of both the arrays after that we are saying return the list of all the intersections so list of all the intersection refers to this whole part set of now one and this operator which I'm saying and is the intersection operator and set of num two that's it and this is the exact answer for this approach but the thing is this approach consist of this inbuilt operator right this end operator which is uh finding out all the intersecting elements or numbers from both the sets so this whole approach won't be acceptable in our interviews but just for knowledge I have gone through this approach and the time complexity of this approach would be beo of m + n because we have transformed of m + n because we have transformed of m + n because we have transformed both the sets firstly and then we are checking the intersection so we are traversing both the arrays firstly to convert them into a set and then we are going through both these sets for intersection so time complexity is bigger of M plus n and space complexity is also bigger of M plus n because we are creating two sets so first one is of n length and second one is of n length so space complexity will also be same so this was the first inbuilt approach now there are so many approaches as I previously said there can be two pointers with which we have traversed these two arrays and find out the similar elements but we are going to solve it using set now the approach that I'm going to solve this question with is something that other people have solved it using dictionary but I have noticed that I use a lot of dictionary in my solution so for the change I'm going to solve it using a set so as I said I'm going to solve this question using set so now what I am going to do is firstly I'm going to check what we need to focus on the first thing that we need to focus on is the elements which are present in both the arrays so how we are going to find out the elements which are present in both the arrays firstly we don't need to take care of the repetition or the frequency of these elements if the element is present in an array and its frequency is one or more than that we don't have to focus on that part because we just need to know that whatever the frequency is we just want to check the presence in both the arrays right so what I can do is firstly I'm going to create a set of num one so nums one set will be created and it will look something like 49 5 right now I'm saying I just want to check these elements are present in Num two as well or the num two elements are present in this set right I just need to check this part so what I will do I will Traverse through this nums two and I will check if this element or all the elements are present in this set or not if they are present then I know that this is an intersecting number or element of this array that we need to return as an answer so I will add this element in an in my answer and will return it at the end so this is the approach that we are going to follow so when I created set of nums one what I will do I will also create a set of answers this is an empty set right now this is an empty set now what I'm saying is now Travers through this nums 2 and find whether these elements are present in set of nums one and answer why I'm going to check in both because we can see that the numbers are having frequency more than one so rather than populating or uh appending or adding our uh same elements in our answer we can skip this step you can also skip checking because at the end we are using set so anyhow they are not going to get added up in our resultant but what we are going to do is we are going to check in both the setes because at the end of time complexity is bigger of one so we can take this step in our concentration so firstly we will come to this place we will check whether nine is present in our set or not it is present then we will check it is present in answer or not it is not present so we will add it in answer now we will go to four is also present in our num set and it is not present in our answer that's why we are going to add it we are again going to get nine we can see that nine is present in set and it is present in answer as well so we don't have to add it we are going to check for eight is not present in our set and it is not also in our answer but as it is not in our set so we don't have to add it in our answer because it means this is not an intersection we will again go to four we will again check it is in nums one it is in answer we don't have to added so our answer will be only 9 and 4 and we can return it so this is how we have solved this question now if we see the time complexity of this question then it is going to be B of M + question then it is going to be B of M + question then it is going to be B of M + n how because firstly we are Transforming Our M length nums one into set for that it took B go of n time and then we are traversing bigo of uh we are traversing nums two and it will take big go of n time which is the length of nums 2 so m is the length of nums One n is the length of nums 2 so time complexity is this and space complexity is going to be bigo of M if we are not considering the uh length of our answer but if it is being considered then the space complexity will be big of M plus I where I is the answer array or answer set which is the intersecting set so space complexity will be big of m + I so this complexity will be big of m + I so this complexity will be big of m + I so this was the second approach and let's quickly code this whole solution so firstly we will create a set for our nums one so that is set of nums one after this what we will do we will create an answer set which will be a new set so this is our answer set now we will Traverse through this Nami for I in nums 2 and we will check if I in nums set and I not in answer then answer do add I and at the end return answer so this is the whole code in Python if you want you can eradicate this part because at the end we are using set so it is not needed but just uh
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
763
hello everyone welcome to our channel code with sunny and in this video we will be talking about the problem partition labels its index is 763 and it is the medium problem of the lead code okay so we are given a string s and we want to partition this string into as many parts as possible so that each letter appears in at most one part okay so that is suppose you have the character a then this character a should be present in only one part of the partition that we are going to do okay we need to partition our original input string into the as many parts as possible such that each part will contain the specific character let's call it as c then all the occurrences of the c in the input string s must be containing in this part okay if you're not understanding this right now no need to worry about we will take an example and i will explain how we are going to do this note that the partition is done so that after concatenating all the parts in order the resultant string should be s so we need to partition the strings consecutively like first one from 0 to some index then index plus one to another index and so on return a list of integers representing the sizes of these parts okay so let's look over the constraints also you can see strings length is 500 so uh yeah of n square solution even of n cube solution may pass but we will be focusing on linear time solution okay and uh you can see in the approach that we are going to use is the greedy approach uh it is not like a very hard one you can think about that how the sequence of operations will be performed okay so let's take this input string and we will understand this one so let me write down first the string a b a then we would be having b c b then we have a c a then we have a b e f e l i j h k l i g okay so this is the input string that we have been given and we need to partition this string into as many parts as possible and suppose the character c is present in this let's say part partition string 2 then all the occurrences of c all occurrences of the character c in input string okay so let me write down clearly in input string must be present in this part two must be present in part two okay so let's take an example and understand how we are going to like what is the actual meaning of this entire statement okay so like the example that i have taken over here is this long string suppose we would be starting from the very beginning you will encounter the character a so when you will encounter the character a what does it mean it means that the partition that we are going to take right now must contain all the occurrences of a it means that all the occurrences of a is going to say that we need to include the last occurrence of the character a also last occurrence of character a also so what is the last occurrence of this character a in decision you can see this is the last reference of this character so it means that you need to include all the characters uh all the strings all the characters up to this position like uh for now up to this position okay so when you will move forward you will encounter the character b also okay so when you will encounter the character b it means that you need to include all the occurrences of b it means that last character of b in the input string must also be included so when you will find out the last character of b you will say that yeah this is the last occurrence of this character b okay so you need to include all the characters up to this position also but you can see the last character of a still greater than this last character of b so you will your iteration will go up to this position for now okay so when you will move out to the next position you will see i have the occurrence of a so we are already done with the character a again you will move to b then you will move to c again okay so when you encounter the character c it means that all the occurrences of the character c must be included in the current part partition that we are going to do and if you will find out the last occurrence of this character c you will end up with here it means that all the characters up to this position will be included okay so what about the case like c will end up to this last position let's say at this position so that is the last occurrence of the character c is the end of the input string so in that case it will signify that we need to take all the occurrences of the character c so you can see this end position now which is the maximum in position so far uh will be extended to the entire input string because we need to cover the character c also okay so that is the main key point that i want to discuss over this year but here in the sample c will end up to this position so you will maximize the end like ending state of this you can see the sliding window actually you can see the starting of the start of the window will be up to this position and end of the window is up to this position so your end of the window maximum position where the window ends will be at this position where the character a ends okay because the character b ends over this position and c ends over this position all the occurrences of the character a b and c will end up into this string okay so we are done so what about uh yeah so we need to store the length which is nine i think a one two three four five six seven eight nine okay so we need to store the nine into our answer you can see one of the answers in the very beginning is nine okay so we need to move out to the next part so we are already done with this part of the string now we need to move forward so you encounter the character d so when you will encounter the character d initially your window is up to l is up to this position and right most position is r up to this position when you will encounter d you will have to include all the occurrences of d in the current window okay so you will look out for the last occurrence of the character d in the input string you will find d is going to end up two here so what you will do is you will extend your uh r pointer up to this position okay now again you will move out to the next one you will encounter the character e so when you will encounter the character e you will look out the last occurrence of the character e and will try to maximize the sliding window rightmost index that is the current sliding window right most index you will encounter that e is ending up to this position so you will increment r to this position so you will make r up to here and again you will encounter the character f now last occurrence of f is distiller at this position so r remains as it is now again you will encounter the character e you are done with e then you will encounter the character g okay when you will encounter the character g its last occurrence is still at this position so r remains as it is and when you encounter d it is done e it is done so you need to take this partition okay i think the length is coming out to be seven if you look out the sample one of the answer is seven okay so you are still done you are done up to this part okay now again uh you will look at the character edge its last occurrence is over here so your l is up to this position and r is here now you will look out for i so i large technologies over here so you will try to maximize r which will come out to this position then you will encounter j you will see that j ending index is the end of the input string so rd becomes here so you need to take out this entire string so its length is coming out to be eight so you need to append it to your answer okay so this is the entire step we are going to do okay so how we are going to implement all that efficiently so we will be taking some previous variable which will denote the you can see we should denote the index uh at which the last partition ends okay so we will initialize previous as -1 and each time we will start our -1 and each time we will start our -1 and each time we will start our pointer left pointer which is i as previous plus 1 and we will try to maximize our right pointer which would be which i will be calling as end index each time when will uh i trade from i to end index okay so if you are working upon this position let's say so you will i your i will be zero and end index will be last occurrence of this character a okay so which will come out to at this position and each time value will iterate from i to end index you will try to maximize this index variable as end index equals max of end index and the current character that you are working upon which is last of uh so i minus the character a okay so this is what you are going to do so let's look at the implementation how we are going to do that efficiently okay so n is strings length and last we need to show the last occurrence of each character and we have this answer which will be stored which will store the answer so we first will iterate in the input string and store all the last position of each unique character and we will initialize previous as minus one so while previous is not equal to n minus 1 we will start working on each partition so i will be assigned as previous plus 1 and in index will be last of s of i minus e that is last occurrence last position of this current character in the input string so we will go up to end index and each time we will try to maximize the index such that each unique character must be covered in this partition and each time we will increment i and finally you need to push out the length which will be i minus previous minus 1 and you will assign you will change the previous as i minus 1 to work upon the next partition and finally you need to return the answer note that the time complexity of this entire solution is still often because we are operating each uh each position of this input string exactly once so of n and space complexity would be o of 26 which you call it as of op1 also okay so if you guys have still any doubts you can reach out to us through the comments section of the video and thank you for watching this video
Partition Labels
special-binary-string
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
String,Recursion
Hard
678
1,029
1029 to City scheduling so we are giving a ARR costs let me make a drawing first so about this cost array so for the first index that is the cost to City a yeah for the first person and the second index so index zero index one for this subar this 20 is for another person yeah let me check so yeah there are two people so this is a the length of the cost is just 2 N so it means there are 2 N people so for each people so the people can go to City a or can go to City B but we need to decide so for example maybe this person needed to go to City a so this 10 uh will be selected by City a and maybe this 30 is also selected by C A and what left behind so the 50 will be selected for City B and 20 will be selected for City B yeah but for the people go to City a so there are n people go to City a and there are also own people to go to people B and go to City B they must be equal yeah so we what to calculate the minimum value yeah so normally how can we solve it let me use another example maybe let me make it easier so for example in the subarray that is one and 100 and we have another subarray and that is 50 and 60 yeah now we are going to decide what is the minimum value if we've decided to choose uh yeah so to toose two people so one people will go to City a another people will go to City B but we're going to calculate the minimum maybe here this one is the smaller if we choose this one so for the next array we have to choose the 16 because another person have go to City B so the result would be 1 + 60 to City B so the result would be 1 + 60 to City B so the result would be 1 + 60 it is 61 but exactly how can we calculate it so this is the gritty idea so for the first array we're going to check the difference if the difference is bigger so for example 1 and 100 the difference is bigger than 50 to 60 because 1 minus 100 it is - 99 but 50 - 60 it is - 10 100 it is - 99 but 50 - 60 it is - 10 100 it is - 99 but 50 - 60 it is - 10 so we're going to check the difference so if the difference is bigger but here is a minus value we're going to check if it is a smaller like yeah so if it is smaller if the difference is smaller what we going to do we're going to always choose the first person yeah so here smaller actually it is bigger because the negative 99 is also yeah the difference is 99 n it seems yeah but we're going to sort it like this according to the increasing order if the value is smaller so this means we're going to always choose the first person go to the C A and then we're going to choose the second person to go to C B because the difference this one is bigger but this one is even smaller yeah maybe we can use another example uh let me try to yeah try to use another example yeah we can also use another example maybe uh so for example if we can use 100 and one another one is 60 and 15 yeah so there are two people so those two people one people must go to City a another people must go to City B and for this one the difference is 99 and here the difference is 10 so we're going to sort it according to the increasing order so this 10 will be sorted first yeah so for this array and we're going to decided to choose uh this guy to go to C A this is 60 and then next people will go to say B it is one so it is still the same yeah so the idea is that we're going to use the difference of the two values the cost of two values and we're going to sort it in increasing order or decreasing order then we're going to choose the uh minim so for example we're going to choose the uh minimum we're going to choose the first value yeah in the first part of the array and the second value in the second half of the R so the idea is that if the difference is bigger or we're going to choose the smaller one as you can see the difference is bigger we're going to choose the smaller one first if we choose the smaller one first so what left behind we must choose the yeah if we choose the smaller uh one first it must be at the index one so for the next subarray we have to choose index zero yeah let me go to the code yeah normally gy idea is really difficult to explain basically it is like intution or mathematic skills if you can't think of how to do it you had to use a yeah you have to use a dynamic programming so let's get started so I'm going to prepare a result array and I'm going to check the ab inside the costs so the results should append uh a tole with a and I'm going to yeah use the difference a minus B and then I'm going to sort the result array so I'm going to use a Lambda function so K should equal to a Lambda and here would be X to X2 according to the increasing order so this means so for example this is 10 and 20 uh it is minus 10 this is 30 minus 200 it is 170 this one will be sorted first so I'm going to choose the first value for the first half of the Ray and the second value in the second half of the ray so I'm going to choose a variable n it will be length of the cost and M should be equal to n / two cost and M should be equal to n / two cost and M should be equal to n / two now I'm going to check the result it will be some item and first value zero for item in result first part and plus uh the same item one for the second part for item in result yeah the second part now let me run it to T yeah there's something wrong uh yeah let me t uh let me Che the real aray did I do something wrong about it yeah so this is the result this is SED first normally I'm going to choose this is 30 and 10 in the first array and in the second array I'm going to choose 20 and 15 yes so my programing should be okay but I don't know why yeah because here uh I should use the first part of the r it should be yeah what did I do uh this is the first part of the r yeah so this is my result um yeah the result ARR has been sorted yeah I don't know why I get a wrong answer um so this is 30 should plus this 10 should be 40 and this is 20 plus 50 should be 70 but I did something wrong yes so this is the item zero yeah it is not n because I need to use m is divided by n yeah it's not N I need to use the variable M that is why now let me just check it now as you can see it works yeah so for this problem normally if you can't think of a solution about the problem basically you have to use some examples for the gitty problem if you find some examples you have to guess or maybe I need to use the difference of each item and then I'm going to sort it and choose the first part yeah as the first index and the second part as the second index after sorting the ARR so this means if the difference is bigger yeah uh if the difference is bigger for example yeah the difference is like if inside a tople that is one and 1,000 and inside a tople that is one and 1,000 and inside a tople that is one and 1,000 and another tople is just 100 and 100 what we going to do so the grey idea is we always choose the maximum difference first and for the maximum difference we going always choose the smaller number because we want to calculate this the minimum cost so I idea is also uh yeah straightforward if we are going to buy a flight we have to go uh go to City a and go to City B and yeah how can we decide we can always decide the maximum difference because for this one I use the gry I take a one and after that one because they are nearly the same I can choose either one but I have to choose the second one and the time complexity is unlog in course we used the just the S thank you for watching see you next time
Two City Scheduling
vertical-order-traversal-of-a-binary-tree
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. **Example 1:** **Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\] **Output:** 110 **Explanation:** The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. **Example 2:** **Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\] **Output:** 1859 **Example 3:** **Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\] **Output:** 3086 **Constraints:** * `2 * n == costs.length` * `2 <= costs.length <= 100` * `costs.length` is even. * `1 <= aCosti, bCosti <= 1000`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Hard
null
495
uh-huh Teemo attacking okay fly I don't uh-huh Teemo attacking okay fly I don't uh-huh Teemo attacking okay fly I don't know what Teemo is so maybe is this like meme or something somewhere I John thanks for the trying League of Legends character okay well I mean yeah this is on the first line so I mean I'm with dota person it's beam on my for my last dream so yes so to me to always be heroes and not champions or whatever it is cool okay let me actually get to the bottom now cool okay in lol world there's a hero called Teemo okay thanks plants and his attacking can make his enemy Ashby in poison condition now given Timo's attacking uh let me actually also I guess I should finish reading first well I think this in a chat so you guys can follow along now given Timo's attacking ascending time series that given Timo's attacking ascending time series toward ash and the poisoning time duration for at Emo's attack you need to output the total time that ashes in poison condition man as well a lot of these LICO questions could be like tongue twisters but you may have to assume that teemo's attack at the beginning at the way beginning of a specific time point and big ash being poison condition immediately so it seems like some I mean without looking in the example case it just seems like when I'm dose like overlapping in the world things so we kind of look into a little bit and with that I always checked out the kind of input output because in some cases it may be small enough that you know you just have a bully in a way of like a hundred element or something like that and then you don't you know why you even do anything right to get it out as soon as possible the length will be ten thousand a number in the time series is 10 million so 10 million billion away is if I pushing a little bit way so because especially since this dramatically is smaller than ten thousand so we'll just do like a sweet blind type algorithm where we're you know at most will have ten thousand you fans okay let's take a look at the example just to make sure so in place so what is two of two is the duration of each one so oh so we even have a fixed duration okay so we start up one four I mean I could true yeah I mean for visualization I guess I get Jordan yeah I really need to get on those touchpad things but uh I guess I don't really need to visualize today okay fine so one two three four five and so this is Timo's good and then I have one a poisoned tries and a good again and then poison try so then therefore your output for okay I mean I think this is pretty straightforward to visualize I don't magnitude to the other one I mean I think the other example is kind of obvious and then like if I just do some overlapping thing so yeah so in this case okay overlapping so they're couple of ways to do these sweet blind things especially with the duration being fixed you have an data center that came in at that 10,000 input they will be at most that 10,000 input they will be at most that 10,000 input they will be at most 20,000 defense don't think I'm looking 20,000 defense don't think I'm looking 20,000 defense don't think I'm looking for is also to see if they're like typical numbers which it doesn't really matter yeah just seems like it's okay so okay I think the other thing is an ascending so yeah the other thing I was looking for is to see if it's already sorted if it's already because if it's not sorted then you just sorted which is a prerequisite for a lot of sweet blind things doesn't and sorting is just kind of providing the structure so that you could kind you know sweep across and the most easy way okay cool how do I want to code this it's obvious yeah if it's already sorted then I think we could just do something just like Metro one food the time series yeah okay I think there'll be just some math around like edge cases and stuff like that but I think we could there should be okay so total is we're going to return yeah usually I would I mean in five and general you know use an elevator and look for just like you know inferior like you know time point in time series but I'm trying to think if I need to do like things where like I need to look at adjacent elements because if you do then you know you may do like a sip or something like that to kind of just have them together and in Python is much easier to do things that way with every tours or something like that but probably okay start at zero last poison okay so at every time you vent you have a few things to check is are we still poisoned okay would that be a boolean or the thief I mean so in theory you could just simulated with a boolean value BAM I think we could actually just you know keep the last date of the last event so because is in ascending order time series of X of minus one plus duration will always be the latest possible on poise and state or beginning of the unpleasant state so we don't need to keep more States than that man I just realized I've been using different cases I always forget good language to just much okay if time point out so tempo is an integer if time point is less than or wish I get to stay right okay so if the current point in time if we're poisoned do we want to do poison in that poison okay let's do not poison first so if this is greater than that and then last poison is equal to time point twice duration I think that would be stayed otherwise actually I think and this is going to be true in both cases but I won't save this to the end but if it's poisoned and we want to add something to total probably total because we want to add todo to when the state changes which is in this case from not so it was not poisoned from last poison or from time point - last poison so how long was it point - last poison so how long was it point - last poison so how long was it poisoned for there's a lot of edge cases I really wish I had a sketch pad type thing but okay I think I needed to track one more stable just when it got started so stories you go to tell someone like this okay style is important because if you're poisoned just keep on going and we have to do something to total cuz I'm the total is equal to last poisoned - store I think this is right except for - store I think this is right except for - store I think this is right except for there's one more case to consider which is I think one more yeah so there's one more case where at the end you're poison but you know there's no more loop to check so then I think for dad you could in theory just append a really big value in the end I think that she okay well yeah and I think tissue povery work someone like the tickler see peg was a 10 million so I'll just choose 20 million say I think this has put I mean okay I think the easy part about this is I could print out the state at each paying so there should be easy to debug Alice I think ha man I do not remember how to buy country your pen man oh yeah okay fine sad right I was using ghosts and text for a second none type is not it's fine something warm depend okay fine I'll do the their cell no cases the universe I just want make sure the rest of the logic is way we should get better at that formatting flame string format well total you got - when it's not great okay total you got - when it's not great okay total you got - when it's not great okay how can it be hmm oh yeah well because I did this first okay cool so just to kind of see where things are so star last I guess I could also just press shoulder Toto yeah it should be pretty short I'm sorry I already were both in talking but you know so uh yeah so it okay so that's the pre state I guess hope Ronaldo's hey I mean this was okay so that happen expected man I don't know how to append stuff remaining I mean this looks right yeah so why is this giving me there append stuff it's just this do I have to do then okay so type horn was its last poisoned okay got you abide in triggered is the second time you know time points toward last one todo and time point so oh I'm an idiot okay fine okay so that worked for that case I'm going to try the other one that's here oh so that worked - I guess that's here oh so that worked - I guess that's here oh so that worked - I guess I'm good - somewhere I'm worried I just I'm good - somewhere I'm worried I just I'm good - somewhere I'm worried I just a lot of silly mistakes and that's why we practice right okay cool so yeah in this case I think so a mini wet road I think this was pretty straightforward I mean it's people I know but I think the thing that I would defend here that is something worth pointing out is that I understand the value at the end so that I don't have to do like otherwise I would have to maybe do an extra case here like if you know maybe I could have just done like turnip because I bring a note in a solution would just be like this I guess maybe that could been okay too but I think for more complicated cases you don't necessarily wondering kind of you just want to add a senator or value so that you know you don't have to add an extra case for having the IDN okay cool in terms of an interview question I think actually this is prior I think this is a relatively standard interview question I can imagine being a sin and do you gosh I don't know if I like it to be honest but is very common like interval ye kind of merger and so forth so this is something that I actually but you know concern practicing that one
Teemo Attacking
teemo-attacking
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effect ends, the timer for it is **reset**, and the poison effect will end `duration` seconds after the new attack. You are given a **non-decreasing** integer array `timeSeries`, where `timeSeries[i]` denotes that Teemo attacks Ashe at second `timeSeries[i]`, and an integer `duration`. Return _the **total** number of seconds that Ashe is poisoned_. **Example 1:** **Input:** timeSeries = \[1,4\], duration = 2 **Output:** 4 **Explanation:** Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5. Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total. **Example 2:** **Input:** timeSeries = \[1,2\], duration = 2 **Output:** 3 **Explanation:** Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3. Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total. **Constraints:** * `1 <= timeSeries.length <= 104` * `0 <= timeSeries[i], duration <= 107` * `timeSeries` is sorted in **non-decreasing** order.
null
Array,Simulation
Easy
56,605,649
328
Loot Hello Everyone Welcome To My Channel Today's Question Is Audio Nikli Then Questions Given Link Group Cold Not To Be Followed By Not Pleased To Develop A Strike Rate Of Time E Aaj Ke Din Tak Sample Pure 12345 Se Zara Number Interesting And That To For Which Everyone around for this info which can save a this article example enter question is the school cutni to phone and De Villiers send me all the notes and interesting the first second third fourth 0 the reason why I have but what is the Logic And How They Can Write To 225 Android And 147 That Is Note View Also A True Initially Vrishvi Starting With And Enemy Add Naveen To Do For Is Equal To Medium From This Side In Notices Stop Message To Healthy But In Alternative Mode Switch Off That Shows Pendant Sahitya Hair And Its A Flash Light Come To Again Will Be Changed Is Note 9 Vikram Force International Limited This Sim Android Windows 8 That Tamil Guna And A Jhal That Is Ot Equal To Notice Issued On The Tatas Factory Shifted To Improve Swedes How To Identify The Giver Not Even More Knowledge See How They Can Get More Interesting In The Evening Healthy Market Se Start From You On Unmute Third Notes Interesting And Stress In The Second Notes In The Default By The Questions And Answers Between To return to main link less most innovative in Rajasthan returning audio nikli hai jo alarm repeat to question hai cigarette minute written on jo tu nikale is 1514 statements hai and should look like 239 everyone should look like this let's see who wins from this question is The Question Is The New 2018 Ignite The That And Listen Behavior Find Know Where It's Something To The Point Which Is And For Everyone's Feature To Points Which Will Have To Traverse Through The Language And A 1200 Total To-Do List Note Phone 1200 Total To-Do List Note Phone 1200 Total To-Do List Note Phone and nothing to them dam possible hai ho hai main 10,000 may to link list for now 34 10,000 may to link list for now 34 10,000 may to link list for now 34 points to old is gold hai that and have to break and for even have so let's start which is to prove this roti to False Element And My Friend This Point Into One That Whatever Discovery They Need To Put This One In Front Of Shooting Schedule A Is That Add Next Exactly To He Died To Toot Next Exactly To Head Statement This One Will Come True That Boat Potato Boil Point I head-to-head Next9 Head Come To That If The Said Change My Is Not And Where Is Not Vikram A False Statements Than Next Element Is Even When The Element 11221 Like This That Choice May Even He Did Next Will Absolutely To Head Special 09 Ki And O My Phone Tune Exactly 241 Next Time For Everyone Welcome 1948 Will Also Commented Yeat Hi Hoga And In Those Points Head-to-Head Also Commented Yeat Hi Hoga And In Those Points Head-to-Head Also Commented Yeat Hi Hoga And In Those Points Head-to-Head Next9 He Will Complete Three Layer Is Not Will Be Coming Into Proof Vidro Entertainment Award Winner to as it means o my phone products absolutely to head of lord Vishnu but ministry again played again appointment with oo that and also not done I is beautiful two forms badminton extent even withdrawal to the Malik prevent next absolutely soft be to again appointment head -to-head to again appointment head -to-head to again appointment head -to-head Nisan He Will Come In The Zodiac 236 Elementary Middle Class Products Tweet A Hai Hai Hai Mi A For Redmi Kaun Hai Wow Ek Ajnabi Un Points Medical Student Max And Welcome Them Again Airplane Mode On My Is Jodi Co Into Force Station Aircel Strong Kidney 60 So A Malik So Much For Everyone To Connect With Equal To A Ki And Vikram He Was 6 I May 9 For India And They Can Point My For Medical Tune Switzerland Telling Glycerine Okay That Advance And United States But Will Give Me All This Doubtless That In Defiance Will Go Into Use The Same Logic Pushola And Old Even List Problem With Two Trends On A View Of Making And Forward Neck Shrinkage Improved Fit And Television Institute For Daughters And Middle Guna Increase Three 500 Putting On That All Good night at this place and positive the food but I can do instead of for road electronic that I will write to forward dot Let's move to the wedding point and see what is the hotspot on so let's see the proven code that is look at number 80 while iPhone forward for even option list 90 David O that's interesting and is this mode echo Ruk points starting from one and the first Choice Award Show The Questions Were Not To Give Lots Of Values ​​With To The Number Of Not White Heads Values ​​With To The Number Of Not White Heads Values ​​With To The Number Of Not White Heads Rs Is Not 10.1 Acid And 10.02 For It's Rs Is Not 10.1 Acid And 10.02 For It's Rs Is Not 10.1 Acid And 10.02 For It's Not Even Going To The Point Notice Clipping Medium To The Don Dawood Will Get Started zidaa hai dayan the software aaye samiti mein code whatsapp text message ko support for this problem in this video you will you please give them thank you for watching my video please subscribe kar ka video
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
222
hello everybody is a male and today I'm gonna teach you how to solve the count complete three notes problem giving a complete binary tree count the number of nodes know the definition of a complete binary tree from Wikipedia in a complete binary tree every level except possibly the last is completely filled and all nodes in the last level are as far left as possible you can have between 1 and 2 to the H nodes inclusive at the last level H so for example in this case the input is this complete binary tree and the output is 6 because there are 6 nodes so how can we solve this problem well we can solve this problem recursively and iteratively in this video I'll teach you a recursive solution and first I'll teach you the proof for solution or the naive solution that doesn't take advantage of all the properties of this tree so first I will say if root equals no if I have an empty tree then I return 0 because there are zero nodes there are no nodes otherwise I return count notes of root that left plus count notes of root up right plus 1 so as you can see I have one note here so that's the plus one and then all the notes in the left sub-tree plus all the notes in the left sub-tree plus all the notes in the left sub-tree plus all the notes in the right subtree recursively I'm gonna run the code I'm gonna submit the solution all right this is working but this is this can be improved what we can do is that we can take advantage of the definition of the binary tree it is a complete binary tree so a complete binary tree can be a perfect binary tree and a perfect binary tree is a tree where all the levels are completely filled so this complete binary tree could be a perfect binary tree in that case we need to check that if it is a perfect binary tree the number of nodes in a perfect binary tree is equal to 2 to the height minus 1 so we can optimize we can do this I'm gonna remove the base case here and I'm gonna say the following I will have two variables integer left height test value of zero and right height because if I live zero I will also have a pointer P left initially at the root and P right initially other route then I will get the number of nodes in the left most branch and also the number of nodes in the rightmost branch and that's going to be the height so I will get I will do while P left is not equal to no I will increment H left plus h left height of the left and P left because the value of P left that left I will also check how many nodes they are in the rightmost branch so I will say while Pete right is not equal to no + + H right the height not equal to no + + H right the height not equal to no + + H right the height of the right Pete right to the file of P right that right so I will traverse the entire Ramos branch and get a number of notes in that path in the Ramos branch and then I need to check if it is a perfect binary tree how do I check if this complete binary tree is perfect I compare the left height and the right height and if they are the same then this is a perfect binary tree so if H left t equals h right then what I can do is that I can return cast into an integer Master power the power of 2 raised to the height H left minus 1 that way if the complete binary tree happens to be a perfect binary tree I can immediately return this and I can avoid the recursive calls I'm gonna run the code alright I'm gonna submit a solution okay this is working perfectly so as you can see the time complexity depends on the property of perfect binary tree or complete binary tree if it is a perfect binary tree then it's gonna be Big O of H where H is the height of the tree but if the tree is not perfect then it's gonna be Big O of n where n is the number of nodes in the tree if you liked this video please press the like button don't forget to subscribe and see you next time
Count Complete Tree Nodes
count-complete-tree-nodes
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree. According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`. Design an algorithm that runs in less than `O(n)` time complexity. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** 6 **Example 2:** **Input:** root = \[\] **Output:** 0 **Example 3:** **Input:** root = \[1\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[0, 5 * 104]`. * `0 <= Node.val <= 5 * 104` * The tree is guaranteed to be **complete**.
null
Binary Search,Tree,Depth-First Search,Binary Tree
Medium
270
1,740
so uh currently we are trying to find out the distance between two values that has been given in a binary tree uh for this problem uh we are basically trying to find out the value of distance between the lowest common ancestor and p uh then we'll add it to the distance between the least common ancestor lowest common ancestor with q so this is basically uh the distance formula uh between these two okay the lowest common ancestor for both p and q uh what it will be basically uh we will be uh finding it as a depth first search of root now this we will be able to find out so this means we are going to create two functions one of them is a depth first watch this is used uh to uh find out the lowest common ancestor okay and this has to return a particular value and before that we are also trying to find out the distance and the distance will basically take one node and one target the target can be p or q and it is going to return some value okay it is going to return some value and this will also be able to return some value so let us uh first talk about so this one will take argument node now uh let us talk about the boundary condition if node is uh none or no dot value is equals to p or no dot value is equal to is equals to q uh then what happens we are going to return the value of we are going to return node then uh we are going to calculate dfs of node dot left as left and right is equals to dfs of node dot right so if left and right both are basically uh existing then we are going to return the node okay so this is the lowest common advisor ancestor now else we are going to return left or right now this is the least common advice uh ancestor okay the sleep is taking me over now if node is not existent then we are going to return the distance as infinity okay and if node.val is equal to is equals to and if node.val is equal to is equals to and if node.val is equal to is equals to target in that case we are going to return the value of zero otherwise in total we are going to return the value of minimum of distance of node dot left comma target and list of node dot write comma target so with the help of recursion this will be able to give us the distance and the distance will be calculated as one plus minimum of the distance between node left to the target and distance node right to the target so this ultimately uh will finish our problem now let us submit this particular solution and if this is working lowest common ancestor so this is basically accepted if you can see thank you for watching the video
Find Distance in a Binary Tree
count-subtrees-with-max-distance-between-cities
Given the root of a binary tree and two integers `p` and `q`, return _the **distance** between the nodes of value_ `p` _and value_ `q` _in the tree_. The **distance** between two nodes is the number of edges on the path from one to the other. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 0 **Output:** 3 **Explanation:** There are 3 edges between 5 and 0: 5-3-1-0. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 7 **Output:** 2 **Explanation:** There are 2 edges between 5 and 7: 5-2-7. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 5 **Output:** 0 **Explanation:** The distance between a node and itself is 0. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * All `Node.val` are **unique**. * `p` and `q` are values in the tree.
Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)? To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask. The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.
Dynamic Programming,Bit Manipulation,Tree,Enumeration,Bitmask
Hard
1177
215
all right so disgusting us 215 case largest element in a array we want to return the case the largest element in the unsorted array and it's the question is asking for the case largest element in a sorted order not the case this thing - element so basically if we could thing - element so basically if we could thing - element so basically if we could sort it we just take the case element from the right that's the number we want to return but for this type of question like case largest the cases smallness that table K or smallest okay this is similar to a question that I did like I think it's more about our weeks ago that a week ago the put a link over up there that's the question is that case closest point towards the origin that it's exactly the same type of question and they're typically the interviewer I guess they are looking for two kinds of question solutions one is priority queue you maintain size k priority queue throughout the when you're iterating over the whole array so and use the priority queue to keep track of the current k top k largest are less than you are you currently scan through yet so far and in the end you just return the you know the first element in the priority queue that's the smallest if you're using a min priority queue that's the smallest one on the priority queue which is just so happens to be the case largest and for that necessary will be the time complexity is n log K and B the number of elements in the array and K s T is K here the reason for that is you have to maintain a size k priority queue and the operations on the priority queue is log K whether you want to pop up event or you want to push something over it that's log K so the time complexity is l know K but it's actually lower than that because for a lot of the numbers when you compare that with the zeros you know first element on the priority queue you can already determine whether you want to do this keep operation or not so unless you're working on monotonically I guess increasing array that's the worst case you have to pretty much share and do the operations every time you see in each iteration otherwise you wouldn't actually do anything to the keep you just compare they're just do a compare and you can figure out you use a lot of the times you actually donate it to that so and lokay is the upper bond water staircase and for the space complexity at its k that's the size of the product you know the primary q the other method is the quick select basically it's using the petitioner pressure from Creek sort and you just do that multiple rounds petition well until that you the elements that being you and the element ended up exactly at the case to the right location you know when that happens you just return that number that's the quick select the best scenario for that message is as linear is order of n so it's pretty much to end job closeness the worst case is quadratic so yeah I like them you know if you want to further more detailed analysis you can you know check on the case closest the points to origin that's the video contains more detailed explanation my personal feeling that if you want to sort this do this question it's usually again you can ask them if the unsorted array of whether it's a stream of numbers in that case you would almost be sure that if they say it's a string they'd ever looking for a prior to queue so yeah so for this question today I'm just gonna coat that priority to you what the quick select and you can go to the video and look at that it's gonna be pretty similar so yeah because this question is just asking for the value just comparing the value directly and then it's asking for the largest another smallest and the code it's gonna be extremely simple was prior to kill so we initialize in the priority queue to be empathy for each number in the array if we haven't meet the capacity of the priority queue yet less than okay we always got to push the omelette on to the party so that's like keep Q dot otherwise if we do this check whether the current number is larger than the smallest of the top KEK we currently know so far if that's the case we're just gonna do a hip replace which is equivalent to pop this number and push this onto the right ear and at the same time maintain the heap ordering in the end we just return the you know this number it's guaranteed to be the one that we looking for so yeah this passes the judge and pretty fast a little bit bad on the space because this does have to require some I really don't know this is almost a constant for reasonable sum okay yeah for a quick slack if you do in place of swaps modifying the elements within the Dom so it's a constant space and linear time the best the time but that one is honestly I'm really looking for that I think they have hip one which is to do five in the most current of your purposes so yeah you feel interested in quick select go check out that video or look about the civil you know articles explaining quickselect so yeah that's the short video question for today
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
92
hey hello there now i'm looking at a potential follow-up potential follow-up potential follow-up to the question 206 reverse linked list it's a 92 reverse linked list of two so instead of doing the whole linked list reversal as the previous exam question now we are given a starting position and end position all we want to do is to only reverse the linked list in that range so obviously if the approach is gonna be in a couple of steps one is to move to the starting point two is to reverse the section then third is to make sure the uh the you know the rewiring is okay so using this example here and our initial state is looking like this to move to the starting point notice that this linked list uh pretty much one index so this node one is actually the first node there so when we're looking at the m node it's indeed the m node inside this linked list so let's just say that m equal to two here we basically want to get to here have another traversal pointer and a pointer points to this node two here uh then we do the reversal so we're basically just gonna have a while loop or for loop whatever that counts down to exactly the difference between m and a so um we want to reverse that many links so let's say that uh just taking this as an example we notice that in the final state here we basically change the two points to three point two four to four points two three points to two so in the reverse in the section part we need to reverse m subtract by m exactly this number of pointers internally within this section so that would make this to be something like here and uh and potentially we'll be able to we will need to cut off this link here from one and four to five so we need to make sure that we have some pointing pointers points to those very important locations so just call it the graph some reference pointers uh obviously we will want to have the have this we want to memorize this note one here this is going to be the last node of the section that's prior to reversal the importance of that is after we do the rewiring in the middle we need to have this last nodes points to the new head so this node here will be become the previous pointer so to the third step that making sure everything is rewild correctly we will ask the last two points to this previous and so that it's one two four and we want to have node two points to a new five um so after we do the reversal uh there is going to be a next pointer points to five or the traversal pointer points to a five um yeah i know it's a little bit confusing if you have no idea about how this two a few variable naming is working um maybe checking this uh this video here my video about the 206. yeah i should make this uh two in one video actually anyway so um yeah so that's that is pretty much uh it i'm just gonna do this in two three sections one is to move to the starting point second is to apply the reversal code on the section then after that we need to do some final rewirings we will have the this is going to be the tail note right yeah because also going to grab a pointer for this node just going to call it tau this is going to be the tail node for the section for the reversal section now so this is all means that after we do the reversal this node 2 will become the new tail and we would want to have the tail points to the uh traversal so connecting 2 to five uh and one to four so that's uh that's the third thing that we need to do after that uh we pretty much just return the original head uh if not if that exists one case that the previous head can be problematic is that if we have m equal to 0 meaning that we're starting the reversal from the beginning we wouldn't be able to have anything like the last it will be a no pointer if that's the case we will want to return the node 4 which is previous otherwise we want to return last um yeah so i think that's pretty much the uh three stages of applying of solving this problem yeah so let's get into code all right so we need some pointers um what do we need definitely a traversal node that's starting with the head we want to move that to the beginning of the reversal section and we also want to indicate the previous note to the traversal because it will be tagged as last and we're going to create two aliens for the previous node and the tail node for this two nodes immediately this node immediately before the section and the first node of the section so let's do this traversal first the uh the number of step that we need to hop to the m's node is going to be m subtracted by one so as example the question example we have m equal to two we're starting with the head we just move uh two subtract by one to get to the two so that's why i have this while loop to be m greater than one i'm going to decrement and in there and also something that i will also need to do i will also be doing is to decrement in as well because in the number of nodes that i need to swap is the difference between m and n so if i uh decrement n at the same time um it will be become exactly the number i want after this while loop obviously i could do the calculation of the difference beforehand and yeah actually just do that now let's just call it k so we are traversal um to move this traversal node to this amps node so after there we basically creates the alias the last for the previous the tail for the traversal it's called tail right so this is to move to the start to move to the amps node make sure the connection is right that's this last step now the return part is just going to be um we're going to return the header all right uh right because the head node should be the same uh the only complicated can be is that if the last node is not there well if it was starting with the m is equal to zero so that pretty much translates to the previous note is going to be a null pointer yeah so that's that leah let's do the uh let's do the reversal uh we first grab the next then have uh how about next node points to the current reversal node um nope sorry have this traversal nodes point to the previous node and then to advance the previous note to the traversal and move the traversal to the next so that's how we do this reversal among two notes we do that for exactly n times uh yeah actually n minus one because when it's a zero uh that iteration doesn't run so it's uh it will be exactly the difference between n and m uh n and m so this will take care of the reversal of those sections uh lastly we will just need to do this rewiring look up the notes here what should we do we should have lost the points to the previous uh that's when the last node does exist it could be the case if m is zero that this last is going to be the same as this previous note initial state is going to be a null pointer so if it's not now we will ask it to points to the new head node for the section um yep and we will want to have the tail nodes points to the traversal otherwise here if the last node is not there we will actually need to have the head node to be the previous node there we don't need to reassign it yeah so this should be it yeah so in three stages we first moved to the amps node we keep track of the nodes that's immediately before these reversal section because we want to have these two points to the new head and the original head of the section is going to be the new tail so we also make an alias there am i missing any kind of uh pointers declarations uh lost and tell oh i'm missing the next all right uh so then it's the reversal we grab the next because we're going to lose that reference if we don't grab it very early on then we just have this current node we're looking at instead of pointing to the next i ask it to point to the previous note so to reverse the direction and have the advance this previous and traversal to their next and decrement the count for the number of nodes i need to do the reversal so this while loop will take care of the reversal between m and n after that we want to have the last the very last note before this uh reverse the section we want to have it points to the new head and also have the new tail of the section points to the head of the remainder part from this original linked list in the end when we try to return the head node we do a quick check if the uh if m is not zero if we are starting with uh if we are not starting with starting the reversal in the head node that means that the last day is not no pointer then we return the original head otherwise we return this new head which is going to be the original tail of the reversed section yeah so that's uh i think it's the code let me run it no what's the problem okay this k here right um no still no uh am i reversing more than needed no i'm reversing less than needed actually so uh i will say this to be the k should be plus one yeah this time should work okay yeah um yeah this is tricky okay so that's uh the this follow-up okay so that's uh the this follow-up okay so that's uh the this follow-up question to uh reverse linked list um the this middle section is pretty much the original question in the iterative fashion the only thing that's different is to have the the initial kind of a movement and also keep track of a few things and then it's the last housekeeping kind of work so nothing too difficult just need to be careful and pay attention to details about the code and what is pointing toward at what time yeah so that's a diagram definitely helps so that's the second question today
Reverse Linked List II
reverse-linked-list-ii
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\], left = 2, right = 4 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[5\], left = 1, right = 1 **Output:** \[5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 500` * `-500 <= Node.val <= 500` * `1 <= left <= right <= n` **Follow up:** Could you do it in one pass?
null
Linked List
Medium
206
1,535
hi everyone my name is steve today we're going to talk about lego problem 1535 find the winner of an array game let's take a look at the problem first it's giving an integer array a of distinct integers and an integer k the how the game will be played is like between the first two elements of the array that means array zero at index zero and at index one in each round of the game we compare the first and the second elements the larger integer wins and remains at the first position and the smaller integer moves towards the end of the array the game ends when an integer wins k consecutive rounds return the integer which will win the game this is the problem and it's guaranteed that there will be a winner of the game so let's just take a look at one example it's given this array two one three five four six seven and the k is two which means we need to find a winner that wins this comparison game twice consecutively let's see the first round is this given original input array 2 1 so the first two elements are 2 and 1. the winner is two and one is moved towards the end everything else shifted towards the right so three five four six seven three right so three five four six seven i shifted towards the right because one has been moved towards the right and then two wins once and then we keep con we keep playing the game which is the first two elements are going to compare two and three so three wins so three moves towards the front position and two is shifted towards the back everything else shift towards the left so three wins once we keep continue playing this game for the third time is three and five are the two front elements they are going to compare five is the winner right so five wins the first time and then we have five and four these two trend elements are going to compare again five is the winner so five wins the second time and the k the required time required times to win is kk is 2 so that's why we return 5 in this test case we can go through a few more test cases for example this one 3 2 1 k equals 10 that means we need to find k times which is 10 times such a winner such an integer in this given input array that wins consecutively 10 times there's a total only three integers in here so what we have is of course it's going to repeat itself but in this case pay attention there's only a total of three integers which is less than the number of k so what are we going to do we're just going to return the largest one which is three and in fact that is the case because like say we compare we just keep comparing in this case three and two compare so two moves towards the right and next one is one in the second position then let's we compare the second time three compare with one it's still three is the winner so three wins the second time right then two is in the back in the second position again we continue to compare you see this is e cycle we keep comparing three with the remaining of this array and three is always the winner so three will continue to win many times k specifies but do we really need to go through all of that times no we don't right that's just repetitive it's repeating itself so we can just cut a shot we'll just return the max number in this given array if the total number of distinct integers is smaller than k times now let's take a look at example three we're given this one is zero one two three four five six seven eight so it has eight elements and eight is bigger than seven so let's see we'll compare we just follow the rules to compare the first two elements one and nine one will be shifted towards the end nine stands in the first place and now looking at this array we know nine is the biggest element in this array so nine will always hold the first position everything else the remaining atoms they will just keep shuffling right so nine will win seven consecutive times in a row so we'll return nine in the end now let's take a look at it at example four we're given this array k is what k is like say this is three zero okay k is one billion so which number it can win one billion consecutive times it's guaranteed to be the max number in this given array since this problem it says it's guaranteed there will be a winner of the game so in this case it's very safe that we just returned the max number the k is like so many orders bigger than the total length the total number of distinct integers in the given array the only possible solution in this case must be the max number of this array all right that's the first thing that we need to pay attention to which is the case when k is greater than or much greater than the total number of distinct elements in this given array then we're guaranteed to return the max number in this given array what about the second thing that we need to pay attention to that is when k is smaller than the number the total number of distinct integers in this given array in that case what can we do we can just detract the biggest number that wins so far when we have a one pointer to move from the left towards the right every time when we encounter a bigger element than the current one we can just mark this wind times to be one and say if this current element is always greater than the next few elements that we are comparing against then that means this element is the one that will keep standing in the front rail then we can just keep incrementing the wind times and whenever the wind times is greater than or equal to k we can simply return the current element which is the element that is standing in the front the trick here is that we don't really need to imitate what the problem is describing see you don't need to really increment a an array list in java or a doubly linked list then you can move the one element that is the loser after comparing with the other element in the first two elements and move that one towards the end of the array or the q and then you keep doing this shifting that is really not necessary to do the simulation what we can do is very simple we can just use constant extra memory and this is a one pass now let me put this idea into the actual code let's take a look so first would call this one we'll initialize two variables one is called wiener we're just to use the first very first variable in the given original input array to be our winner it can change of course in many cases it's going to change but that's totally fine we have another variable called win times wind times first this one the first element we haven't compared with anyone else so win time is going to be zero now let's have one point we have a for loop to go through this entire given array and we do the comparison we play the game it says we play the array game we'll start from the first and we'll start from the second element which is index equals to one and then array length i plus so we do the comparison if this the current one that if the current one that we're iterating r is greater than the winner that means this is the new winner so we'll use this one as the winner we'll overwrite the current winner value with this one and win times is going to be one because we have finished one comparison we play the game once with the current winner so win times is going to be one otherwise what that means is the current winner regardless which one that is still the winner so in that case what we're going to do is that will increase win times by one that is what it means and every time after we do this we want to check if wind times is already greater than or equal to k if that is the case we can just return winner we can just return the winner boom because we have found a number a winner that has one consecutive decay times at least k times already and in the end we can just return winner this one will help us with the first case that we just discussed when k is much larger than the number of distinct elements in the given array then it must be the max number in that case we can simply return the winner in this case now let's hit submit and see all right accept it and the time complexity of this algorithm to solve this problem is simply o n we only need to iterate through this given array only once you see there's only one for loop all of these operations are constant space complexity is one we haven't used any actual memory all of these just a couple constant variables it takes constant time so that's why it's all one that's about this problem i hope it helps people understand this if that is the case just do me a favor please smash that like button that's going to help a lot with the youtube algorithm and it helped me out tremendously i really appreciate it and i have accumulated quite a few legal tutorials of videos or algorithm or data structures in my playlist so feel free to check it out hopefully i'll see you guys in just a few short seconds and don't forget to subscribe to my channel as we continue to go through a lot of interesting vehicle problems or algorithm or data structure problems all right i'll see you guys in just a few short seconds thank you very much
Find the Winner of an Array Game
build-array-where-you-can-find-the-maximum-exactly-k-comparisons
Given an integer array `arr` of **distinct** integers and an integer `k`. A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to the end of the array. The game ends when an integer wins `k` consecutive rounds. Return _the integer which will win the game_. It is **guaranteed** that there will be a winner of the game. **Example 1:** **Input:** arr = \[2,1,3,5,4,6,7\], k = 2 **Output:** 5 **Explanation:** Let's see the rounds of the game: Round | arr | winner | win\_count 1 | \[2,1,3,5,4,6,7\] | 2 | 1 2 | \[2,3,5,4,6,7,1\] | 3 | 1 3 | \[3,5,4,6,7,1,2\] | 5 | 1 4 | \[5,4,6,7,1,2,3\] | 5 | 2 So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games. **Example 2:** **Input:** arr = \[3,2,1\], k = 10 **Output:** 3 **Explanation:** 3 will win the first 10 rounds consecutively. **Constraints:** * `2 <= arr.length <= 105` * `1 <= arr[i] <= 106` * `arr` contains **distinct** integers. * `1 <= k <= 109`
Use dynamic programming approach. Build dp table where dp[a][b][c] is the number of ways you can start building the array starting from index a where the search_cost = c and the maximum used integer was b. Recursively, solve the small sub-problems first. Optimize your answer by stopping the search if you exceeded k changes.
Dynamic Programming
Hard
null
743
Hey guys welcome to take dola I am Nivedita and this video they are going to solve network delete time so this problem I have given you what I have given here I have given a network of and not which has been leveled from 1 to and Till is fine and one is giving you the times list here, the to -do list which has the value you have -do list which has the value you have here, what is the source, two heavy drips, dark red and blue time dominance, it will take you w time to go from u to b. Okay, so what we have to do here is that we have given you a source note, what we have to do here is to check that note, all the notes are given here in the graph, all the notes in the network. We have given the maximum time to reach there, what is the maximum time it is taking to reach the farmers, what is the maximum time, what should you do, is it okay to fine if there is such a note that it is not able to reach there as far as this note is concerned? Whether it is there or not, understand that it is okay if you send something obscene from the email that was given to you and this is a directed note, so it is possible that it may not go on any note in that condition if the diet connectivity is not connected. The signal will not be able to survive till this note, right, so what do we have to do in that condition - make it 110. Let us understand this problem through an - make it 110. Let us understand this problem through an - make it 110. Let us understand this problem through an example. Here we are fine, so look here, assume that you have been given an example of 4 notes. You are taking it on the first name only, you have given me three and food is okay so here how is it connected to seven is connected 273 is connected three to four is connected okay Soudh What have you seen here that with this note you What has to be done is to fix the maximum time. Okay, here it takes one to 123 to reach two to seven and one to eat from two to three to four. Okay, in the morning you will reach to two to seven in one time, two to three. To reach till 1304, you will need two only to eat one more till then maximum, in this graph, how much two will you need, then this will be your two final answer. Now let's see the case of minus one, there is no jam, first look here, one is taken, okay here. Took two and took free here ok so how to connect it what do we do here we connect 102 then we also collect it 133 * collect the remaining teams also collect it 133 * collect the remaining teams also collect it 133 * collect the remaining teams okay now we do more source code source note we What to do with school tattoo, now we can go from two to five, we can go right from two but we cannot go less than two seven because the director note is dry, it is connected from here, no, from Chitvan to two, continue seven is not correct, so we cannot go here. No, the department cannot go till 101, what will we have to return here - if we have to do 110, then - if we have to do 110, then - if we have to do 110, then how will we solve this problem, let's see here, we will solve this problem by using the benefits, okay then we will use the face, first of all I will Have you given today list and what will we do? We will add it. Okay, now what will we do? We will turn off a batter. To enter here, first what criminal is she taking as an example that I am happy here? Write copying of children. What is said here is that 271 is connected, okay, this is to you, this is the poet and don't understand w any time, this forest of w.app is looking from the ancestors, okay to this forest of w.app is looking from the ancestors, okay to this forest of w.app is looking from the ancestors, okay to go to two seven, okay then your What do you have to go from him to the head, what is that time, okay, then what is ours to go from three to four, one time, okay, so what will we do with the one who gave us this time issue, it is okay in the form of Twitter. What will we do, how will we start it, what will we do here, we will store it in the script and tractor and also in the stomach, and what we will do, we will store it, okay, it will appear, we will store it here, the proof of doing will be vector, such a tree. We children, then we have broken it. Okay, then what will we do? Here's another one. What will we do? Let's take one here in the gallery. This chunri will see that the source node is our source node. How much time did it take to reach in years i.e. 2723? much time did it take to reach in years i.e. 2723? much time did it take to reach in years i.e. 2723? How much time is it taking to reach 2101? How much time is it taking to reach 24? Then what will we do about this? What will be the maximum that will be obscene? What will happen to us? What will be the answer? So how much is the total here? Your total is yours, this is your note, you have been told that the level done from one to the end is okay, so what will we do, we will take likes and shares up to one pan plus one, okay then knowledge up to n plus one E4 Plus If we take this till five then zero is 1234. Why are we taking it here for five years so that we can get the label? If we look at the showroom of Intex, if we get from one to 100 then definitely we will have it in the next one which increases from zero to next. So what will we do, we will fry till plus one, okay 1234, so now what will we do, we are going to use gas, it will thank us here because it is right to use it, so what do we do here because take it here, okay fuel only, I am here, okay now If we shift to two, what will they do, why won't we insult you and what will we do, let's see, and this is what you have taken here, what to do with it Omex, we accept that right now we are not feeling the maximum, it is taking maximum time. It's okay, we will release the internet connection, okay done, then what will we do, let's juice it, now we will start it, why not and how much time will it take to reach it, so what will we do from here to this here's maximum Now what will we do, see if it is connected, we will see that it is 12321, we will see that our destination is Gaya, then to see Mitthu Seven, first look here, how much time is it taking to go from 12 to Fasal 2727, till 202, whatever. Was that I have so much attachment to come to two seven, one, now we have got one jo mara timing in it, this is the timing and we have come out, we will compare it, is one jo hai less than maxis, is this maximum effect, then whatever value mara will be made from this. It should be less, otherwise it is less, what will you do, remove it from here and put one and what to do there, add 1.5 inches to Mohan, okay then he will die 1.5 inches to Mohan, okay then he will die 1.5 inches to Mohan, okay then he will die from here, we will remove whatever is the topper element. Then whoever is dependent on it will see the type. In this, we will see from Pintu, we will see from three, how much will it take to go to 223, juice till end, zero from two to three, commerce plus one, our total time will be the same, we will compare from here. What is one, is it less than this, no, is it less than this lineage, no, I mean, what will we do here, because of updating this, I have updated it with that, then what will we do, then we will add inches to this also here, okay Okay, we will do it inside, I will be the first to give both of these from one place and no one is our navel, we will cut it from here, will we see for this earth or will we see for TV, are you on the side and If so, how much will it take for us to go from three to four, how much did it cost us to go from two to three to 143, will you do Vansh i.e. OnePlus One or not, now it will be cut, okay let's Vansh i.e. OnePlus One or not, now it will be cut, okay let's Vansh i.e. OnePlus One or not, now it will be cut, okay let's see if this is less than this, I am less here, so what about here? Will update to go updated quid here next updated Saranam Prapadhe can do so we will see look here now it depends on us whether Saran and we have visited is standing or not, how will we check which We took the note here, nor here we made it OnePlus One size, what will our note be from one to the end, nor what will we do, once we take it, we will check till the end, there is no maximum left here, if there is any maximum, there must be do it means What is it must not have happened, right visit has not happened, mark it, what will we do - we will make it not happened, mark it, what will we do - we will make it not happened, mark it, what will we do - we will make it 110, if given, if there is no maximum, there will be no left in it, then there must be some maximum number, that maximum number will be our answer, so here But you will see, if you have a mind which is 182, then the maximum number is cut to two, then what will you do, here you will return two, if you do the right vision, then it is yours, now let's see that it checks for this, see here, what will you do? Whatever you might have made earlier, there might be something which is less than the maximum, so what should we do in that condition - we will take two sources what should we do in that condition - we will take two sources what should we do in that condition - we will take two sources here, if we take one, then we will definitely visit both, but we will think here. We will take two, okay, so first what do we do with it, if we take a broken person and end it, then he and Sita can go less, we can go less than two to three, so what do we have from here, I don't feel like timing one. Worn in here Sharma - going to make because in here Sharma - going to make because in here Sharma - going to make because you are the one who took the tukun source, okay, to go to the other contractor, we have our forest to break from the forest, and what is ours to go to 153, they are okay, what do we do now? Source code will do two to four. We do the chart first. Let's take it here. Right signal that the size explosion will be till yen plus one, that is, for 80, we will see. For one, how for two, it is okay for MP3 so that what I get is just. Let's get the interest till the head. Okay, Khan, we will take plus one size. Hey, then what will we do. Why will we take one? Okay, why will we take it? So what will we do now? Here is the source code for two, so take this note. So what will we do with you, first of all we will put it inside ma'am to the maximum number, from us it is okay from the maximum number, if we start from pm2 then we will lick it, then we will put two inside here and also what is the value relationship here. We will reduce the maximum to zero. Okay, it will be necessary to go to friends, what will be fashionable, you will be free to go from like to Delhi, but what will be zero, to know well in advance, Vande Rakha 1, add one here. It will be okay, now we are comparing it, why is it less, where is it less, so we will do it here, if you pick it up, you will do 3 sets here because the shopkeeper has nothing, now is there any number of Mr., is there nothing, now is there any number of Mr., is there nothing, now is there any number of Mr., is there no one here? Otherwise it will not be found anywhere, if shown, we will see that there is no such thing, we will enter it because I have entered, because there is no circular, then it will not be fair, why I have already entered, now we will come to this from forest to TV. In between we will check is there any maximum what is the condition is this one maximum left date mill dhyave - hona ka return ok now let dhyave - hona ka return ok now let dhyave - hona ka return ok now let us come to the code understand the code right so now see what we have done in the channel we are on the back cover If we had taken it then they will turn it off, they will take the signal to the maximum, where we will send the note and what can we say in the press, will we take it in plus one size, what will we do with the internet, will we slide inches, we do with the internet, what will we do with the internet, will we slide inches, also liked this, got it on withdrawal. So we are here that we can speak on South children, okay, what will we do after that, look here, this time size has been given, now this broken time has been given here, okay, we will install it here, which I have given here. But we have taken it on the voters, on vectorvector, okay, so see here what we will do, here whatever will be your first, here you are taking it, look at this here, hey, what is this hair, which must have been given to you. I have given like this 162 I am looking at the forest, what will we do, we will take it out, okay, we will take it like this and we have taken this tree, okay, we have taken it, now what will we do, I am doing it here that we are times is rolling i.e. the first times is rolling i.e. the first times is rolling i.e. the first element. After that, we are setting these two trees like what should we do, so what will we do here, sell everything or comment on the graph, after this what will we do, why will we take it, okay, why will we take it, why will I set something and what will we do? We are taking single here, how to start here, for this thinking, what we will take from here and from is doing operation, for how long will we do it till our why MP is done, then what will we do first, quarter inch from here and first We will take it out on the stage, we will copy it and then we will see which trees are connected to it. Okay, we will take which trees are collectors and then we will see what happened first, what is in the stomach, what is that Bigg Boss element. Decide that destination note. Right destination is noda next and second is its time here we are arranging here what destination are we free destination and it is boni's time so we will be first who will be our first this destination will not be enter my time So now what we will do is till Aravan time and find the travel time for that note, then send signal to friend i.e. to 4, then definitely there will be Pawan, i.e. to 4, then definitely there will be Pawan, i.e. to 4, then definitely there will be Pawan, next load time, this is the destination and time of the note, we will add on both then we We will compare what is on that note, what is on the next note, is it less, then what will we do there, we will update it and why not go, we will add inches, we will set the destination of that note and what they will do. Is it next or is our destination nor any other Evernote, can you say it is ok then you will do this, update this operation that until the work becomes MP, then finally what will we do, which is single here, we have made it from mind to end. Till now we will check whether our maximum number is no more intimate or not, if it is there then test that condition - * Test it there then test that condition - * Test it there then test that condition - * Test it there, otherwise what will happen is that the maximum number till now that we get in that body will be reduced to medium. Here we will point out. K and Maximum elements will be defeated by the Congressmen. Okay, now let's run the point. Here's what happened, we will worship it, we will submit it. Okay, I'll wrap it up. Rat, thank you.
Network Delay Time
closest-leaf-in-a-binary-tree
You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target. We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`. **Example 1:** **Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2 **Output:** 2 **Example 2:** **Input:** times = \[\[1,2,1\]\], n = 2, k = 1 **Output:** 1 **Example 3:** **Input:** times = \[\[1,2,1\]\], n = 2, k = 2 **Output:** -1 **Constraints:** * `1 <= k <= n <= 100` * `1 <= times.length <= 6000` * `times[i].length == 3` * `1 <= ui, vi <= n` * `ui != vi` * `0 <= wi <= 100` * All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.)
Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
705
That in this problem with design this set a problem has been cleared in Google interview servicing problem statement will also seen in general water colleges how to reduce colleges in the improvement of and subscribe statement soon without using any building and 285 rates on her private function but Subscribe incentive this festival duplicate values ​​subscribe festival duplicate values ​​subscribe festival duplicate values ​​subscribe must subscribe to share pill values ​​of point note to share pill values ​​of point note to share pill values ​​of point note on key value services develop into mystery loot check person and suggestion unmute available to remove a key value from the has set delicious specification soft c what is hai singh subscribe Like subscribe and share and subscribe system that all good qualities of table is time set needle with points enter value is award internal leaders to calculate satisfaction in general is sindhu six this cream and what we integral light came when a string of words he will Do to take medicine and converted into its quality k and subscribe 1m college channel subscribe now to one to e-mail minus one and in minus one let se hai main e-mail minus one and in minus one let se hai main e-mail minus one and in minus one let se hai main itself is the number of but it is a very simple function for r Model of the banyan tree whose intercourse in tears after 10 ranger sudhir will take mode of this dried molu in some cases - 142 mode of this dried molu in some cases - 142 mode of this dried molu in some cases - 142 that you size in his last in the first individual soul first converts into to interest in this will not need you will you subscribe to That Android to contingent convert setting they give one range ranges from CO2 and minus one listen and subscribe but the responsibility of multiple input school map to the say not show in general if you have more number of subscribe multiple the same whose subscribe to a Politically Correct Work Next According Marriage To Interact 216 States Air Pressure Day Extremes 31 Miles 261 Game Morning Vid U That Chaudhary How Will Address Collagen Problem So Will Come Back To Withdraw This College Person College In This Tomorrow Morning Input Tax And Its A Disk Amazing Dr To Functions Channel Ko Subscribe And Subscribe To Subscribe Our The 100th Call Set Chinese E Will Just 100MB Will Use This One Only Power Solution Soft Chain Us Weakness of A Creative Restless Surajkund Chinese Craft Busy Schedule Subscribe Must Subscribe and subscribe the subscribe to a separate responsible and there meters back pain of missing ooh tomorrow morning simplex method in open addressing his is linear programming sources means explorer Subscribe to the injustice will not meet channel like this but they are doing everything value in this a great just global largest number of minutes so let's say subscribe robbers on Thursday subscribe channel subscribe to sea for bollywood city members this calling A problem with a research positive Praveen Ko Hai Convenience Things Will Fall On This Entry Are Searching for Free at Max Player Good Value Suzy Don't Return for That But Instead You Can Access Point It Also Provided Support from Extreme Cases Blank Space Invaders Did Not Exist For Removing But While Removing The Gross Revenue Subscribe To General Secretary Forestry Vikram Hair Vidmate Location Respond Open To Vitamin Falls But Smart Collector And Junior And Senior Just Removed From Value From Withdrawal 12th Science Possible Subscribe Like And Subscribe Diy Ocean K Superstar Singh Gill Map Doing Today Its End Difficult Job School Decide Subscribe Decide How Much Loot Ki A Main Suraj Hua Madham Active Voice And Yes You Can Study Award Is Method Detail Subscribe Prohibition Do Subscribe Table Number One Drops Video Subscribe That In Context of facing is load factor vital statistics for stable and stiffness in over key entry total number of countries and subscribe one slot factor will be given to us 60 90 this material load factor lakshmi 1000 v2 v3 lord 0670 pimple water after alleged in general And Fighting Game's Load Factor Is Process Points 150 A Heart Which Has Been Study subscribe our Channel Please subscribe and subscribe That Team Management And T20 Doctor Sam Day Take Care Number Of Butt SIM Number Of Mid-Sem Care Number Of Butt SIM Number Of Mid-Sem Care Number Of Butt SIM Number Of Mid-Sem Sudhir Pressed Towards Research On The Topic Do 121 Ahmed Raunak Preserving Electronic Point 250 Another Case Of Observing Do Not Disturb And 1622 Mein The Sun That This Order Time Taken Her Will Be Ne Are Not Very Superlative Will Be Not A Good Day Function Steven Is Not During Elections In West Oil The Various Is Very High For Online Factory Singh Sudhir V Subscribe Now To Receive New Updates Comeback Problem Egg Content Every Vid Oo Hai And Fifty Thousand Any Problem Active Will Have The Values ​​In Range Of Threshold To Medium Values ​​In Range Of Threshold To Medium Values ​​In Range Of Threshold To Medium Number Of Operations Is 120 Maximum 1000 Form In Total To Maximum Number of medicines can be 1000 Maximum number of cases can be set up in 1500 Number of valves in this case Load factor Maximum appointment for organs More than six-seven hours Maximum appointment for organs More than six-seven hours Maximum appointment for organs More than six-seven hours Singh Time Want to build a network Its eyes and define the Victor of Twitter Turn Off Cent Are Called But It's You Can Also Take Leaders List That And Wen Jia You Can Think Of It Is List Of List That In Python A Stranger Is Infested Are Least They Can They Find Something Like This Sweet 0214 Note Fuel Vid oo one bear all mp initially morning aravind shirt wave in food should be increased in rain zero 225 g subject one model is divine kit size tours and equity shares in directions not sold this latter operation different size of china to improve idea of ​​good habits and to improve idea of ​​good habits and to improve idea of ​​good habits and united Distributors Evently Is Vighn Number Its Complete Total Number Of Doctor Subscribe Video Subscribe Length Lee Which Hour Idea So It's Present Already Been Victims At It's Not Present Scientific England Suggest And Define The Synonyms In Fact Witch Content A Inside Bhar Loongi Present With First Find its effects after but it doesn't want to meet its Radhe ji Kar do hai aur number kat do hua hai kar do hua hai ko pure constructor in the divine power and function so will define this singh function so they Can do handsfree hour model number one private nursing subscribe 21 a that in this function and not need to change in unison solid int yo honey singh all in all its function and point is the return key molu a number of hits on hua hai and suresh bhai balwinder angelo 2149 ki is find aap sabhi ko to but i ki and jupiter 200 box is not being in the service of them will and on hua hai main abhi want to loot ki shiksha this is equal to hai but say daughter And What Is The Key Was Not Want The Institute Of I Am Being Done With And Next They Want To Remove Pimples And Tomorrow Morning Find This Function Lakh Effects Equal To Difficult To Win The Removed And He Will Need To Know The Twitter The Amazing That sugar is equal to but I don't exist without doing anything in this is very simple sentence the sweets and unlike was not want to Be written for its true spirit term hai tu hai to yeh cancer department contact center news indore swift content generated amazon insert a hai but in van into fine surplus orchestra MP3 aaj hum jis match so let's submit inside solution is accepted no what will oo Do ki Bigg Boss use list hai you can play list private list sunni everything list hai MS Word work adjectives hua ki try with ease and see which means first you can play with the number of the crescent with something in Java Flats for Rent Flash Lights patient should be taken report kar do hua hai main reviews remaining list area of lists 200 bhains ki peeth s40 android hua hai a new list number its a main in english vipin singh ki surya not initialized me but subah have created a group of Data Play List of Cities But They Never Were First Time Setting To Do We Need To Improve Incident Quick Pull And First Time Withdrawal Winner List Is So Is But I Who Is Equal To Null Din A Bucket Say Equal To New That A New Link List of Winners The Sweets Ine Silai Sunao Ki And Kar Do Hai Tu Insited Of Mind Will Have Ajay Ko Hai But Its Eyes At Index Of Those In Least They Can Search For Giving Ki Fee No The Land Of The Return - Mother Was Written In The Field of which is Of The Return - Mother Was Written In The Field of which is not equal to minus one sweet 16 present here tomorrow morning not meet win32 that sui a sports minus one should not present to be introduced in morning website and similarly remove this video channel the returns it is not present but it was not mean that lies mid-way return mid-way return mid-way return that this normal person we this index not able to minus one is one day but it's I that dot remove yesterday morning chemistry made redmi variable em well done next contents 220 but size null and are but I don't the index of is That which is equal to minus one that in both cases where to return for that on that aims were return to that in all it's strong and yes is Amazon it a that and works so according to Let's Summit elected on that we got Times 11:00 Seconds that we got Times 11:00 Seconds that we got Times 11:00 Seconds website is to select mic quarter inch and not be changed its rear seat number 103 fever that know it is now not accepted as blood boils and changes swell times primed you can play with different values ​​and a guy at least see the play with different values ​​and a guy at least see the play with different values ​​and a guy at least see the whole earth decreases the Number of but its grammatical fuel Vishnu avatar change a great time with love-light change a great time with love-light change a great time with love-light shining in them yesterday morning create and play list for fifteen thousand votes a famine in add morning Neetu final function face function that this note of these not just don't a bucket psi effect no dav institute so it's present win32 editing similarly in that removing that it's present danveer mooli other vice president s hua hai [ hua hai [ hua hai [ appreciation] that its sprinter return fruits return for that so countless matches so inside let's submit first service updated on
Design HashSet
design-hashset
Design a HashSet without using any built-in hash table libraries. Implement `MyHashSet` class: * `void add(key)` Inserts the value `key` into the HashSet. * `bool contains(key)` Returns whether the value `key` exists in the HashSet or not. * `void remove(key)` Removes the value `key` in the HashSet. If `key` does not exist in the HashSet, do nothing. **Example 1:** **Input** \[ "MyHashSet ", "add ", "add ", "contains ", "contains ", "add ", "contains ", "remove ", "contains "\] \[\[\], \[1\], \[2\], \[1\], \[3\], \[2\], \[2\], \[2\], \[2\]\] **Output** \[null, null, null, true, false, null, true, null, false\] **Explanation** MyHashSet myHashSet = new MyHashSet(); myHashSet.add(1); // set = \[1\] myHashSet.add(2); // set = \[1, 2\] myHashSet.contains(1); // return True myHashSet.contains(3); // return False, (not found) myHashSet.add(2); // set = \[1, 2\] myHashSet.contains(2); // return True myHashSet.remove(2); // set = \[1\] myHashSet.contains(2); // return False, (already removed) **Constraints:** * `0 <= key <= 106` * At most `104` calls will be made to `add`, `remove`, and `contains`.
null
null
Easy
null
764
hey everybody this is larry this is september 9th the ninth day of the september leco day challenge because that's how you count stuff uh hit the like button hit the subscribe button join me on this card let me know what you think about today's prom largest plus sign um yeah remember join me on discord come hang out nine days and we'll do it for the rest of the month and maybe beyond because i've been on a i don't know how long my streak is anymore it's like 520 days 530 days something like that um so i'm gonna do the math from april 1st of last year not a joke not a another april fool's day thing but anyway so terry's problem is largest plus sign so you give an integer n plus n grid sum once and you find the largest plus does it have to be just length one or like can it be i guess my question was that like can you be a two by two or like a two by two plus seems like that's not the case um okay and this seems pretty okay i think in a dynamic program kind of way um and you know so let's go over uh some stuff real quick uh so n is less than 500 what a minus that length what's n again n by n grid what are mines uh mines are basically the grids of the ones okay that's a little bit awkward right i thought they were just gonna give us the grid um okay oh they want to give us your zeros okay i mean that's fine too but same information so now you have a 500 by 500 grid um let's see i mean there's a couple of things we can do right um i think the thing that i'm thinking about though it may not be the most efficient but somewhere but the same idea but um an optimize optimized version of that is probably gonna be the idea i think we can just start with just constructing the grid 500 square should be fast enough and as long as we have a 500 square technique and that should be fast enough right where 500 is the size of one side um so the naive algorithm is just that okay you have 500 by 500 so then now we just go up down left right from each cell each possible one and then calculate it right in the worst case however this is going to be 500 cube because it can go all the way up for each one and that's going to be too slow but with some optimization with some memorization we can actually do this in n squared time and we'll kind of look at this in a sec hmm yeah and i think that should be okay let's at least get it started and if it takes too much room or takes too much time then we can up figure out how optimized i think the thing that i always say is that you know don't prematurely optimize that's one and the other thing is that uh the thing is that on python in the code is a little bit awkward because in the code specifically the running time for time limit exceeded is the sum of the test cases right so it depends on how many test cases you have so 500 square maybe i mean it will definitely be good for one test case because you have enough time but maybe that's like a thousand test case then that's not fast enough and that constraint of course is not given to you in the constraints so you have to do some guesswork and hoping work and whatever it is that you need to do um but yeah okay so let's actually start by creating the grid i like my ends to be uppercase just for consistency so let's change that and then we set everything to 1 times n for so n by n grid of once and then now for x y and minus we just said grid of x y is equal to zero right okay and i'm going to do this recursively though maybe it's a little bit inefficient and that does create some um additional core stack uh um overhead but i think that it'll be easier to kind of understand how uh the problem so that you can optimize this in the future but anyway but i'm gonna keep it in a way such that it's easier for me to explain and teach and then we'll see if it's fast enough and then we'll talk about some things that we can optimize for if it's fast enough or if it's not fast enough and then we'll play around right so then now we'll just to do a naive algorithm right so let's do the naive algorithm which is that for each cell let's just do if grid of x y is equal to one you know we do you know we yeah in theory you do something like for l it's in range of l or something like that and then you know you basically um go up down left or check up down left right um and then you can't just keep going and then um until the first no good right so that'll give you the answer for sure so you know you might have something like return best is equal to zero um if this is the case then we um yeah if let's see with grid of yeah grid of x y i mean you have to do all four directions right so something like this um if this is equal to zero or this is going to be i mean you could actually write another for loop i don't know sometimes i go back and forth from whether this is worth another for loop but um but you have something like this essentially right and then if this is the case we break otherwise best is to go to max of best l plus one i think uh yeah and actually technically i think you should start here no i mean this should be always be true because of this thing so yeah so that's good maybe you don't even need the if statement in that case but let's actually also put in the other test case i guess the other test case is actually useless but um why do i have invited syntax oh i missed an or but i think i also have a mistake here which is that this goes out bounce obviously um and we'll see in a second when we kind of run it uh i meant to actually put that in but um yeah so x plus l is um i guess this is very annoying actually just to for learning purposes um so yeah so anyway let's pretend this works for now because i you know we're not going to go over here but basically the idea for this is that you know you just go kind of like a breakfast search uh kind of thing where you go up a step left right up down a step and all at the same time right if this is out of bounds or if it is zero we break um i didn't want to outbound this one again just to be clear in case you're joining in now for some reason uh and i would say that you should stop this live so it's a little bit slow just fast forward or watch enough asset speed but yeah so this is going to work let's just say that's going to work right um however this is going to be of n this is all of n and this is of n and that's going to be of n cube right so what can we do well we can for example this is we do all the dimensions at the same time right um so maybe one thing we can do is that we can do one dimension at a time right and what i mean by that is checking up independently uh for example uh you can have something like this and then this is just you know check up though technically you know uh yeah and then you would have to do some additional logic to kind of get the you know like maybe up max is equal to zero um and then this is up max's you know in increased by one and then here we check left um or something like that i don't know i guess technically left would be minus but yeah uh and then left max you know he goes to one someone like that right i'm not gonna do the other one two because i'm lazy but then at the very end uh but this is just for illustration anyway uh this is gonna be uh best is your best of the min of the up max left max right max oops and down max something like that right so yeah so let's just say you know some dot here do the same with check right and down so the thing with this now of course is that you know we didn't change anything this is exactly the same which is kind of what we want so this is n cube still so we didn't change anything just to be clear um okay so then what do we want to do next the thing to take advantage of is noting that you can actually count these backwards right um so this up max for example up max is equal to if you want to think about this recursively up max is just equal to um one plus uh get up max naming stuff is tough of x minus one y right something like that i think maybe i did my here wrong this actually goes down here it's not how you wanna do it but that's the idea right um yeah so basically going up is equal to one plus the max of going up of the step that uh of the cell that is up right and you can do the same for left oops right uh now left max is equal to one plus get left max um i guess this is x minus one right max and i guess i should be consistent and a half camel case hang on uh one plus get right max uh x of uh lm plus one and then down max is equal to one plus get down max of x plus one y right uh let's also correct these so far still we have not changed anything it is still n cubed um let's just say that you know this is these are recursive functions um and i guess to be clear um the more clear way maybe instead of kind of writing it like the way that i did to be honest um it's just to kind of do this but for the x y coordinate right um so yeah so then i'll get up max from x y will be equal to you know one plus get up max of um x was it minus one to go up and then y um assuming of course the base condition of if um was it with minds of x y oh no not minus of x y but with grid of x y it is one well if this is zero we just return zero because that means that um yeah that means that you can't go up anymore right so that's basically the idea and then here we can do the same thing for left and this is of course a little bit awkward uh in that we're writing four functions of course one for you statement uh direction um i'm not gonna go over the technique now but you can actually combine them into one more generic function if you like but uh and there's a couple ways i can do that but i'm not going to do that for this video just because um you know i'm trying to keep it for beginners to be this technique of basically now we what i call um you know writing a loop ins for with tail recursion instead right um yeah of course we have four of them uh you know and i actually messed up here so i forgot to check for banks again so i will have to add that in day down of x plus one y and this is of course um so yeah so this is just uh and we can actually use a decorator to if you're familiar with python we can actually have a decorator that checks their inputs not going to do that for now because decorator syntax is very confusing for the beginners and me to be honest as well now i mean it's not that bad but it is hard to um hard to kind of understand for beginners so i'm not going to do that um with respect to decorators but i know if you're a python enthusiast and specialist you'll be like oh why didn't you just use a decorator i know i just wanted to kind of get this on um anyway let's run this code wheel so quick i think it should run unless i have an additional typo somewhere uh it might be slow but it should run okay well up dog oh wait huh i messed up the in the statement let's see if this is um if this is not true then we return to zero whoops i was talking about doing it about that greatest that i got distracted and forgot yeah if this is not true or this actually messed up again basically if it's our bounds or the their minds in it then we can just do this right um i would also say that you may also notice that because we only use the grid to check this and this we actually could also have put all the mines in the set i know i just kind of try to keep it simple but yeah so you can see that this works um the only issue is that it's still n squared right say um so this should probably time out i mean it might actually be fast enough but given enough test cases it would not be fast enough but um i don't know it yeah it is too slow so basically the other thing to notice is that um now that we put intel recording notice that these functions have a property that makes it memorizable and why what is that properly that is the problem is that for every single input we get the same output right because that doesn't change any time so for every same input we get the same output and that same output is um yeah and that's the same output it's deterministic and there are no side effects so you can you know you can just uh memorize is what i would say uh and this part is a little bit more annoying to write as well because i'm trying to do it for learning reasons um but yeah so then here you can just write up uh let's just say like one time or up cache maybe um you can write this in a few different ways uh i am i've already spent you know 15 minutes on this video and i'm a little bit tired because it is really late where i am so otherwise i would maybe even go over this in more detail but as a result uh this is just easy right so here i just choose a value that is impossible um i don't usually do it this way to be honest especially for learning i think the way that i usually teach is have having two different um two different uh storage one for writer the cash assist and then another one for the value i'm just being a little bit lazy today so excuse me but you know it's a little bit late i just there's a lot of copy and pasting doing i'm doing it uh and as you know as some of you might notice i'm doing it this for learning purposes or teaching purposes but more particularly otherwise um yeah i would not probably have done it i would probably do this you can yeah as an upsell but you can probably do this all these functions and maybe six seven lines of code maybe a little bit more maybe ten lines of code at most um see if you could challenge yourself to do that but yeah uh otherwise uh yeah or you can write this in the other way which is that this is if this is one negative one we update the cache and then we just return this um yeah so that's basically the idea for the up cache um and of course uh we do it for the other ones as well so this is going to take some time to do pretend this is a montage you could fast forward play some music in the background some copyright music that i'm not going to play and pretend this is a montage you know like uh and then that maybe that will uh keep it fun but anyway you see what i'm trying to do here this is just caching um yeah um and you could cash to zero as well but that's a little bit more awkward uh at least in this case it doesn't generally matter because that's you know it's an all of one check and i wrote the wrong one uh so buying typos that's pretty much all we have for this one though um i might need to i'm gonna go over the complexity real really quick but even then we're pretty much the way there let's run it again yeah and you can see that this is much faster still a second is a little bit slow a little bit discerning but it should hopefully it gets us fast enough from that we have to do a slight more optimization um i mean i did this kind of for visualization for teaching but yeah um so let's give it a quick submit and hopefully this is fast enough if not i'm just gonna be sad because that should be fast enough oh no we're gonna be too slow hmm that's sad i mean and this is only sad because as we kind of demonstrate uh for every input we are going to be fast enough but it just depends on how many test cases they have for us only 56 but i guess if a couple is uh longer than that this is already too long um yeah i think um how do i want to do it so and the first thing that you get uh so let me go over the complexity real quick just for learning at home um and you know all four of these functions are the same so i'm just gonna go over one of them uh it's just in a different direction but basically you know you look at every how many possible inputs there are right so x can go from zero to n y can go from zero to n so that means that this is o of n squared input each input takes over one time and each um input takes over one space so in total it's gonna be n squared time and square space right um and then times four because you have four of these but that's still the same big o um and of course that makes each of these function calls or one so combine this with the oh and square loop in total it's gonna be n squared plus n squared which means of n squared um so the n squared is going to be fast enough but um i think we just have to do some fixed constant speed of things um to kind of make this run fast enough um we are we do pass all the test cases it's just i guess the recursion is sometimes too slow uh and it is what it is but yeah and you can do that by instead of doing uh tell recursion we can do it um with an explicit stack i suppose but yeah i mean i think we can just write it but basically with the same idea right we just basically we have this idea of a cache and then we keep going up until we can't and then we come back down so let's uh let's do it that way but here we just unroll the loops so here we go um okay how do i want to write this so then we just go for l in range of um one two and say it doesn't really matter because if we break earlier but this is just annoying too right let me think about this for a second hang on i mean a couple of ways to do this as well there's also you can do it backwards if you're really smart um with respect to like it's almost like um pre-processing the prefix sum so pre-processing the prefix sum so pre-processing the prefix sum so here what you can do and i think that's what i'm going to do because i'm too lazy to kind of make sure all the edge cases work for what i'm doing but the idea is that okay instead of counting um from the ones we count backwards from either the edge or the zeros and then pre-calculate everything right and the pre-calculate everything right and the pre-calculate everything right and the way that you can do that is just by one at a time this is slightly a bit messy as well but we'll do it um so yeah for x is in range of n for y is in range of n um then here now we start at x y and then um go down right or go yeah we start x1 and we go down i'm going down meaning x plus one and then x plus one would depend on the end zone x right so here we actually have to rewrite the loops a little bit at least the way that i like it um just to i mean it's actually for this form i don't think it matters but it does come into play in other things actually and then here we our base case would be zero because that's the longest length assuming that it is whatever um is zero good enough yeah let's just say it is right and then here we just have to start at uh this is actually yucky as well but yeah now we check to see if there's zero well if this is equal to one then this is just basically the base case right this is going to be one um l is this is equal to zero so i guess you can actually rewrite this as up cache of zero y is equal to grid of zero y right so this starts up this first row and then now for every row we look at the previous row so then now we can do x um well let's just start at one so then now x of y is equal to up cache of x minus one y right um so this is now just calculate the up backwards um well no sorry this is well so if grid of x y is equal to one then we add the previous row um else then this is just zero right because this is zero because now you don't have the longest streak going basically you're just doing strix backwards um okay and then now this is going to be up what up cash get it okay fine but uh but yeah now we do it backwards for the other ones as well so here we look at the last cell so n minus 1 y is equal to grid of n minus 1 y and then this is also kind of just annoying to be frank but um this is basically the same thing as what we had before and to be frank this is also pretty much exactly what we had before anyway uh except that this is now kind of bottoms up uh if you want to play with those terms was hoping to go asleep a little bit earlier a bit left wait okay yeah i think by default it should be zero anyway so but always good to initialize but yeah so hopefully this makes sense what i'm doing right now but um this is actually not a hard problem but i think i chose to teaching well but uh but now it's costing me a lot of time and also like i said earlier um a lot of why this is a little bit silly oops is um is because we don't know the number of test cases for each individual test cases this should be fast enough uh let's run this real quick so before it was at like 9 47 let's see how uh hopefully this speeds it up by significantly oh whoops i forgot to uh update this part but this is just up cache of x y left cache of x y write cache of x y down cache of x y oh well i mean on a good note this is faster but on a better worst note it is the wrong answer and i think i just forgot to add a plus one yeah because i think i assumed that this already had one because usually i pre-fill it with stuff in the grid but pre-fill it with stuff in the grid but pre-fill it with stuff in the grid but um but we don't do that here so i think i just forgot to do a plus one should be okay though um now let's see if this is fast enough um oh yeah oh it's way faster why was it not as i mean why does it trace so much let me take a run again yeah okay i don't know but yeah you could see that this is uh three times faster so let's give it a submit and hope this is good oh maybe because it's just errors i don't know it's a little bit weird but yeah this should be at least three times faster so we'll see yeah so this should be good enough that's actually i don't usually take a look at timing but that's at least for this one take a look at this real quick it takes three seconds so i think actually our original solution was way close um to being ac but apparently not that yeah just slightly off um so yeah and there's still optimizations that you can make but i'm gonna stop here and here i think the complexity i'll go over it again but it should be more straightforward in that you know this is n squared that's obvious hopefully um this is also n squared so everything this is gonna be n squared times n square space i think one more optimization that you can do is knowing that i don't know if this is not sure that this is going to be faster though to be honest it just saves this n square but you can actually put mines in a set it depends on the number of mines you have and 5000 is actually a very sparse table that we have and as a result you can actually put in a set to do lookups i don't know if that's gonna be that much faster it really depends on the input size um or the basically the properties of what input they give you so give it a try let me know what you think let me know how that works out um yeah that's all i have with this one let me know what you think uh took a long while to this one but i hope that's okay stay i hope that you know you're learning from kind of all these routes that i took with this one anyway that's all i have stay good stay healthy to good mental health i'll see you tomorrow see you later and goodbye
Largest Plus Sign
n-ary-tree-level-order-traversal
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ 1_'s contained in_ `grid`. If there is none, return `0`. An **axis-aligned plus sign** of `1`'s of order `k` has some center `grid[r][c] == 1` along with four arms of length `k - 1` going up, down, left, and right, and made of `1`'s. Note that there could be `0`'s or `1`'s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for `1`'s. **Example 1:** **Input:** n = 5, mines = \[\[4,2\]\] **Output:** 2 **Explanation:** In the above grid, the largest plus sign can only be of order 2. One of them is shown. **Example 2:** **Input:** n = 1, mines = \[\[0,0\]\] **Output:** 0 **Explanation:** There is no plus sign, so return 0. **Constraints:** * `1 <= n <= 500` * `1 <= mines.length <= 5000` * `0 <= xi, yi < n` * All the pairs `(xi, yi)` are **unique**.
null
Tree,Breadth-First Search
Medium
102,775,776,2151
99
um hello so today we are going to do this lead code problem uh it's part of it called april daily challenge recovery binary research 3. so the problem says we get a root of a binary search tree where exactly only two nodes of the tree are were swapped by mistake and we want to recover the tree so that it respects binary search through properties basically the left side should be smaller than the node and the right side should be bigger so we need to convert without changing its structure so we get two examples here um one three two so this node 3 here is bigger than 1 although it's in the left side but it's in the left side so left side should always be bigger than the node or the root and then the right side should be left side should be smaller than the node and the right sides child should be bigger um and this is violated here and so when we swap them we get the properties um that we want which is left side smaller right side bigger if we take a look at the second example here you can see 2 is to the right of 3 but it's smaller than it so these two are out of order so you can see it's not always just the direct child and the parent here for example four is good because two is smaller than four but three is not uh two is the right child of three but it's smaller okay and so if we swap the two we get a valid binary search tree where the node is always has sloth child smaller than it and just right shoulder and bigger than it so that's the problem now how can we solve it well the simplest solution right is to do inorder traversal and that will give us a sorted array and then we can just check in that array we can sort get a sorted version of that array and just replace all the node values with um with the sorted version um so yeah this one is like uh expensive because it's overlapping solution we need to sort the values but it's really straightforward so let's do this straightforward solution first and then we can go to a more optimal solution so um the first is we will just collect a list of nodes using in order traversal and then after that we just solve the values and then we assign to each node the right certain value okay so yeah this one should be quick and really simple to code so first we'll just draw in order that collects the node in the right order so usually to collect the values we do something like this in order well we go to the left go to the right and then collect values and to collect values the simplest way to do it is just um it's just to do plus node val we could have like a property on the class called the values independent to it but it's easier to just do this so we can do that and then return if node is normally reached at the end we can return empty list so that the concatenation here works um but what we want is to change the value in the mode itself and so to do that i will collect the nodes instead of just the node value okay and so now to get the values so first let's just have the nodes as in order of node right and now to get the sorted values of the nodes we'll just do sorted on the values which is uh node for nodes in nodes right for node in nodes so this will give us the values inserted of them now we can just go through all the nodes and modify them so that they are in order their values are sorted and that will give us what we want so to do that we'll just go through the range of length of sorted values or of the length of nodes doesn't matter and now for each node we want to assign to it the sorted value at i and so this we don't bother ourselves with finding exactly where the mistake happened we just update everything to have the sorted values um and that will give us a bst because the bst the inorder traversal gives us a sorted list so we just do that and that should be it um okay so which looks like we have a small issue here this is this should be plus here uh yep yes we should pass through it okay it looks like there is a small issue somewhere here so we got the sorted values um and we got the right in order traversal we called it okay sorry yeah we shouldn't replace the node itself we should replace the node value this is the right way to do it okay and now if we submit this it should pass okay so that passes um but this is not ideal like we are not finding the exact two things that we need and this is also all vlogging and like because of sorting um and we have open space and so how can we improve this um so one way you can do this is let's just find the mistake in the um in the array of nodes instead of while traversing that will make this simpler so how can we do this um uh yeah let's go to the uh drawing board and see how we can do that um okay so let's take two example arrays um arrays and you can imagine those others are just the node values right so if we had let's say 1 7 4 5 maybe 2 9 10 right so if we take a look at this array what is the problem well we have here 7 is bigger than 4 this 7 should not be here um 5 is also 2 is also smaller than 5 so it's messing up the sorted order so this one should not be here if we swap these two we'll get um we'll get 1 2 4 5 7 nine ten so we'll get a properly sorted array if we just swap these two the second example is so this is an example one if we take a look at the second one it's so here the mistake is in non-adjacent non-adjacent non-adjacent values so um so in that second example let's take for example maybe a 2 7 9 something like 30 um 10 and then maybe i don't know maybe 50 here okay so what is the problem here um well you can see that it's just here these two if we swap these two these are in order to add seven and nine so it's increasing until 30 and then increasing for 10 and 15 but 30 and 10 if we swap these two we get the order back the right order so if we do that we get 2 7 9 10 30 uh 50. so we get again the right order um so with their example what we need to do is just we need to find the place for the first mistake and the price for the second mistake right and here the first mistake is here and then the second mistake is here so how can we do that um in for just for an array so what we can do is just loop through the array right and since we want to compare every element with the next we can just go through the length of the array here but we'll start from one because so that we can check the previous value and so what we'll do is just check if let's say this is an array so i'll check if the value and before is bigger then that means there is a mistake there if the value is bigger than array of i then that means we found the first mistake right but since we want so let's initialize our first mistake to maybe minus one let's say our array only has positive values right so what we want to do in addition to checking the values we want to check that we haven't assigned yet our first mistake because otherwise it will assign the first and second mistake place to the same variable right so if this is equal to -1 which means it's not equal to -1 which means it's not equal to -1 which means it's not assigned yet and the previous value is bigger than the current value then we will mark that the first mistake happened at position i okay i minus one sorry and so in this case we won't find okay um seven is bigger than four first mistake is at position seven for the second mistake it's after we said the second mistake the first mistake but we still need the values to be the previous value is bigger than the second value well what should be the index for the second mistake so here um we have that five is bigger than two and the mistake is actually at two so i minus one i so the mistake is at position i well look this is the main idea is that the first mistake it's the value where the mistake happens is that i minus one the second mistake of the volume where the uh mistake happened is at position i and so what this means here is that we can assign second mistake position i and this is the main idea here is that the second mistake is at position i in the first one position i minus one and if we swap those two we'll get the proper order and this works also for adjacent values so we'll find okay 30 is bigger than 10 this is i minus 1 this is i so we'll assign for mistake to first mistake to i minus 1 and then we iterate and we find okay for i minus 1 for 10 um we'll find so 10 is smaller but 30 is also bigger than 10 but here we would have um sorry we just need to adjust this a little bit without doing enough because if we do announce then we won't assign the second mistake what we need to do this is i minus one and this is i so once we assign it we'll find okay it's also bigger so we will assign i to the second mistake so first mistake would be this second mistake would be this one this is for the case where they are adjacent um so this is the main idea now this is for an array now for the for our case where we have an array of nodes that we can just get an array of nodes like we did earlier within order and then just apply the same thing except now um first mistake um will be pointing to a node um a second mistake will be pointing to a node um so yeah let's do that um in encode and see how it works um okay so let's modify our uh function that we did earlier to uh do the same thing that we did for another in this conceptual explanation here so we no longer need to sort but we still need to go through the array of nodes in the same way we did for an array of numbers we'll start from one and now we will need two things to store the first mistake and the second one okay and since we will put um in distance there we can just have minus one okay um and now we will check if uh the in the notes at position i minus one in the same way that we did for the array but here to get the value since it's a node we need to do that val if it's bigger and for our case pst because we are considering equal to be out of order we will do bigger or equal and then for the nodes at position ida val now if this is the case we need to check if the first mistake is not assigned yet which means it's equal to minus one then we need to mark the first mistake to i minus one like we said earlier otherwise um or not otherwise but in any case we want the second mistake to be at position i right we are not doing enough so that we can for the adjacent to the case where the mistakes are adjacent we want to set the first one to i minus one and the second one to i so we can swap both adjacent values and in the other case where they are separate by some distance um then the we'll first assign these two the one the element and the one next to it and then in this in another pass we'll find the second mistake and we'll assign it to i okay so that's the idea here um and now once we know the positions of the mistakes we can just swap and so nodes at position first mistake in python we can do the swap this way and so we'll just swap these two right and so that would be um here in the first one is we swap both essentially and that's pretty much it so if we run this um okay it looks like we have a small problem here so we have the first mistake second mistake we go through the list and we check if the values i think is just because the indentation is not working properly um yeah so actually what we want to change is the values right sorry about that i want to swap out the values because if we swap the nodes then we'll swap the children as well and that's not what we want um okay so let's run this and let's submit and that passes test cases um okay so now a slight thing you can do we don't need to keep track of the indices we can actually just keep track of the nodes themselves so we can just change these to be nodes instead so this would be the node at position i minus 1 and this would be the node at position i and now um since it's nodes we don't need to do to get them we can just do the value like this hopefully this makes it easier to understand and with this um so here we need to check if not first mistake which means basically if it's none okay so that should be good let's check okay so that passes um okay so this solution actually is open um because we need this um it's over time and over in space we need this nodes uh array uh how can we get rid of the node array then um so i'll do a couple of changes to this here to make it easier to transform to um to a solution where we don't need um an array so uh so all i'm going to do is mark this so this is the previous value right in the traversal in the inorder traversal this is prev and then the current node is this right so this is current and this is pref and so first mistake was signed the previous value and the second mistake was sign count right um and so now let's just make sure this still works okay looks like still does okay so now you can see what we are doing um this is the inorder traversal right but this is where we are processing the node and so we can just try to put that here while we are doing the traversal a couple of things we need to do we need first mistake second mistake and previous pointer but since we are doing the circus of function here to simplify it for us we'll just make these properties for the class so let's just do self that first mistakes of the second mistake and we'll need soft.pref need soft.pref need soft.pref okay and we'll do in order we no longer will need to collect the list um let's just comment this we'll still need to swap in the same way at the end so let's just keep that except reference the new property values okay um and now we'll go here we no longer need to return a list we just return and we no longer need that list okay so here we'll process instead of adding okay so we'll need to process the node here and what we said is that we just need this is the processing that we had before and so let's just replace this with the value so now what secure and current is just the current node we are processing so that's node and this would be self.proof and node and this would be self.proof and node and this would be self.proof and this would be the current node okay so we are doing the exact same thing um when the value is bigger we want the first mistake the position at the first mistake to points to the i minus one position which is the previous value and the second mistake to point to the node itself or the i position and that's exactly what we are doing here um and now we need to update prepare right before we were assigned it in the list to the previous value but here it will be the previous it will do the next call so we need to update the prev what should it be it should be just a node right the next call will just you use the previous value we'll process it um and then here we need to point to the right variables so solve that first mistake and solve the second mistake and same thing here um and that's pretty much it we just translated this instead of doing it in the for loop i'm doing it while we are traversing um and now this should be enough um let's just call in order root now after we initialize the values okay so if we run this here we need to check to make sure that we have a previous value and if we use all examples submit and this passes test cases um one thing you might think here is that okay why doesn't too many class variables here can we do better um it's harder to do better with the recursive version but we can do it with the iterative version and so let's write out in order first in iterative way and then update it to have this processing that we did here so comment the recursive version and we'll write our alternative version so for the iterative version in order is pretty straightforward we have our stack um and then now for these two we no longer need to them to be self because we are not doing a recursive solution so let's just put them back like this uh and we need our current node to point to uh root or our node point to root let's call it current that's easier and now while stack or current okay basically stack is after we push all the left side it will have elements and current while we are to traverse initially stack is empty but can't it's not um and so here we will go all the way to the far left so this is just in order um with in iterative way so here we need to append each node and then here we process and we do current equal to countdown right so this is the template for in order traversal um in an iterative way okay so now we'll just do our the same processing we used to do here except now this needs to be if pref um and we just get rid of all the soft values that we had before and to place node with karen because that's what we are calling it now um and this should be it um yeah and this should be it pretty much so this will go all the way to the far left and then push to the stack and then we take the top most left with the top left element which in this case would be the leftmost element check if it had a process it check if it's height has a right node process that node and the slope children and keep going like that so pretty much the same in order as the recursive version um and then the processing here is checking if the previous value and the current one are out of order if they are detect the first mistake or detect the second mistake um and then at the end just swap so we no longer need to call our recursive function and these are no longer sub values they are just properties of the function so we can remove that and let's find this um okay it looks like we have just something with the indentation here cool um okay so current is going to be equal to oh sorry for the processing here in the in order traversal we need to pop from the stack and that will be our current because when we exit this while loop right current is none and that's why we exited and so we need to pop together leftmost element uh that we haven't processed yet um and so if you're on this it should work i'll submit okay and that passes test cases and this solution is um in terms of time complexity we do um at most the number of elements in the tree um and we are not using extra space only these three variables um sorry we are using the extra space for the stack but we have to for in all the traversal but we are not using any other extra space um yeah i think that's pretty much it so you can see with the um iterative version it's easier to not have all of these self dot value variables um and global variables essentially yeah so that's pretty much it for this problem thanks for watching and see you in the next one bye
Recover Binary Search Tree
recover-binary-search-tree
You are given the `root` of a binary search tree (BST), where the values of **exactly** two nodes of the tree were swapped by mistake. _Recover the tree without changing its structure_. **Example 1:** **Input:** root = \[1,3,null,null,2\] **Output:** \[3,1,null,null,2\] **Explanation:** 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. **Example 2:** **Input:** root = \[3,1,4,null,null,2\] **Output:** \[2,1,4,null,null,3\] **Explanation:** 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid. **Constraints:** * The number of nodes in the tree is in the range `[2, 1000]`. * `-231 <= Node.val <= 231 - 1` **Follow up:** A solution using `O(n)` space is pretty straight-forward. Could you devise a constant `O(1)` space solution?
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
1,773
hi my name is david today we're going to do number 1773 count items matching a rule this is an easy level problem on lead code and we're going to solve it in javascript so the prop rating pretty much says as a summary it has a function that takes in an item and this item is an array of strings see in a very and uh this items the items are an array is an array consisting of arrays and these arrays inside of it consisted of strings there you go so here but it's pretty straightforward how to explain it this one is a foam blue pixel this is computer civil lenovo and what else this function takes in as a rule key and also a real value and it wants to know that whatever the rule key is and the rule key can only be three options the type color and name and these correspond accordingly so the type corresponds to the first in index zero of the item the color corresponds to the index of one in this one and the name comes with the index of two in it and that's the rule so the rule tells you which index you have to look at and then the value says what's the value of that has to equal to so for this one the rule key is color so color is here so the first index will so we'll look at the first index here and it has to match with the value silver so only one of them is a silver so i can't pronounce that and output is one so that is what it's asking for this fun little problem so first we want to what do we need to do we want to create a count variable okay next we want to have a condition for rule key and so there will only be three conditions to be let's do an other to be type so this is in this we will have to loop through items and condition if so i um when we the type if the rule value is equal to the index 0 of each item inside of here and then if it does you'll have to increment count and basically we do the same for the other ones so the next one we have color and this will be index of one and now we copy this and do it one more time name index 2 after we do all these conditions we what do we return count okay now let's play the code that count starts off at zero next we have the conditions if rule key equals type we loop through items for that i equals zero i is less than items dot length i plus if items i as we'll loop into each item and then we're gonna have to look at the index 0 in it is equal to rule value we increment count and basically we do the same for the other ones so we can just copy and paste two three and i'm going to change type to color and this one will have to change to the first index since we should be fine now this one we change that to name and this won't be the second index and lastly we return count great so we got it so the complexities time complexity we know that we're looping through items so we of n and the space complexity we're creating a count as a constant variable so we 0 1 and that is how you solve this problem thank you
Count Items Matching a Rule
percentage-of-users-attended-a-contest
You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`. The `ith` item is said to match the rule if **one** of the following is true: * `ruleKey == "type "` and `ruleValue == typei`. * `ruleKey == "color "` and `ruleValue == colori`. * `ruleKey == "name "` and `ruleValue == namei`. Return _the number of items that match the given rule_. **Example 1:** **Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "lenovo "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "color ", ruleValue = "silver " **Output:** 1 **Explanation:** There is only one item matching the given rule, which is \[ "computer ", "silver ", "lenovo "\]. **Example 2:** **Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "phone "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "type ", ruleValue = "phone " **Output:** 2 **Explanation:** There are only two items matching the given rule, which are \[ "phone ", "blue ", "pixel "\] and \[ "phone ", "gold ", "iphone "\]. Note that the item \[ "computer ", "silver ", "phone "\] does not match. **Constraints:** * `1 <= items.length <= 104` * `1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10` * `ruleKey` is equal to either `"type "`, `"color "`, or `"name "`. * All strings consist only of lowercase letters.
null
Database
Easy
1338
1,603
hi everyone so welcome to the channel so we will today try to solve this problem known as design parking system and this is a very famous problem it's been asked in various companies like Amazon Bloomberg and Uber so let us try to read the problem statement first it states that we have to design a parking system for a parking lot and the parking lot has three kind of parking spaces big medium and small with a fixed number of slots for each side each size so we have to implement the parking system class and the parking system comprises of integer big into medium and it is small and it initializes object of the parking system class the number of slots for each parking space are giving given as part of the Constructor we have a Boolean of add car int card type and it checks whether there is a parking space of car type for the car that wants to get into the parking lot and the car type can be of three kinds like the big medium or small which are represented by one two or three respectively a car can only Park in a parking space of its car type there is no space available we have to return false else the park in that else the park the car in that size space and we have to return the true so as you could see that this Boolean is asking for false and true and we have to use this public parking system uh a Constructor and inside it we have an integer big integer medium and end of small so the input example will look something like this that input of parking system then we have a add car and add car so initially what will happen that uh when we have one two and three so one two and three are the car types which we have so it will give us the output that we need to do and uh one is true 2 is also true and three is false reason being the space availability now uh we can check for the constraints that is 0 is less than equal to Big medium small and less than equal to thousand and car types could be one two or three at most thousands call calls will be made to add cars so it's in limit which is given to us so in simple let us try to understand this that how we will initially try to build up the logic which and the variables which you are needed so definitely we'll be needing this integer of big limit and then we'll be needing this medium limit same like this we will be having a small limit after that we have a in tough big count I have to directly code it in the lead code only because intelligence it's not possible due to the limited inputs and this small count so we have declared our three variables which we are needed now let us just try to pass it over here this of Big Dot limit this dot big limit is equal to big this dot medium limits equal to medium and this dot small limit is equal to small initially we will take our sorry let me correct it initially we have to make it three values as zero of this big count medium content small content of big count is equal to zero end of small count is also equal to zero and same like this print of medium count or I can just copy it is also equal to zero let me just cut it and paste it over here to maintain the consistency okay now all the other things we have to do inside this add car function only so we have card type of one two and three so according to this we have to code it now if car type is equal to 1 then we will check our condition that if this dot big count because it's in big curve we have to check for the big content only no other things we have to do and we have to check the limit also always the count should be less than limit if the condition is fulfilled then we will just simply increase our big count now we will return true over here that yes car can be added and after that we have to put on our or we can say add on our else condition otherwise we will return false over here so this will be the same thing we'll be doing for all the other three as well let me try to just copy this sorry and this okay so else if card type is equal to 2. instead of big count we will using the medium count now here and also here and instead of big limit I'll be using medium limit over here okay so we have added this as well now just let us try to do it for the third one small count and small limit here and change the card type is equal to 3. okay let me try to read this once everything is correct or not okay we have to add the else over here else car type okay I think this else we are not doing anything else so we can just simply use the else we have to we don't have to write the uh card type in the last condition because obviously if it's not 1 and 2 it will be three only so if it's small count is less than small limit then the small count will increase and we will return true otherwise it will be false and if car type is 2 then medium count is less than medium dot limit okay medium count will increase return false return true okay I think we are good to go now let me remove this extra code over here and also this one okay let me try to run it to see if there is any of so there was only one case present over there so it is passed let me try to submit it okay it's in submitted answer and it is running in and good uh time like it's in seven millisecond run time and it beats 99.9.6 percent of users which are 99.9.6 percent of users which are 99.9.6 percent of users which are so yes thanks for watching that's it for today and you can just use this solution for your answer bye for now
Design Parking System
running-sum-of-1d-array
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor. * `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`. **Example 1:** **Input** \[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\] \[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\] **Output** \[null, true, true, false, false\] **Explanation** ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); parkingSystem.addCar(1); // return true because there is 1 available slot for a big car parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car parkingSystem.addCar(3); // return false because there is no available slot for a small car parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied. **Constraints:** * `0 <= big, medium, small <= 1000` * `carType` is `1`, `2`, or `3` * At most `1000` calls will be made to `addCar`
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
Array,Prefix Sum
Easy
null
141
hello guys welcome to algorithms made easy today we will be discussing the question linkedless cycle in this question we are given the head of the linked list and we need to determine if the linked list has cycle in it or not in the first example as we can see the linked list does have a cycle so we return true in the second example also the list has a cycle so written true while in the example 3 there is no cycle so written false there is a follow-up problem with the there is a follow-up problem with the there is a follow-up problem with the equation which we'll see in the later part of the video we need to find if we have encountered the same node previously or not so in order to do so what we can do is we can store the nodes into some data structure and then check if we have already have that value in the data structure or not so we can use a set of list node to store all the values we'll iterate on the linked list till its head is not equals to null then we see if the set contains the node or not if it contains the node then we directly return true otherwise we need to put the value into the node and then we move this head to the next pointer if we ever get out of this value that means the link list doesn't have any cycle so we directly return false outside this while loop when we run this code it runs successfully let's submit this so it got submitted successfully the time and space complexity in this approach is often as we are using a data structures in order to store the node values now the follow-up the node values now the follow-up the node values now the follow-up problem with this questions ask us to solve it using our fund memory that is constant memory so how we can do that there is a straightforward algorithm that we can use which does the same thing that we need without using any extra space the names algorithm is floyd cycle detection we have already discussed the implementation and how the algorithm work in one of the videos wherein we have solved the question find the duplicate number on lead code so you can check that out if you want to understand the algorithm and its implementation now we will briefly talk about it over here and then we will proceed to code it the algorithm states that we need to have two pointers one fast pointer and one slow pointer the fast pointer moves two nodes at a time while a slow pointer moves only one node at a time if we continue doing so then sooner or later the fast and slow pointer will be at the same node if they meet then the linked list does have a cycle so now let's see how we can implement that so as discussed we need to have two pointers the slow pointer which will be starting with the head the fast pointer head dot next so we can get a null pointer exception in the fast node if no node is present in the head node so in order to mitigate that we will first check if the head is equal to equals to null we will directly return false because the null list won't have a cycle now we will loop till the slow and fast pointer are not equal if they ever become equal we will come out of this loop and we will return true that means there is a cycle that exists in this linked list now as we discussed we need to move the slow pointer one node at a time while the fast pointer will be moved two nodes at a time there can be a scenario if the fast pointer can be null or the fast dot next can be null so to remove this null pointer exception we'll do a check now if the fast pointer ever becomes null that means the linked list is ending with a null node and there won't exist any cycle if there is a null node in the list so if that is the case we can directly return false from this while loop now when we run this code we get the right results let's submit this so it got submitted successfully the time complexity still remains of n but the space complexity becomes of one as we are not using any data structure in order to store the nodes of this linked list now how about the question asked us to return the start of the cycle well that is the next part of this question and we have already made a video on that question so do check that out too thanks for watching the video see you in the next one
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
495
hi i am ayushi rawat and welcome to my channel today we will discuss the september lead code challenge week 4 problem day 26 teemo attacking now let's have a look at the problem statement in lol world there is a hero called teemu and his attacking can make his enemy ash be in poisoned condition okay now given the teemo's attacking ascending time series toward ash and the poisoning time duration per teemo's attacking you need to output the total time that ash is in poisoned condition okay you may assume that teemo's attacks at the very beginning of a specific time point and makes ash be in poisoned condition immediately okay so now let's have a look at the example let's see what it says okay input is a array 1 4 and 2 output is 4. now let's read through the explanation at the point 1 timo starts attacking ash and makes ash be poisoned immediately this poison status will last two seconds until the end of time point two at the point four teemo attacks ash again and causes ash to be poison status after another 2 seconds so finally you need to output 4 okay so now let's look at the second example here we have an input array 1 2 and 2. the output here is 3 what the explanation reads at the time point 1 timo starts attacking ash and makes ash to be poison this poison status will last for two seconds until the end of time point two however at the beginning of time point two teemo attacks as again who is already in poison status since the poison status won't add up together though the second poisoning attack will still work at point 2 it will stop at the end of time point three so you need to finally return the output as three right okay now let's see what the note reads we have two points here number one says you may assume the length of given time series array won't exceed 10 000 okay and second one reads you may assume the number in teemo's attacking time series and is poisoning time duration per attack are non-negative attack are non-negative attack are non-negative okay the idea is pretty straightforward we consider the time interval between two attacks as spends in the poison condition the whole time interval if this interval is shorter than the poisoning time duration and the duration otherwise so we can break our algorithm into three parts first being we'll calculate the total time in poisoned condition we'll use total for this case and assign total to zero in the beginning then we will iterate over the time series list at each step we'll add the total time the minimum between the interval length and the poisoning time duration at last we can easily return total plus duration to make the last attack into count it should become more clearer to you once we code so let's quickly dive into the coding section first i'll calculate the length of time series here now i'll check if n equals to 0 in that case i can simply return 0 here next we'll assign total to 0 here and now i'll run a for loop over the range of n minus one now we will find total by calculating the minimum between time series 5 plus 1 time series of phi and duration and adding it to total at last we can return total plus duration here and we are done let's try running a code and now let's try submitting and it's done you can join my discord server and telegram channel for regular updates you can find the code at my github repository link is available in the description box below if you wish to connect with me on other social platforms the link is mentioned in the description box below if you have any queries or suggestions please feel free to ask if you like the video hit the like button and subscribe my channel thank you for watching
Teemo Attacking
teemo-attacking
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effect ends, the timer for it is **reset**, and the poison effect will end `duration` seconds after the new attack. You are given a **non-decreasing** integer array `timeSeries`, where `timeSeries[i]` denotes that Teemo attacks Ashe at second `timeSeries[i]`, and an integer `duration`. Return _the **total** number of seconds that Ashe is poisoned_. **Example 1:** **Input:** timeSeries = \[1,4\], duration = 2 **Output:** 4 **Explanation:** Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5. Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total. **Example 2:** **Input:** timeSeries = \[1,2\], duration = 2 **Output:** 3 **Explanation:** Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3. Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total. **Constraints:** * `1 <= timeSeries.length <= 104` * `0 <= timeSeries[i], duration <= 107` * `timeSeries` is sorted in **non-decreasing** order.
null
Array,Simulation
Easy
56,605,649
804
hi my name is Alexandra Lennon I'm experienced itself to our engineer today we will solve unique humours code words problem from lead code with JavaScript the plan for today is next we'll observe the problem and find what is meaningful for the task what is not second we will design or algorithm third will calculate complexity of our algorithm fourth we will try to find out is this algorithm efficient enough and what we can optimize here fifth we will try to implement algorithm six we will test that everything is fine and the back or code if it required and servants we check our complexity that it's the same it was originally calculated and see what findings we have during the task so let's go loading okay it's loaded so let's see what we have here we have international Morse code standard where every letter Maps two dots and dashes something like that we have an array of all the letters we have here so every word should be write as concatenation of all letters we have here so for example CBA will be resulted to something like this and we need to return how many different more the combination for words we have because the same Morse code can result two different words but I just want to mention that inverse you do some pauses between the letters to ensure that receiver understand what you are sending otherwise you will end up with something like that so we will receive for in this example four words we will need to calculate Morse code for them and see how many unique words we have in total so let me just see what constraints we have here so the length of every word maximum 100 symbol each no sorry the count of words is maximum of 100 each word will be from 1 to 12 symbols world words will only consist of lowercase letters so it might be useful to use some ASCII code later on that I had used in previous tasks looks like it related to this one also to have simple transformation so let's think what options we have here so first of all we receiving array of words let me copy this one oh it's too big maybe if I will zoom out a bit yep like this so what is a problem okay so we have these awards and we will go through every of them like this will GU go through every of them and we'll find the proper representation so for example for this one representation will be like this for the first letter we will need to find this representation and we will need to store this representation somewhere so we will store it at the start I think we will can start with dictionary where this will be K so we will use this code s key and we will check in our dictionary if such keys exist so for example we are going for first one we create our dictionaries empty so we add one symbol at the one two over counter so we have like one combination when we go with the second one the code is the same so we look up to our dictionary and found that it's already exist so we don't do anything and we will repeat this separation for how many words we have so originally we have like three steps here first step is going through array second step is transforming the world to the code okay to the code and third part is to take a look at our dictionary and check that it has like it has this word or not let's see what complexity we will have here first of all we will need to have at least one to two wearables the first wearable is length of array let it be a let me do it like this hey the second one will be no not a let it be a like array the second one will be the length of every worked let it be W so can wet what to Morse code will took to up to all W time since for like every letter we have some representation then we make join of this representation and so on and we do this encoding eight times so at the end who have something like Oh a w we multiply this because we do word encoding there count of four times can we optimize this house somehow let's think like watches the this calculation was for time complexity is how CPU is used depending on incoming data and for space complex team which is how memory is it depending on coming data we will need to store dictionary in the worst case this dictionary will have separate code for every of world so it will have like the same since for every symbol will have like encoding so we will end up with something like the same so we'll have totally same one I'm not sure that we can dramatically optimize time complexity in this case like in worst scenario since we still need to check every word we can of course cache some parts of words or words entirely but I didn't think that it will save a lot of time anyway we will need to go like through symbols to compare them and so on but for memory consumption I think we can use another structure we can use something like tree where we can store something like that we can store dot or - on every level so we can store dot or - on every level so we can store dot or - on every level so for example how we can encode this one welcome encode this one as like line dot and we have like tree like this and right now it doesn't save anything to us but when we go for a second one it will be the same so there is no big difference and in the end we have something like stars or some another symbol mentioning that this is the end so and we have the second one this one which can be stored in this structure like first single same than three dots then two dashes so instead of dot here we can store like - here and here we can store like - here and here we can store like - here and additional dot so instead of saving entire word we can go with something like this and we will store only two symbols that are different from previous one which is will be much cheaper since like on a relay level we have only two combinations and like let me think for a second we have maximum twelve letters and a lot of them will be have the same structure but like in the worst case again it possible that now anyway some at least some part of what will be reused like word start with - or not so reused like word start with - or not so reused like word start with - or not so we're at least save some space like in this part we can have only two words right two letters and this part we can have like four at the third step we can have eight so we have maximum of the first of all for every letter we need to have some combination right and for every world so 32 so like at least this part should be very common but combination after this can be differ but ok let's try to calculate what space complexity can be with this approach I don't think we will go on this video today since it's complicated a bit not so complicated but it will took time will not go away this reason if you want me to make a solution with this approach leave a comment please so what is possible space complexity here I in good scenario will have only small over overlap like in this case it will be only two symbols it's like nothing in other cases it will have words by 12 symbols and there will be like 100 words ok it sounds not so easy to calculate it properly like on the fly so I am not sure how it will differ I think in worst case we will end up with since something like that so for example what if we will have only two words like in worst case we will end up with two of them with totally different when like one of them will start with dot one of the most art which - but since count of that resists which - but since count of that resists which - but since count of that resists finit there should be some optimization but ok I don't want to stop on this now for sake of saving time so let's go for implementing or initial algorithm this one with this complexity so we'll have three steps one of steps is converting to Morse code let's go to our code and try to write something so we need to copy the array of Morse codes let me add it here oh I cannot format it well but okay so let's just save them it will be from 0 to 25 right from 0 to 25 like this so we have words and let create additional function and called it and called like what - Morse this and called like what - Morse this and called like what - Morse this function will encode the word itself to encode words we will go through every single of this work and we will create a resulting array and in the end we will join this array so Const result array the true result join all the symbols with spaces then we go through every symbol in our world let I okay and current letter getting current letter which will be a word I we need to get current char let me take a look we have only small charts right that was from conditions consisted only lowercase letters so lowercase letters start in ASCII table with symbol of 97 and up to 122 so we can remove from our chart code 97 and it will be Muppet to our coats so the a will have 97 minus 97 will be 0 and we will get the first letter like this so the method called char code app we getting char code we remove 97 from this and we get it from codes maybe we don't need the additional variable I don't want to use it no this one's still better so we get our code and let put it true result I prefer to store it in meaningful variables for easy understanding cos if I will like use something called like word I in couple of places it will be easier to miss something so we have function or tumors here we will have couple of things in our main function so the main function will go through our words will transfer work to the code which we already implement put it to some dictionary try to put some two into some dictionary otherwise not otherwise it is if it's possible to put in dictionary then we increase our counter so we have two things first one is counter which is zero and we will need to return this counter and second one is our structure which will be dictionary where we can save our keys so and we go through all our words since words is array we can use for each construction to go through every of them and we can use arrow function here so by this construction we took every word from overwrite so for example we have array like this so what will represent like jeans and geek message and so on so for each of them we will called work to mores function here we will have more representation we will take a look if our structure and is our structure have this Morazan tation and if it doesn't have less mean not we will increase our counter by 1 and we will add or worth here s key and just true so generally that's all let's try to run our code and see how it will work so at least for this one output is exactly like expected let's try to run ok its success work faster and so on everything is nice so we solve this problem now we will need to see what complexity we have here you can set and pause and try to calculate complexity by your own so let's start with space complexity and time complexity so with the space complexity so we have two function functions so first we will calculate it for inner function for this one so first space complexity we use result are originally at least the same length as word so it will be au n there is no nothing else is stored and resolved in the antis Kinkaid choose drink for time complexity we have this cycle which go through every letter in word and get proper code so our everything inside the array is just 1 it's simple operation nothing special but cycle itself make o n so let's go for this one so space complexity and time complexity first of all we have just one structure here so everything will be around this one for count of keys here it will be all I have had used two variables a is array and we W for the word length so Oh a kiss we will have totally so up two words length and you Ricky will be a string up to all W of length since this one have space complexity of Oh W so we put all w8 x so we have all a multiply W and for time complexity this cycle is oh a so we go through every word so this itself took a time and this method took all W time so it will be like again we got same o AV nice so what we had solved asked we had calculate or complexity it's the same that it was expected initially again if you want me to explain more about structures like this and make great video regarding to that said likes comment and don't forget to subscribe and set like just for this video what findings we have here is that we can easily transform any symbol to Mars with just simple mathematical operation if we have array of these symbols or of course it's possible to have some dictionaries with like a equal to dot dash and so on it will be same easy but since we don't have it initially I don't want to spend time on creating it and if the list will be really high of symbols it will be harder to represent so I think that's all thank you for watching have a nice day
Unique Morse Code Words
rotated-digits
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: * `'a'` maps to `".- "`, * `'b'` maps to `"-... "`, * `'c'` maps to `"-.-. "`, and so on. For convenience, the full table for the `26` letters of the English alphabet is given below: \[ ".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. ", "--. ", ".... ", ".. ", ".--- ", "-.- ", ".-.. ", "-- ", "-. ", "--- ", ".--. ", "--.- ", ".-. ", "... ", "- ", "..- ", "...- ", ".-- ", "-..- ", "-.-- ", "--.. "\] Given an array of strings `words` where each word can be written as a concatenation of the Morse code of each letter. * For example, `"cab "` can be written as `"-.-..--... "`, which is the concatenation of `"-.-. "`, `".- "`, and `"-... "`. We will call such a concatenation the **transformation** of a word. Return _the number of different **transformations** among all words we have_. **Example 1:** **Input:** words = \[ "gin ", "zen ", "gig ", "msg "\] **Output:** 2 **Explanation:** The transformation of each word is: "gin " -> "--...-. " "zen " -> "--...-. " "gig " -> "--...--. " "msg " -> "--...--. " There are 2 different transformations: "--...-. " and "--...--. ". **Example 2:** **Input:** words = \[ "a "\] **Output:** 1 **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 12` * `words[i]` consists of lowercase English letters.
null
Math,Dynamic Programming
Medium
null
57
Hi gas welcome back to my channel so today our problem is insert interval so what have you given us in this problem statement here we have been given an ad right by the name interval where your interval is represented by star t. And indirect i.e. the starting time of any interval indirect i.e. the starting time of any interval indirect i.e. the starting time of any interval is the same and the ending time is the second element. Okay, and this is your add, it is sorted in ascending order. Through whose start I is okay, that is, you sort it on the basis of the first element. This has been done and here you have been given a new interval, what you have to do is to insert it in this interval and you have to keep in mind that any two intervals should not overlap each other if you want to merge. If you want to do this then you can merge but after the merge there should not be any overlapping, still no one of yours has been given in the overlap, okay so after that whatever will be your interval, you have to give it by returning okay so what do we do? Right, through rice, let us understand what is the problem and how can we solve it and this is a very important problem, we have also asked this problem in our Google, so what do we do, let's see here, see what There are two intervals, we have given 1369 and the new interval is five, what do we have to do, we have to insert it, so look here, first, what is your one and three, okay, then what is six and nine, so look at what is here, it is overlap. What is there after van? Three is after three. Here five is not four five. You are starting directly from six and have given till 9. Okay, this has been given to you and what to do with 2 and 5, you have to do inside. Here you are, where will your five and five come? Look, from here, five and you are in between. Okay, it will come this far, so this means it is overlapping. What we have to do is to insert this internal interval. So now. You can also merge, so see what is happening here, this part which is of the first interval, this part of ours, what is happening in it is overlapping right, so what will we do, we will merge this part, how will we do that, we will do it from the van. We will start but not ending from three, we will take it to five, then from van to five, the first step will be from van to 5, then from 6 to nine, so will these two intervals be related to each other? What is it overlapping, what is it not doing? What have we done here? Mars is overlapping. Okay, so one to five and six to nine, so this is your answer. You are looking at one, five to six is ​​nine, now how will we do that. Later is ​​nine, now how will we do that. Later is ​​nine, now how will we do that. Later we will see through the example, what is the problem, okay so now look here, 1 2 is given, 35 is given, 6 7 8 10 12 16, so what do we do, let's see here. Then what have you given, then from here we have given from six to 7, then from 8 to 10, then from here we have given from 12 to 16, okay in this interval, here This is what is happening in both of these intervals, so what will we do, we will merge this part, okay, so what will happen here, 1 will be 2, so this will be our starting from three, but How far will the ending be, look at the ending, look at the seven, sorry, it does not come here, sorry, for the date, there is no stomach here, sorry, it is here, so this one is including it, okay, that is, it is touching this interval also till here. So we have to take this interval together, we have to take this, okay, so from here we will start from three and till 10, we will take one interval okay and then from 12 to 16, now tell me here. Among these three, is anyone overlapping or not? After Van, from Tu to Three, 10 is becoming one, then from 12 to 16, so is it overlapping, what is it not? What will we call Mars overlapping? We do not have to insert the new interval, for that you can do merge overlapping, so now how can we solve this problem, see, here we will create two conditions, either it is possible that the new interval will merge with each other. It depends on whether it will happen or not. If the merger will not happen then how can it happen? So take the supposition man, here let's take another example. Okay, the interval we already have is 23, we have given only one. Man, okay now, let's take it from one, then we will see and then you have a new interval seven and eight, okay now what you have to do is to insert this here in this interval, so where will you do it, see you and three are yours. Pass and you know that its ending is 78, its ending is more than this, its starting, ending, automatically what will be more, it will be right somewhere on this side of it, that is, whatever you see, one thing also You have to keep in mind that what you are doing should also be sorted on the basis of the first element, so you see, in short, after van, after three, after 12, it should not be that you insert 7 first. People, and you will do this later, otherwise what will you do here, after returning the vector, insert this element in it first, okay, now you do not have any element, then insert this new interval later, people, see, you will come here. You are ok, now reverse the case and give two opposites. The interval is fine. The new interval is yours. You have to insert it, then you will know whether it is its ending or its ending, it is less than its starting, so somewhere it is If it comes on the left side, then in the answer vector, we will insert it first or we will do this first, because it is less of ours and we need it in sorted way, we will do 2 and 3 first. Now whatever new interval will be formed, it will become ours. Ok 7 and 8, but now when you go to search to insert it, you won't find any further ones, then what will you do by inserting it here, people, I just told you this one is correct, it's done, now let's take two-three examples. now let's take two-three examples. now let's take two-three examples. What do we have, then we have given 9 and 10, okay, and what we have to do is to insert 7 and 8 here. Okay, so we will start from here, see, then we will know whether this is its ending or there is more to it than this. Seven starting, somewhere it is more than this. Let's store this element in your answer vector. Finalize the interval you are going to give, take a screenshot of it first and move ahead. Still, your new interval will remain here, now it is 9. And this is 10, okay, then you will know which is its ending or not, if it is more than this, its starting, then somewhere it will be inserted first, okay, so what will we do, we will insert seven and eight, okay, we have done it, and what will we do? We will make 9 and 10 a new interval. When we move ahead, we will know that we do not have any element. So what will we do if we insert 9 and 10 here, then this will be our final answer. Okay, now we come, situation overlapping. How will it be, this second example has been given very well by us, we will do the same, okay see, when will the situation of overlapping become less when you will see which intervals are touching each interval here, as if from you There is three and take five from you, this and one of yours has given 10 from three, okay so three is coming somewhere in between, you came to know that some part of the second interval is taking the new interval, so somewhere we have It will have to be merged, okay, so what will we do, we will merge it, so how will you merge it, which is 25 and 310, so here, whichever is less in the first element, we will first merge it for the new interval and these two. Out of these, we will take the one who is maximum, we will take him because he will come till the last, he will take the maximum and in the starting, we will take the one who is on the left side, then who will be on the left, who will be the least i.e. 2, 3, who will be less who will be the least i.e. 2, 3, who will be less who will be the least i.e. 2, 3, who will be less i.e. If you are there, then you i.e. If you are there, then you i.e. If you are there, then you can do overlapping from you to 10, right, so if you want to do it in this way, then how will you solve this problem, how will you solve this condition, then I will remove it, I understand you by doing it in the second example, so What you have to do is keep watching all the conditions, sometimes they will overlap, sometimes they will not overlap, in which we will store the final answer, right, so we will take one and compare 48, one will take it, we will come to know that its which is more than the starting one. So what will we do, we will do our answer, we have to censor it, after that we will come to three and five, when we come to three and five, what is the new table we have, 4 and 8, okay, so here. You will know its ending, what is its starting, right is its starting, so look somewhere here, this is three and five, and this is 48, that is, it is overlapping, so this part, which is your new interval. What will be formed, how will it be formed, you take the minimum of these two, you are making the new interval, okay, the new interval will be yours, so who is your minimum in three and four, here is the minimum of your three, you have taken that and in five and eight Who is coming, okay 38, we will not insert this, we will see further also, maybe we will overlap further, we will have a new interval, now ours will become 38 from 48, okay this is done, now we will come to six seven, when we come to six seven here. What is pe and apne pas 3 and 8 okay now 6 7 3 8 Here also you will notice that it is overlapping six and seven and what is apna three se eight is right so this will go to the text of this so in The minimum of both will also be free. What is the maximum of both of them will be the same, so again the new interval that will be formed will be our own 38. Okay, so here also you will get the common, what is included, so that means now the minimum of these two will be only three. You will get 3 and 10, okay, so your new interval becomes three and 10. Okay, let's see further, what fire, who knows, it will merge further, 12 horses, 16, what do you have, three and 10 is your interval, so you know that its ending. Isn't it more than that, its starting means it is not overlapping somewhere, so what do you do by quietly inserting it into it, there is nothing to be done, we have now made our new interval, it will be 2016, what have we done here. We have been given one this side function whose return type is tu di vector so one we will take the answer vector in which we will store the answer OK and we will go through each element one by one interval right now we will see each element we will see First condition, if our interval which we are taking, the element which is in our interval, which is your inning, is it less than the starting of our new interval, then we will understand that it is less, then what will we do with the interval, we will insert it, then if If this condition is not being fulfilled then we will check in this condition, is our interval, the elements in the interval, is its starting greater than the last of the interval i.e. ending, then last of the interval i.e. ending, then last of the interval i.e. ending, then what you will do is you will insert the new interval and the new internal. You will update this element with the right interval so you have updated it. If both these conditions are not fulfilled then we will understand that a case of overlapping is being created then the new interval will be zero or it will be minimum. New interval will be zero and end. Interval zero i.e. New interval will be zero and end. Interval zero i.e. New interval will be zero and end. Interval zero i.e. whatever the element is, the minimum of both will be updated in the first element and the maximum in the ending of both will be your update i.e. it will be on the second element and update i.e. it will be on the second element and update i.e. it will be on the second element and this will become yours and this era when your It will be finished, you can insert it later, okay, that is, people should insert it in the last answer, I have installed mine and donated the answer here, okay, so I hope you have understood this, so what will be its time relaxation, we will If we are doing a loop then right will be on, if we are going through each element then it will be on and here we are doing extra space then on here will be space b and time complexity too so I hope you get this. You must have understood and whatever problem there is in the last 2 days, I will solve it and share it with you. I have uploaded the video of the topic related to Union Fine, so you can watch it and then you can also try because you have time right now. You try, I will post the video again, ok thank you.
Insert Interval
insert-interval
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval. Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary). Return `intervals` _after the insertion_. **Example 1:** **Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\] **Output:** \[\[1,5\],\[6,9\]\] **Example 2:** **Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\] **Output:** \[\[1,2\],\[3,10\],\[12,16\]\] **Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\]. **Constraints:** * `0 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 105` * `intervals` is sorted by `starti` in **ascending** order. * `newInterval.length == 2` * `0 <= start <= end <= 105`
null
Array
Medium
56,715
312
hey everybody happy new year yay uh hit the like button hit the subscribe button join me on discord let me know what you think about you know what you're doing this year this channel whatever it is just you know i hope you're having a good time i hope you accomplish all your goals uh people in my discord has been kind of talking about you know uh all the victories they had and just things that they're doing uh you may be wondering why at this point i am not wearing a shirt uh well it is because i'm in panama and it's really hot but also uh you know to kind of go with the mood into the intro hopefully um it's a thing i'm doing because it's new years and maybe i'll be doing it uh for special events and heart problems uh we'll see how that goes um yeah i don't know let me know if this is too much or you have fun of this i don't know it doesn't really matter that much uh okay today's problem is burst balloons uh a hard problem a good way to start of the year um just to also give a note i have a 640 day streak or something like that actually i don't really know should double check that but what i mean is that i've done the video for every daily video things for the last year and eight months or whatever the math is i don't know i can't do calculations but yeah um so if you're new to this channel you're watching on new year's because that's your new year's resolution or you just want to stop by feel free to subscribe but just come back every day come check solutions i don't always have the best but you know uh and just check it out all right uh so all the other ad stuff aside uh today's problem is burst balloon uh a classic problem that is um and i don't mean to say classic as in it's going to be easy because i actually struggled this one a lot um because and you probably could find videos on me doing it um previously including the first time i did it which not the first time but the first time i've done it in like a decade but a couple of years ago at this point um i think one thing that um one thing that i would say about uh so okay let's start by saying this is a dynamic programming problem if you struggle with this dynamic programming problem i would um not look at this one first um there's definitely a lot of things you can work on getting to this point because even though i was probably i would say like really good because people have gotten better over time but at a certain point i consider myself pretty good at dynamic programming and even i struggled because um there was certain uh mind blocks say that i struggled with just from um i don't know just from my our practice or maybe my understanding of certain aspects of uh dynamic programming including the states and something like that was uh incomplete or maybe i just didn't learn it as well as i died but hopefully this time um i did the key thing about this one that um i see myself struggling with uh at least a little bit more in the past i still kind of struggle but a little bit less um because these are things that of course with more exposure will becomes easier but it doesn't come up as often in the stuff that i'm doing now um you know lee curry doesn't get that difficult generally with dynamic programming and i honestly haven't done like hard you know more harder uh competitive programming in a while that said so the hard part about this dyna the aspect is um is that it is not symmetric um i do bring this kind of concept up from time to time with dynamic programming um and the reason is because um in a lot of things it is symmetric in the sense that you can go from left to right or right to left and it gives you the same answer you just have to you know like maybe it's plus instead of minus or something like that right you go uh both directions or if you go like you know down you know like one of the pascal triangle e things where you go from top left to bottom right well you could go from top down to bottom right or go back up in a similar way and you get the right answer for like you know let's say shortest path going in that y direction or whatever right um so there are a lot of things that are symmetric and at least for beginners or not even beginners but just like a lot of these problems by construction is um symmetric so what that means is that it lets you get away with being slightly wrong unless you really understand it uh you might not you know be you know like you know proof by ac is you know maybe good enough for certain cases but it's still you know like there is an underlying understanding that is a little bit lacking and i'm not you know trying to be judgmental because a lot of this i think i'm speaking to myself to be honest um and trying to self-reflect be honest um and trying to self-reflect be honest um and trying to self-reflect on my challenges and kind of understanding these sort of problems um so yeah um so keeping is that it's not symmetric so it really matters which way you go um so that's the only thing that i would say before we kind of dig deeper uh we're only five minutes in so hopefully you're still here if so uh leave a comment in below about your favorite balloon animal shape so i know uh so i know who's actually watching here instead of skipping ahead or skipping whatever and people should be skipping ahead if they don't find it useful um watch it on two eggs whatever you need to do but i'm just also curious who actually listens to all these stuff uh but okay so yeah uh my what is my favorite balloon animal is probably a unicorn it's just cute you know you just get it's just like a horse balloon with a horn right so i guess that's uh okay now that said let's burst this balloon um so the key thing to know about this problem is that like i said it's symmetric and then it is what i would call um that divide and conquer dynamic programming and there is a concept behind dynamic programming called um this idea of um you know you have these sub problems right you have a problem and you have to see sub problems and you have these like um uh um you have these concepts of the subproblems leading to you know uh the concept of optimality where these subproblems build up to uh the best solution um in addition to that i mean that's a lot of mathematical stuff but in addition to that i want to say that the way that i think about it and the way that i try to think about it and for me in a way it almost is easier than say a greedy algorithm in that it is just brute force with um with a couple of concepts and kind of collapsing states or whatever but an idea the kind of the mathematical concept that i think about it is brute force and trying to think about a quote smart way or clever way to prove first um because once you're able to move first um then you can prove that it is um uh if this is brute force then they're able to prove it much easier right of course there's technically speaking a greedy aspects that um that builds on top of this and what i mean by that is that um you know in this case uh you want to return max score or mass max coins or whatever and of course the max is going to be a max in this case um like the function is kind of linear um right so in that way um you know the these uh components you could separate them to the components and then max them together and in that way um of course that's where the greedy aspects come from right you just take the greedy sub components sub problems that gives you the best answer and then combine them in a way and then see if that gives you a better best local answer so that's kind of the ideas that we're dealing with these are all the concepts that i'm talking about um hopefully that makes sense i know that sometimes i tend to go a little fast but you know you're watching a video feel free to rewind or you know uh this is the internet feel free to join discord and give me a chat or in the comments or whatever right um but hopefully these things uh things that kind of um you know obviously it's not the answer but or like not only the answer but hopefully these concepts will um help you unlock understanding burst balloons instead of just like okay look um because i do see this from time to time from people um and i'm not a fan of this where they're like oh let's see the code and then the girl was like okay how did i change this code to work for burst balloons how do i change this first balloon code to look like another prom code that looks like that is similar right um and you know that's not the way to really understand it um and you know um if you really do understand it you only have to learn it once that's the grand idea that i'm presenting okay so the key thing here is um and i said this a couple of times is that it's asymmetric and what i mean is instead of thinking okay first i want to burst this balloon and then what happens right once you burst this balloon you have these sub components that you have to kind of you know merge and so forth and then the other another way to think about it of course is what we already kind of hint at a lot of times which is um doing it in reverse where it is not symmetric right where you instead of looking at the first balloon that you burst think about what is what happens if i burst this as the last balloon well if i burst this as the last balloon that means where my borders are from the left and the right um so let's say we have okay these are kind of terribly simple examples so let me expand on this a little bit and i'm just banging on the keyboard like a cat on that meme uh but yeah but the idea is that okay let's say you have a subsequence that's like okay let's just look at this subsequence right we're going to get the subprop sub solution for this sub problem right um and then here we have the left and the right and then the idea is that okay let's say we only care about this component and let's say we burst this five last what does that mean well we burst this five last means that we already burst the this problem and this problem meaning that we have a score for this after we burst them in some order like we don't know the order per se but let's say we burst these two in some order um and then we get a score from bursting six in some more well there's only one number so i guess sex uh let's say we burst that one um and then after we burst everything here and everything here then that means that we are now at here which is what we kind of look at when we want to burst the middle five last um and here then it's easy to calculate the score right it's just a score of these components um and then bursting the five will give you a score that is according to this formula and that's basically the idea and if we able to force it um then we should be okay um i hope this is okay though because one reason why i just said that is that the idea behind this algorithm is going to be um and cube um it is n choose three ish so it is actually um a bit faster than that but um but we'll see uh this is fast enough um yeah let's see um because to con because usually they do have a lower constraints and cube ones and i'm not aware that there are any quicker ones though if there is let me know in the comments or maybe we'll cheat but yeah so basically that's the concept and let's start writing you know um calculate max for range say i don't know when you have 11 decks and the right index um this is a hard problem and i know that this is the first day of the year but i would also say that if you sometimes i do explain it but this one i want to focus on um the harder components um and here let's just say that um you know you can put in the sub array that into the function but of course you'll notice that you know uh that is uniquely determined by the left index and the right index and that's why we're able to do this all right and of course just to kind of write whatever um the score for bursting uh left right inclusive so that this is the contract that we tell ourselves just in case you get a little bit weird because or if you get off by once or whatever this is the thing that i at least myself come back to um and what i mean by that is that sometimes you forget whether you do inclusive exclusion or exclusive or whatever on the bounce and it's very easy to mess up to be honest um because whether it is inclusion sorry friends uh i'm in panama right now uh and this is actually a couple of hours before new year's here even though i said happy new year so i lied but a happy thing that people do is a lot of fireworks i'm a little bit distracted by fireworks um at least the sound i don't know if you could hear that if you can't hear that's fine too but apologies for that um but yeah um but it is a key thing to keep in mind the inclusivity i mean you don't have to define it as inclusive but that's the way that i do it um because otherwise um you know it's just easy to do off by one and you know you have some function here later on what uh i just bang on the keyboard and that came out with curse how did that even happen uh but yeah you have some fun some function here that deals with the left and the range right and the range um but then sometimes you just like forget whether your inclusion or an exclusion and you have off by one so that's why i try to be careful um okay so let's see if left is equal to right then we have only one balloon left so then here is it possible to have only one balloon left i guess not um okay let's actually change this a little bit um what is our base case i guess would have three balloons let me think about this for a second i actually don't remember what i should do for the base case um i am solving this live so yeah um okay let's just write this for now and if i'm wrong then and i'm wrong um and then we could adjust but yeah um and one thing i do want to do is actually um yeah treat it as once on the coin on the ranges so without having to care about um uh you know handling these edge cases or whatever let's just you know let's just change that and of course we'll have to remember to return calculate max for a range of zero and n minus one where and as you go the new nums and of course now this is where our contract comes into place we actually want this to be exclusive so we don't actually burst the left and the right so i lied here and because of that means that if this is true then we return left plus one technically it's this plus or this multiply by left and right but in theory i don't know how i feel about this actually okay let me think about how i want to do this uh when we kind of write it out right um okay um so yeah so this would get determined by what we do here um as well um maybe i might okay i don't know this one is a hard problem i don't know but i mean it's actually fine as long as you're self-consistent meaning that as long as self-consistent meaning that as long as self-consistent meaning that as long as you're consistent everywhere it should be fine but yeah let's kind of get to it and we'll maybe play around the thing first but then yeah now we want to burst a balloon right let's say we want to uh burst the number x so we build from range from left to right inclusive so that's why i write it like this um and then now what is this right so best let's say we get the score of zero there's no negative in here right no okay um so yeah then what's the score of for getting this right it is max of best of uh calculated max for range from left to x right plus calculate max for range from uh is this x i guess this is x minus one right because this is inclusive you're not going to burst it again but that also means that this should be left plus one and this should be inclusive going in the middle because otherwise that doesn't really make sense uh and then burst it on the right um yeah and this is inclusion so this should be fine and then plus the score for popping this current balloon which is num sub x times num sub x minus one times num sub x plus one of course this cannot go around um just by the constraints that we're met with um and then at the end that's i think that's pretty much it uh i'm a little bit shaky about this one to be honest or i don't feel so good um just because of the possibility of off by ones and stuff like that um but conceptually um the idea i think it's okay i think this only goes to 100 so that was the wrong thing so let's give it a go um of course i haven't done the memorization yet so we'll look into that in a second but let's just see okay so we're doing very well um okay so um if this is inclusive then we have to burst these as well um so okay so let's actually i was thinking about how to do this but uh if left is greater than right we turn zero um so basically that means that there's no balloon to burst i guess that's better than putting it the if statement here maybe i don't know how i feel about that okay so we fixed this case which is good um but then we didn't fix the other ones uh wow i am very sloppy today i guess um why is this returning 98 did i act am i lying did i actually push some balloons i might be not bursting some cases all right let's try uh the bounce on this one is kind of tricky uh or the base case um because i think this is relatively right to be honest but this is where i'm getting wrong okay 13. so that's weird because you don't expect to get bigger than whatever so that's bursting i mean this seems right oh well i messed up here um so that's why i said it's so easy to mess up and i you know talked about it for about 10 minutes about what to do in this problem uh about asymmetry and symmetry um but i still mess it up right but of course here we're not choosing the next balloon to burst we're bursting the last balloon and when you burst the last balloon that means that all the balloons within the range is uh burst and that means that the last number is actually um left and right but now everything feels a little off to be honest so i think these may be a little bit off um but yeah uh okay i mean we're wrong but at least we're happy about it because i think now a lot of these bass cases are a little bit awkward because i confuse myself with the lat with first thing and last versus first uh and first it doesn't really quite work like this um but yeah by brushing it left and right so we have these three balloons left um here that means that we're going from zero to n minus one now yeah because we yeah okay um and then now yeah okay let me i have to recalibrate my mind sorry i we talked a lot about this and i still get it wrong so uh so yeah tell us how hard this problem is and i've done it before so yeah okay let's think about this again so okay if we want to burst these balloons this is okay uh maybe this is still zero because now this is really awkward let me think about this well in this case this is exclusive now right so that mean that means that if left is equal to right this is zero um and if this is exclusive then we want to do something like this anyway um i think this is a little bit better but um now we're just doing random stuff it seems like um but i think maybe i'm just off by something here let's see let me just for the logic right okay so we have the left um and then the oh this should be left plus one and this should be right minus one right because now we have this left and the right and we're talking about the stuff in the middle um between these things um oh no but it's exclusive so since this is exclusive it should be this now um because now we don't care about the balance see this is where um having this reminder helps because then now i could look at my bangs and be like oh no this is exclusive see so i don't have to like rethink about my strategy a little bit i just have to look at my things and look it worked out right this is why i point out that it's very important to really knock down if you struggle with off by ones and stuff like that anyway uh whether you want to inclusive and exclusive and then everything files through sometimes it's some problems is easier with inclusive and some problems are easier with exclusive um that's why sometimes i jump or you see here i jump between the two in that what is easier to represent because then you i mean it's not that much harder you just have to be consistent like i said but there'll be more if statements and so forth right um okay so of course um if you're up to here uh you know that uh you know we need to uh we need to cache this basically right because um this is exponential for each pair of numbers we do a ridiculous amount of work um so we definitely need to uh clean this up let me also just add one more test cases uh test case uh but yeah we need uh so yeah we definitely need to clean this up and of course if we just show any big enough number of these uh we can it's very easy to demonstrate right like even this it's not even that many numbers but it should time out regardless and n is 500 so if this doesn't time out miraculously over time out easily we just double it um but yeah um so the idea here is that okay for dynamic programming or memorization uh for every input uh left right i guess technically they're not inclusive so you could write this like this um we get the same answer and because of this we do something called memorization which means that if we see the same inputs again if we already know the answer we just return it that's basically all memorization is dynamic programming is a funky sounding complicated term but that's basically all it is right there's nothing really that complicated about this per se um so let's uh let's do that let's put uh cash as you go uh let's has cash is to go to force times oh what am i doing right uh and this is better to see whether we have cash and then we just you know the actual cash though of course it doesn't really uh matter because uh this doesn't really matter because um because we're never gonna use it unless it has cash so now we can do something like if has cash of left right return cash of left right otherwise cash of left right is you go to best uh has cash left right as you go to true um and that's pretty much it let's run it again obviously and yeah you can see that it happens much quicker um let's see if we could i want to see the 500 case at least once so that's 10 20 30 40 50 100 is that 100 once really two three four five and welp hmm well that's awkward did they miss something hmm just doing some micro optimizations but that is a little discerning that was 500 right i didn't do like anything really funky or anything hmm not sure what the deal is here to be honest uh 14 seconds is not really acceptable but uh huh and this actually went with my i don't know when it gets some i guess 500 is a bad way but let's see whoops 14 seconds really uh 11 seconds 542 yeah okay i don't know what to say but in any case the explanation is right even if uh lead codes being a little funky today maybe a lot of people doing it i don't know it's a little bit awkward let's see let me try something real quick so you can do this bottoms up but i don't know if that helps enough that's my problem so that's why i'm uh um let's see sorry hang on uh so i'm just i'll do an explanation i guess but uh so this is much faster i mean so one thing that is uh annoying um about lead code is that they don't really care about python as much clearly um and one thing is that functions in python are kind of expensive which is why you saw me kind of got rid of the max um but there are you know stuff that is harder to get rid of so basically what we're doing now is just converting it to bottoms up um it's not that hard but it just takes a bit of practice you it has the same logic you just kind of have to look at this function and then convert this function that we have into a for loop the only hard part about the this is kind of writing the for loops in the correct order to be honest because um we're here you don't have to care about the order in which you do the calculation in dynamic programming you do in this problem it actually might not be as tricky but um but it might be that you know in other problems you might have to look out um so yeah so let's kind of do that um the idea here is that okay we have to convert the base cases um which is if left is greater than zero but um but we start right from the left so even in that case that's not possible but if left is equal to zero then the cache is equal to zero anyway so maybe um or if left is equal to right to zero so we can start with left plus one and then for x we go from uh left to right which will which is just the same as this loop so that should be pretty okay um yeah and then now we write the same thing here but instead of calling it cache i call it dp just for my uh it's just something that i've always done so excuse me but here you can see that you know this is just you go to this thing um right so here we can set you know you go to best is equal to zero we said uh this is but of course we already did this here that's why i didn't you know but i just want to write this out so that it is you know more explicit for the viewers at home um and then now we're just converting this for loop which means that you know you have this thing uh let's just say score as you go two or coins maybe as you go do this thing which is of course um dp of left of x plus dp of x of y plus num sub x times num sub left times num sub a and then if score is greater than dp of left and right then oh it's right i make that mistake a lot not this time though at least almost not um so that's pretty much the idea uh let's wanted to see if that's right first of all and see if that's fast enough second of all um okay wrong answer but i have a typo am i doing this in wrong order uh as i said no this is roughly right but why am i getting okay at least i got the last answer right but the other is not so much ah let's see am i doing in the wrong order yeah i am doing in the wrong order am i um because basically i'm doing in the wrong order okay so then now that's annoying to convert then um so the reason why we're doing an order um is because i mean you could just kind of trace it and retrace it um we calculate this while this is zero before um before this gets calculated uh you know i think this part is fine but this part is the warm part so um so yeah okay this is kind of an annoying one too to convert but uh but conceptually we have to the functions right um how do i rewrite this in a good way but basically you want to calculate all the um other segments of size one and then two and then three and then four so that basically is the idea because if you think about it you're building it off from smaller components to bigger components so in that way um you are able to kind of do it that way this one they made it annoying but okay so then that's let's keep this here for now but now let's change the definition right basically instead of so before we said that dp as you go to a dpo of left right is you go to something exclusive bounds or whatever right um but now we want to do something like dp left and then size maybe it's basically the same thing but in a way that's easier to iterate i guess i don't need to do it this way but uh let me think about this i think i could write it that way as well but i could still do it in this idea we just have to write um for okay so then now we go for l in range sub n maybe or maybe n minus one but okay from left and then here we can do dp of left of um of left press l um let's also start uh let's start this at one right because then we want this to be a left plus one does that make sense no because um i think in our other function which we deleted because i'm silly uh technically if left plus one is equal to right um the inner for loop never executes so it just returns zero um but so it was an implicit base case even though i was not correct here but here we can actually skip it by making a two as a result um okay uh so we set this equal to zero again i know that is here a bit but uh but yeah um but of course we also let's check that f plus f is less than n which we can of course just write this here then um okay yeah um okay and then now we go for um for x in range of and then now we get set uh maybe right as you go to the left plus l is a little bit clearer uh and then now we can do the same thing as we did before we just now have it in a different order um okay so it's not always straightforward converting this is a little bit triggered unusual hopefully this is right i don't know if this is right uh my dp might not be right or like the balance of what we accept um but that seems okay for this one uh it's still so slow five seconds i mean it is twice as fast but it is also much slower um we probably could do a little bit better with this array because most of this away or maybe the most but half of it is zero so your x um but it's only 500 squared so maybe it's not that bad uh yeah okay i don't know if this is good enough let's give it some mid five second is still really slow uh apparently my older solutions is good enough maybe we'll have to convert it to another language if this is a little bit yucky but uh i guess they changed the test cases then right what did i do last time oh i did no i did it with dynamic programming last time so okay so if you want to see the memorization top down version um you know this is the explanation uh or like we had the explanation um so you can see that it used to work um it might still i don't know because even my test case is five seconds six seconds um and when i ran the top down was 11 seconds or something like that right so though if i would have timed out i guess they just add a lot of test cases or maybe they i don't know if the balance were higher or something like that um but it's a little bit awkward because i don't know and of course i didn't see plus way back when um and i did this in this really funky way because i wasn't sure about my bounds and stuff like that which is a lot of the stuff that we talked about anyway um i actually didn't see my streak because someone pointed out that i should bring it up so maybe tomorrow but yeah uh this was a very long video uh longer than i expected for a farm that i know how to sell um but hopefully the exploration and kind of the things that we talked about um it makes sense um and even though it wasn't structured as a specific det uh specific um you'll notice this is not structured as a specific tutorial i hope this was a really good in-depth video of um just really good in-depth video of um just really good in-depth video of um just this genre of divide and conquer and then also converting it to bottoms up you know maybe i hand waved a little bit toward the end but the idea is that you have to do things in the right order and yeah and basically after you convert make sure that this is in the right order by having length this way and defining it this way um everything else is the same right we didn't really change anything else um except for the loop order um and kind of made it a little bit different um so yeah let me know what you think this is a really weird one uh happy new year again everybody hope you all have a great year hope you had a good last year as well uh mine was tough at times but whose is it right um anyway stay good stay healthy to good mental health i'll see you later um and i'm gonna show you one more drone footage before i go see ya bye and i have to press the button for you to see it you
Burst Balloons
burst-balloons
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it. Return _the maximum coins you can collect by bursting the balloons wisely_. **Example 1:** **Input:** nums = \[3,1,5,8\] **Output:** 167 **Explanation:** nums = \[3,1,5,8\] --> \[3,5,8\] --> \[3,8\] --> \[8\] --> \[\] coins = 3\*1\*5 + 3\*5\*8 + 1\*3\*8 + 1\*8\*1 = 167 **Example 2:** **Input:** nums = \[1,5\] **Output:** 10 **Constraints:** * `n == nums.length` * `1 <= n <= 300` * `0 <= nums[i] <= 100`
null
Array,Dynamic Programming
Hard
1042