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
4
hello everybody it's uh Ryan power share your favorite programmer and we're gonna do today a leak code number for median of two short arrays pardon my speech at the moment I went to the dentist today got some work done but we're gonna power through we're gonna put this video out anyway so the problem we're doing today is a medium to sort erase this is actually a pretty cool problem it's a pretty challenging problem so I definitely encourage you to try to solve it first before we went all the way through this video but let's just introduce the problem here real quick so there are two sorted arrays nums wanted numbs two of size m in size and respectively so they could be of any size they don't have to be the same size so one could be smaller one could be larger one could be empty one could be full so you just have to sort of race and we need to find the median value so one assumption that we get to make here between 1 and M s 2 is that not both arrays are going to be empty right so at least one of them is going to have some number of values in them and here's some examples for us to look at so we have 1 3 & 2 the median value of this array 3 & 2 the median value of this array 3 & 2 the median value of this array here is 2 because if you put these arrays together hmm 2 would be the middle value so that's why we get 2 here so here's another example 1 2 3 & 4 so because the length example 1 2 3 & 4 so because the length example 1 2 3 & 4 so because the length of this array is an even value we actually take the two middle values which in this case are 2 & 3 which in this case are 2 & 3 which in this case are 2 & 3 and then we take the average of them so that will give us the midpoint between those two middle numbers which will give us the median so I will drop a few hints about how to solve this problem so if you don't want to keep going with the video I would solve the problem and then come back and check this out but so there's two bits of information here that are well there's three bits of information here that are really important so the first one is that the solution the runtime complexity the solution should be of log M plus n we're actually going to do it in log min of M and n um but this is a big clue here to tell you that you should be having your search space each time you iterate through with your algorithm so that's kind of a big clue there and then also both arrays are sorted so that means that they're pretty easily searchable using binary search so those are the that's the strategy that we're going to use to solve this problem so we're going to use a binary search and the fact that these arrays are sorted to find the median value so come with me to the white board and we'll check out the strategy we're going to use for solving this problem welcome to my white board I've gone ahead and drawn out an example for us to go through and what I've done here at the top is I've just merged these two arrays into an two sorted order into one array so we can kind of see all right what is this array supposed to look like and what are we supposed to be returning so the median value here is 11 so that's the answer that we're after in this problem and the reason why we're looking for 11s because we have five values on the right sorry five values on the left and five values on the right and that is going to be the median which is 11 so this is the simplest way to solve this problem which is an order n solution where we just take the two arrays we merge them into one array and then we just divide the length of the array by two and return that value at the midpoint of the array but what we're trying to do is we're trying to solve this problem in log min of N and M so the first thing we need to do is define okay which of these arrays are we doing binary search on so since we're trying to solve this problem and then log min of N and M we're going to do binary search on the smaller array so the first thing we need to do is we need to split our search space in half right so since this is a small array we'll just draw a line straight down the middle or will define the middle as B three values to the left and two values to the right and this particular circumstance and so what does that tell us so since we split this array with three values to the left and two values to the right we're saying that these three values here are going to be in this left group and we're saying okay these two values here are going to be in this right group and what we're after is what we're going to be doing is actually on these odd arrays we're always going to be putting the extra value or what will eventually be the answer in the left group so what we're looking for is a split of six to the left and five to the right so if we draw this line here and we put three values in the left group and two values in the right group then that means that we have to put this line and this larger rate can go in no other place but right here right to achieve this six left group five right group then that means that we have to draw this line here so the next thing we need to do is check to see okay is this a valid split and to do this we can look at the four values that are straddling this line okay so that would be 8 18 9 and 19 okay so we're going to define two variables here the left variable is going to be the maximum of the two left numbers which are 8 and 18 and that's going to be equal to 18 and right is going to be equal to the minimum of the two right numbers so that would be 9 and 19 so that would be 9 okay so the test that we can use to see is this a valid split is left less than or equal to right if it is then it's then we have found the place where the median exists where if we draw these two lines in these places that means we have found the place where the meeting exists if it's not true then that means we have to keep looking and it's false so why is the left the max of the two numbers and the right the min of the two numbers well if this was a valid split then that would mean if we're looking at this large right here we would have a we would were eventually looking for these four numbers right here right so the so for this statement to be true then the two values to the left of the line the maximum should be less than or equal to the minimum of these two numbers on the right side over here right so these would be our two right side values and these would be our two left side values and that's what we're looking for so we know that we've found the correct split if this statement is true if left is less than or equal to right because there could be the case where we have duplicate numbers right where maybe both of these numbers were 11 and then that would still be the median so left can be less than or equal to right so since this is not true we now need to know okay which way do we need to go like where do we need to search now so if we look at the values here we can look at the let number of the smaller a and we can compare it to the right number in the large array so we can say okay is 8 less than 19 if 8 is less than 19 then that means that 19 is where it should be it's on the right side of the line so that means we need to move our line or our where we're splitting these values and the smaller right we need to move it to the right because that means that this 18 here is part of the right group so we need to move this line over here to the right side and we need to move the top line to the right so if eight was greater than 19 or if it was greater than this number right here say this was eight and this number here was seven then that would mean that this line needed to move in the other direction right so that's how we're going to decide which space we need to search next so because 8 is less than 19 and that means that we actually need to moot our line needs to move farther to the right here then we need to now search this space right here so we need to find the midpoint of the right side and make a line such that we are finding a midpoint again so we'll do just that we'll split our line right here and that puts four numbers to the left and a 1 number to the right and so we're going for the 6 5 split here so that means we have to draw our line here right we don't have any other choice it has to equal 6 numbers so we know that we need two values from this larger array to be to the left so now our four numbers are nine eleven 15 and 18 and we'll just do our check again right we'll say left is the max of 9 and 11 which is 11 and right is the min of 15 and 18 which is 15 and we can see here that left is less than right so this is true we have found a valid spot to split our a so we know that we've drawn our lines in such a way where the median exists so how do we know which number to return well if we look at this mess that I made up here in this larger array we were we have found this spot here right like this is this what we're looking at so we have 9 and 11 to the left which we have over here right and we have 15:18 to the right which is and we have 15:18 to the right which is and we have 15:18 to the right which is what we found right here so we already have a way of deciding what value we want so if the array is odd so if array dot length um mod 2 whoa sorry about that mod 2 if that equals 0 and it's even then that means we want to return left + right / - right so that return left + right / - right so that return left + right / - right so that would mean the midpoint existed between these two numbers if our the length of our array is even so we would add these two numbers together and then divide them by 2 to get the median value if it's not even then all we have to do is return left right because we have six values here on the left and we have five values over here on the right so we just return this here which is the midpoint okay so there is one other small kind of wrinkle to this problem that we're going to go over with a much simpler example to illustrate how we're going to handle that case so I'm going to do a little bit of setup and then I will run through one more small example okay so here's the second example that I wanted to go over to illustrate kind of the last little wrinkle in this problem so this is a much simpler example we're just doing 1 2 3 & 4 so it's gonna take just doing 1 2 3 & 4 so it's gonna take just doing 1 2 3 & 4 so it's gonna take us two rounds again to solve this problem but let's kind of go through our process and when we hit the little wrinkle that I'm talking about a we can make the small adjustment to our strategy in solving this problem so the first thing so our two rays here are 1 & 2 & 3 & 4 so the first thing we are 1 & 2 & 3 & 4 so the first thing we are 1 & 2 & 3 & 4 so the first thing we do just like we did before is draw a middle line straight down the hook so we've drawn a line down the middle and since we're putting one value to the left and one value to the right then that means that we have to draw the line in our other array down the middle as well so that would give us these four values for comparison right and as we did before left is equal to the max of 1 & 3 which is 3 and then right is equal & 3 which is 3 and then right is equal & 3 which is 3 and then right is equal to the min of 2 & 4 which is two so we ask ourselves again is left less than equals to right it is not so this is false right so we then do our comparison again where we compare this number to the right value of the other array so as we saw before this value is less than the right value in the other array so that means that this number here is on the correct is in it's in the correct position it should be to the right of this line so that means we need to move this line this way and we need to move this line that way so we now need to create a search space on this side so the only other place we can draw this line is here right so that would mean that the line that we drew on the bottom array would be here right so that means that our four numbers are to this kind of non-existent numbers are to this kind of non-existent numbers are to this kind of non-existent value and then to the right we have three and this other kind of non-existent value all right so how do non-existent value all right so how do non-existent value all right so how do we handle this case where the array the way that the median works with these two arrays is that all of the left values are all of the numbers from one array or the median is basically between these two arrays right so we only have two numbers to work on so instead of what we have been doing where we just define the max for left as two numbers we have to create another case right we have to say well what if the number doesn't exist at all right so left in this case would be the maximum of two and so we'll say if there is no number there if there's not a number then we'll say left is the max of two and negative infinity so that way if there's not another number two to compare I'm sorry I'm talking about these two numbers here right - and then this would be negative right - and then this would be negative right - and then this would be negative infinity um so if there's not another number to compare with - then we want to number to compare with - then we want to number to compare with - then we want to make sure that we're always taking the number that exists so by saying negative infinity and taking the max then any number that we have is going to be more than negative infinity right so that's going to be two and then right similarly only has one value so we're going to take the minimum of three and infinity so that way we're always taking the value that exists right so this could work in a case where the Rays in this instance happen to be of equal size but you can imagine that there is a scenario in which we're take all we're putting all the numbers from the small array on the left and then we're drawing our line somewhere in the large array and that's where we're gonna find our median value right so anytime we're in a scenario where we're putting all the numbers like this like we're doing right here well we're putting all the numbers on one side of the line then we need to we need that we need to then use this infinity and negative infinity to do our comparisons for creating our left and right variables right so right is equal to the min of three and infinity which is three so we can say okay is two less than or equal to three it is so this is true and we have found the correct position in our array and like we did before we say okay is array dot length Maude to equal to zero okay in this case it is this array is even length so what we need to do is we need to take right plus left / - if this wasn't the case then we / - if this wasn't the case then we / - if this wasn't the case then we would just take left right so in this scenario we're taking two and three adding them together which is five and then dividing it by two which is two point five so you can see a drawn up here that two point five is our actual median for this array so between these two examples this is kind of the or this is the strategy we're going to use to kind of implement this into code so why don't we go to the terminal or to the repple and code out this problem to code this problem we're going to use three functions two of which are on the screen here find median sorted arrays and the other one check for median so find median sorted arrays it's going to be responsible for doing all the binary search logic and in implementing the binary search and then check for median is going to be responsible for taking the four values the left side values and the right side values and then determining whether or not the line we've drawn is a valid median so the first thing we want to do is create a size variable so the size is going to just be the sum of the two lengths of a of array one and array two this is going to allow us to or this gives us the whole length of the array and we know that half of that amount is what we need to put on either side the left and the right so then we wanted to find our helper function so the helper function is going to take a small array a large array and then we're going to define the lo and we're going to set default to negative one and then the high to be the default of the length of the array so when you do binary search the first thing you need to do is find the midpoint so we're going to grab the midpoint so that's going to be the low plus the high / - going to be the low plus the high / - going to be the low plus the high / - and then what we want to do after we grab the midpoint is check this line is this a valid line so we can store a result variable in the result variable we can just we can store the check for median so check for median is going to take an index which is the midpoint that we just calculated as well as the two arrays and then the total size so the result variable if we find the median is just going to return a number so we can just check for the type we can say if the type of result equals number then we're done just return the result if that's not the keep searching so well we need to know okay are we too low or are we too high so result if it doesn't return our number is going to return a string so if the result is equal to low then we're too low so we need to redefine the low as the current midpoint so we'll make another call to help her with this small and large array and will redefine load to be mid and we'll keep our high if that's not the case then we're too high so we need to do the same thing with our in putting our small and large arrays but instead of redefining the low point will redefine the high point so this is everything we need to do inside of this helper function to do the binary search the only other thing we need to do is make sure that we're doing binary search on the low the shorter of the two arrays to ensure that we are actually doing log of min of N and M so to do that we'll just check to see which array is longer and we'll do binary search on that one so if a are 1 if array 1 is longer than array 2 then we'll call helper with array 2 as the first argument otherwise we'll call helper with array 1 as the first argument ok so that's everything we need inside of fine medians sorted arrays so now what we need to do is to find this check for median which is going to be all the logic to decide ok is this a valid point so the first thing we need to do is figure out how many numbers we need on the left of the large array so we came to find a variable called num is needed and we'll set this equal to the total numbers that we need so the floor of the size divided by 2 minus the numbers that we have already allocated to the left in the small array so that would just be index plus one right so the current index for passing in if it's the index one then that means that the zeroth index and the first index have been allocated to the left side and if we want to say that there are two numbers there we can just take that first index just add one to it and say okay there are two numbers allocated to the left so now we need to define our four variables so that would be the small left side the large left side and then we want to do so small right that didn't help small right and enlarge right okay so we have a small left and large left small right and large right so these are the four numbers we're going to use to define whether or not it's a valid medium so small left is going to be equal to the smaller array at index if that value doesn't exist we'll just set it to negative infinity large left is going to be equal to large at nums needed that was my wife at and my minus one so if we say we need four values allocated to the left side and we subtract one to it then we want the third index right so if that's not that number is not defined then we'll set this to negative infinity as well so then small right will just be that index at index plus one or infinity and large right will be large that just numbs needed and similarly if this does not exist will set this to be infinity so with this in place we have our four values and now we just need to define what is left and right so as we discussed earlier left is the max of small left and large left and right is the minimum a small right and large right so now that we have these two values we just need to do our check so we say that if left is less than or equal to right then we can return something right if the total let or if the total length of the array is an even number if the number of values is even so if size mod 2 equals 0 then we need to return right plus left / - else we can just return right so / - else we can just return right so / - else we can just return right so before when we talked about this problem I said we were going to put the odd-numbered one to the left but it was odd-numbered one to the left but it was odd-numbered one to the left but it was easier to code to put it to the right so in that scenario where we had six numbers on one side and five numbers on the other well that six numbers going to be on the right side so if it's odd we'll just return this right side value so if this is not the case if we didn't find the midpoint then we need to either return if we're too high or too low so if the small left value is less than the large right value then we're too low right because this large right value is where it should be so we need to move the small left value further to the right and so we can just return that it's low and then if this is not the case then it's too high so with all this logic in place we can just do a quick little recap here we grab the total size we define this helper function which does our binary search for us we're finding a midpoint and then we're passing it in to a call to check for media so check for median is going to take our midpoint and it's going to figure out how many numbers do we need to the left using these four values it will determine a left and a right and then if it's valid if less if left is less than or equal to right then we can return our value if it's not it's going to say whether we're too low or we're too high and then here at the end we're just stating that we want to run binary search on the smaller of the two arrays so we click Submit here okay I'm getting a runtime error line 34 let's see so it's result equals low so mid high low mid unexpected token okay I need a question mark here a another type of 129 okay with the type was out of the way a little live debugging we have we've come to our answer so as you can see I've already run this a few times I've been working on this problem for quite a while actually trying to write it in a readable way that's easy for me to explain but I've actually run into some really interesting results that I wanted to show you so you can see here that I'm actually getting some pretty variable runtimes like I'll get 150 - I variable runtimes like I'll get 150 - I variable runtimes like I'll get 150 - I even got a 2:16 down here and I was even got a 2:16 down here and I was even got a 2:16 down here and I was pretty surprised by this so I wanted to investigate some of the solutions and show you guys a little bit about how you can kind of check your own runtimes and when you get these kind of funny results from leak code I found myself in the past just hitting submit over and over again until I get a value that I really like and I'm starting to learn that maybe that's not the best way to kind of go about checking your solutions so if you look at some of these solutions so you can see that ours Falls kind of in this 80th percentile range but here's one that I found that's a 112 milliseconds and this here is actually a linear function so if you see here that they're calling this merged to this merged ray or they're defining it and then they're defining these two pointers and they're just pushing these numbers in so this is part of the part of a merge function and they're just saying that if the length is even right then return the two middle numbers divided by two if it's odd then just return the middle number right so this is the simple this is the simplest solution to this problem it's a linear solution but you can see that it's only four milliseconds slower than what we've done so if our if the work that we've done is suppose to be actually quite a bit better than this the tests are definitely not reflecting that especially if I'm at sometimes getting a runtime that's twice as long as this 112 milliseconds so I just wanted to do a little investigative work and show you guys and maybe how you can look at these yourselves and maybe you should take some of these leak code results with a grain of salt but so here's something that I so okay so it's not here it's here okay so here right here is that linear function that I was telling you about so I pasted it into the console here and then here's our function so it's a I called it check for check or find medians or to raise two and then I use this decorator function that a friend of mine actually mentioned to me that I should try to show to kind of show how this is working and what I've done here is I've created so I've renamed it to linear and run it through this time decorator so this time decorator is going to just basically you know right before you run the function it's going to take the start time and then when you're finished it's going to give you the end time and it's going to just spit out like how fast is this function run it and I did that for both so I called this the linear and then this the binary and then I made two giant arrays a and B and then we just ran them so you can see here the linear one ran in about a second and a half right and then the binary function ran in two milliseconds so you can see that the run time for these is actually quite a bit different and this one problem ran in 1453 milliseconds whereas the run time of the total test suite for leak code for the problems that we did was a hundred in 108 milliseconds so I would just take those results with a grain of salt I would focus more on your implementation of the problem and if you're getting it's kind of these strange results I wouldn't just pound on submit over and over again to try to validate the work that you've done I would recommend that you actually investigate it this way to verify that what you've done is actually a good solution to the problem anyways this has been a very long video it's been a really complicated problem it took me a long time to go through this and I spent quite a bit of time coming up with this solution I hope you enjoyed the video and congratulations if you completed the problem and made it all the way to the end
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
525
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 525 contiguous array given a binary array nums return the maximum length of a continuous subarray with an equal number of zeros and ones so for example if we're given this nums here zero and one what are the two sub-arrays that are contiguous and have sub-arrays that are contiguous and have sub-arrays that are contiguous and have an equal number of zeros and ones well it's going to be zero one and one zero right and both of these actually have a length of two which is our solution here so how might we solve this problem well we could do it in a naive manner and basically that is going to be building all the possible contiguous sub arrays right so we could have 0 1 we could have zero one zero we could have one we could have zero one zero and then zero right and the only ones that have an equal amount are these two which is the ones that we saw earlier they both have a length of two and that's our solution but doing this is not going to pass your interview because this is a very inefficient solution you basically have to build all possible combinations and that's going to be a ridiculously expensive time complexity and your interviewer is basically just going to laugh at you so how can we solve this problem in the most efficient manner and actually pass the interview so what we want to realize is we are interested in the count of the zeros and ones in a sub array and the way that we're going to do this is we're going to have a count variable which represents basically the balance between the ones and the zeros and obviously in the beginning we haven't counted any so it's going to be at zero and any time we see a one what we're going to do is we're going to increment the count by one and if we see a zero we're going to decrement the count by one so let's look at a different example we have zero one right so let's look at what our count would look like if we were to do it this way so obviously we start at zero so we see the ones we're going to increment our count by one so the count is now plus one we see a zero so now we subtract one from it so the count is now zero we see another zero so now it's minus one see another zero it's minus two we see another zero it's minus three now we seal once we're going to add one so now it becomes minus two then we see another one it becomes minus one and now we add one to it because we have another one and we have zero so the points where we had zero is going to be here and it's going to be here right so those are potential solutions so basically i mean the optimal solution is the entire thing because it's perfectly balanced but you know what we can look for is points where our count is zero and that is for sure going to be a place where they're balanced but what about this sub array here this one actually has a balance in it but you know it didn't show up because we were only looking for zeros well let's think about this if we have some count minus three because of some stuff in the array and then some more stuff happens and then at some point we're at minus three whatever happened between these two points we don't know right it's the squiggles it can be any random numbers but all we know is that we started at minus three and we ended at minus three so that means that all the ones got cancelled out by zeros which means the numbers between these two points actually are balanced right so if we look at this between the minus two and the two these two values including the end point here is actually a balanced array so we not only want to look for points where the count is actually zero in these cases because we know for sure it's going to be zero but we actually want to look at points where the count is actually something that we've seen before so here we've seen -2 before seen before so here we've seen -2 before seen before so here we've seen -2 before and here we've also seen -2 before so and here we've also seen -2 before so and here we've also seen -2 before so that means that everything starting from the next one after this minus two up until this minus two point is actually going to be a balanced array and we can see the same thing here with the minus one and the minus one right so everything from the right of this first minus one and then up until the second one is going to be balanced right we see that there's one two zeros and then two ones so this part is also balanced so we can't just look for points where it's zero we also need to look for points where we've seen that count before and then basically take the difference between the end index and the start index and that will give us our um our length there and this calculation actually won't be including the end point here so that way we don't accidentally like count the wrong value right so what do we want to maintain a dictionary which is going to map the count and the last time we saw it right the index that we saw that count at basically if we've seen the count before then we want to update our answer with whatever the maximum of the current answer is and the difference between the last time we saw that point and our current point right so if we kind of think about this um you know we're gonna do whatever our current index is minus the last time we saw it so we're gonna if this is our dictionary we'll call it d we're gonna say our current index i minus d of whatever the last time we saw that count was and that will actually give us you know this is the case where we see like a minus two twice right so we want to actually take that difference because we know between those two points is actually a zero so that's essentially what i want to do and if the count isn't in there all we need to do is just put it into the dictionary and continue so that's how we solve this problem let's go to the code editor write this up it's like 15 lines of code super simple we are in the code editor let's write this up remember that we need a dictionary to basically keep track of our counts right so we're going to say scene at equals to a empty dictionary and we actually need to initialize our dictionary with a value here and we're going to say cnat of zero equals to minus one because obviously our count starts at you know zero and we can't say that the count is zero at the zeroth index because obviously at the zeroth index there could be a one or a zero in which case it would be either minus one or positive one so we can't say that it's one zero we actually have to set it equal to minus one and that way that our math is gonna work out if we need to do the subtraction it so say the first two values are actually uh balanced and that's our answer right when we see the zero the count will be minus one then we see this one the count will become zero and remember that we take our current index which is you know this is going to be index one and we want to subtract it with the last time we've seen zero if we initialized it to zero it would be the index one minus zero and that would be our length but obviously that's not right because this is a length of two so in that case we need the minus one right so one minus negative 1 is going to be 2 and that's why we do it to basically handle the case where the solution happens starting from the front so now that we have that we basically need a variable to keep track of our answer so we'll just say ands and it's going to be zero because we haven't found our maximum length yet and remember we need that count variable to basically store our current count which is going to be zero so what we're going to say is for index num in enumerate nums we're going to go from left to right and we're going to say count it's going to get a 1 added to it if num so basically if num is a 1 and not a 0 otherwise we just want to add a minus 1 to it now what we want to do is actually check whether or not we've seen this count before because if we've seen this count before then we know that we have two points where in between them the basically the balance between the ones and the zeros is equal and that's what we're looking for so we're going to say if count in uh scene at what we want to do is we want to say the maximum length oops sorry uh we're calling it answer here ands is basically going to be the maximum of whatever our current answer is and our current index minus the last time we saw this so seen as of that count and that's going to be how we update our answer otherwise if we haven't seen this count before we just want to put it into the dictionary scene at and count equals to the current index and notice that we're not updating the count in the case that we have seen it before because we want that original count to be as far left as possible so that way that when we go to the right we want to get as big of a window as we can if we kept moving it up then we would get local minimums but we wouldn't actually get the right answer so local maximums but we wouldn't get that the actual global maximum so all we need to do now is just return our answer and we're good to go i just want to run this make sure i haven't made any syntax errors okay cool we are good to go let's submit this and it works brilliant so what is the time and space complexity for our algorithm well for the time as you can see all we're doing is we're going from left to right over our nums right we're processing each number once and what we're doing for each number we're incrementing this count variable and we're looking something up in a dictionary so the total time complexity here is going to be big o of n right we do these n we process the n numbers and nums and then we do big o of one operations at each time so total time complexity is going to be big o of n where n is the number of nums in this uh nums list that we're given what about the space complexity here well we're storing the counts in our uh you know cnat dictionary in the worst case our nums is actually going to be all zeros or all ones right this can be like one so that means that our count variable right it starts at zero but then we see the one so it becomes one two three four five uh and in the case where it's all ones you know we're never going to have duplicates each count is going to be unique and it's going to be one count for basically each one of these numbers here so in that case because of that the space complexity is also going to be big o of n for that worst case where we actually need to store one count for basically however long nums is so that's why the space complexity is big o of n so this is the most optimal way to solve this problem you're not going to get a better solution than this and this is probably what your interviewer is looking for anyway if you enjoyed this video please leave a like and a comment it really helps with the youtube album with the youtube algorithm sorry i can't speak today and if you want to see more content like this while you're preparing for your on-site interviews please subscribe to on-site interviews please subscribe to on-site interviews please subscribe to the channel i have tons of videos already uploaded and i plan to make a whole lot more subscribe so you don't miss those otherwise thank you so much for taking the time to watch this video have a great rest of your day bye
Contiguous Array
contiguous-array
Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`. **Example 1:** **Input:** nums = \[0,1\] **Output:** 2 **Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and 1. **Example 2:** **Input:** nums = \[0,1,0\] **Output:** 2 **Explanation:** \[0, 1\] (or \[1, 0\]) is a longest contiguous subarray with equal number of 0 and 1. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
null
Array,Hash Table,Prefix Sum
Medium
325
400
hey everybody this is Larry this is me trying to do an extra uh haven't extra prom that haven't done before an hour ago so let's get to it RNG let's go uh and today's PR today's lar extra prom is 4 digit given an integer n return M digit of the infinity sequence what is this one two huh oh I see it I was okay so basically 10 count is two digits okay um it's not an interesting problem I mean I think this is fine um it is just I mean there a couple ways you can think about this one the way that I would probably think about I mean whichever way you think about it is probably the way that you would do it to be honest it is um the I mean obviously you can okay maybe I take it back slightly you can't take you cannot do one digigit at a time okay so maybe you that is the one way you cannot do it but uh but other than that I think any kind of reasonable optimization is good and um and we'll start by just maybe the way that I would think about it just the number of digits right so how many numbers have one digit right so nine um nine numbers have one digits right have one digit one digits poor math and then how many has two I think it's 90 right so 90 numbers have two digits uh and then 900 numbers have three digits and then and you kind of see the pattern way um very quickly right um so and from that I mean you know that's pretty much it you write some for Loops right and to get and you know it's way easier to get you know the number that you want and then at some point you just break it down to the whatever right so okay so maybe I write so many digits it's equal to one right so curent is equal to nine maybe right so yeah I mean I it is how you f i me I'm just trying to optimize writing it cleanly in my head a little bit but to be honest like you if you write a little bit sloppy it's fine too but it is just what you I'm not thinking of anything crazy anything Advanced I'm thinking basically what you're thinking at this point uh if you're watching at home uh I don't know why I say it like that where else would you be watching if you're not watching at home let me know where you're watching this from I'm curious now uh make it safe for work please uh all right let's uh let's yeah so while current is um is it greater than I mean yeah well it's greater than I guess if it's Zod to um if it I'm just trying to think about the Eco 2 case um so if it's exactly then it would just be the last number right I think maybe I don't know maybe I'm wrong on this one anyway so then here um then you have N Sub is that right oh no I think I got this wrong whoops the other way and if it's equal to what happens if it's equal to then it is just the last digit of the last number okay fine right so while this is the case we do n subtract by um maybe this is better like s oh I kind of wrote this in a weird way um maybe count is a little bit better right and actually this is already off it should be count times digits right so then now uh count times digits and count we want to add it by 10 or times it by 10 as you can see from the pattern and digits we want to added by one right so then now we have we want to get the ndit number uh or n digit with um uh with digits number of digits I mean okay that's a awkward way of saying it that's why I'm a little bit awkward but uh yeah right um yeah and basically you know uh so the number is just going to be uh roughly speaking n by um digits right and maybe a leftover uh I guess I could use mod but I'll just write it separately so then this is the leftover of um the digits right or like yeah um yeah and that's pretty much it um we have to be a little bit careful because number in this case it actually starts at zero right like the zero number on the 10 on X digits or whatever so then now you have to um start at 100 or a th000 or whatever it is so then it should be number we added by 10 to the power of digits right cuz if it's one digit then it is 10 so that's not right it's digits minus one that's how I like to kind of check where I'm off by one you just plug in when the numbers if it's two digits this would be 10 so that's good yeah cuz it starts at 10 right and of course um you can maybe PR it for debugging but I don't have to write answer anyway so it's a little bit silly but if um let's say you're doing on a contest and you're kind of stuck and you don't know what to do well and you're just playing around these things and maybe you're playing around with but you're struggling off by one well what can you do well for this problem it's actually um I mean it's not the best thing and well you can't submit it correctly anyway but one thing that you could do is just write a boo Force like write it exactly how you think about it and then check the answer so then now you have a list of answers that you can check against um to verify you know your other more complicated Solution that's one thing you can do uh but today I'm not going to do that I'm just lazy so uh but yeah okay so then now uh so this is the number and then it's just like maybe I'm off by one to be honest but um but yeah you could just you know uh yeah right just see what did yeah okay yeah maybe I modify one but that's basically the idea right to get the digit of this of that uh oh because it's returning a string I have to convert it back to a int um well I mean I think the um even without the boo Force thing one thing that you can start with of course is just no right ready obvious numbers right so for some reason there's only eight I feel like it to be that you could do more than eight test cases by well but yeah so then here you can see them I'm off by one because where if this is zero well this is one this adds one so that's a little bit well no that mean that should be right isn't it uh maybe I'm off by one somewhere but you know that's how I would test it right cuz you know the answer for these things I mean I know that here they give you the expected answer anyway but of course you know during a contest you know you well during a contest um you know it's better to it's good to have and more inputs in which you know the answer to and you know these answers because you can produce them manually or like you know with pencil and paper or something all right um yeah so why is this giving me two so and maybe I'm off by one it's fine uh so yeah so if n is equal to one right so this is not going to be true so n is equal to one over the number of digits is going to be one huh oh I see I think I just off 51 because I um I have a zero index and how I thought about this problem so yeah because number is zero index the way that I thought about it um so yeah let's try this okay it works with this but of course you have to try it for a little bigger numbers uh yeah all right looks okay uh and here this is where I'm cheating a little bit just because I'm lazy uh you may you know uh cuz you know like I when you w in BO for you can actually calculate these like offline or something just to kind of you know and I'm just banging on the keyboard there's nothing special about these numbers but just for test to make sure that I'm right and you know with these random big num big is num numers um and it's still right I'm kind of confident unless I missed like a ready Edge case so yeah um that's pretty much it that's all I have for this one um kind of straightforward I mean it's like let me know if there's other I mean other than really boo Forest I think this is pretty straightforward in terms of how to think about it I don't think there's anything like tricky or nuan you just have to be um I mean obviously your speed may not be my speed just because um you know there are a lot of ways to think about it and like you may have off by one here or something like that um but that's just practice right so like but you can reason like the idea should be pretty okay even if oh jeez oh man don't if I'm allergic something sorry friends and I was so float so maybe I'm coming down with something but yeah I mean like maybe you have off by one maybe you have you know a little bit um you know have to warm up to it or something like this but I think the idea is pretty straightforward is just what you would think it is I think the only other thing is excuse me sorry oh man I don't know what I'm going the only other thing that I would say oh my sorry I'm like half sneezing uh I feel like I'm one of those quick fake videos is like leaving the uh leaving what I'm saying to end um like just wasting time but I'm just like sneezing like a I don't know okay maybe I'm not sneezing now but what I would say is that the only thing that um you may be a little bit kind of scared about is this like two to the 31 number right which is very big but um but I think once you kind of see the structure and I didn't write it out but you can kind of see that um uh this grows like by 10 every time it's actually more than that because it's this number times this but you can see that it grows at least by 10 every time and therefore there's like this log 10 or log base 10 uh thing to it which means which is roughly another way of saying the number of digits so 2 to 31 has like 10 digits or something like this right is it 10 or 11 I don't whatever it is today I'm not yeah it has 10 digits so you know that this will go looping at least at most 10 times let me actually go over this complexity actually I think I missed that sorry um man the sneezing kind of threw me off a little bit but yeah um there only almost 10 things but yeah but know ultimate it's just kind of based off this and you can kind of see this grows at least 10 it goes a little bit faster but um but this should suffice and like I said um this means that this is the number of digit of n or if you want it's going to be log base 10 n right and of course log base 10 of n in big old notation is just log of n um but keeping in mind that of course in this case uh log uh n is the size n is not the size of the input n is the number representing the input and so the size of the input is the number of input bits is log n right or log of this n so this is actually um you can say that this is actually um linear time and I guess in that sense this is like linear space I don't know right uh and it's always awkward and yeah uh but yeah linear time linear space is all I have for this one let me know what you think and yeah stay good stay healthy de mental health I'll see yall later take care bye-bye
Nth Digit
nth-digit
Given an integer `n`, return the `nth` digit of the infinite integer sequence `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]`. **Example 1:** **Input:** n = 3 **Output:** 3 **Example 2:** **Input:** n = 11 **Output:** 0 **Explanation:** The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. **Constraints:** * `1 <= n <= 231 - 1`
null
Math,Binary Search
Medium
null
899
hello everyone and welcome back to another video so today we're going to be solving the lead code question orderly q all right so in this question we're going to be given a string s and an integer k so we can choose one of the first k letters of s and append it to the end of the string now the goal here is to return the lexicographically smallest string you could have after applying the steps that they just mentioned so what does that mean so uh when you have cba the best answer that you could get would be abc okay so that would be the lexicographically smallest value right that would be the ideal value if we could return but in this case we have a condition which tells us that we can only move the first letter to the ending that's the only thing we can do but one two remember is we can perform this for how many other steps we want there's no restriction on the number of times we can do it but the restriction is on the fact that we can only move the first letter to the ending okay and based on that what is the smallest lexicographically string uh that we could actually get that's what we return now another example is when k is equal to three now in this case what it tells us is that we can move any of the letters up to the third letter so that includes the first letter the second letter and the third letter we can move any of them to get uh whatever new string that we want to form or in other words whatever the lexicographically smaller string is so in this case we can either move b a or a to the ending and perform the steps over and over again until we get whatever we're happy with okay so now let's see how we can actually solve this question and there's actually one pattern that we have to look for to actually get the best solution for this so let's take a quick look at that alright so over here i'm going to start off with the case of when k is equal to 1. so what we're going to notice is k is equal to 1 and when k is greater than or equal to 2 are basically the only two cases that we have and we don't need to worry about when k is equal to three or whatever because it all they all of these behave the same way and what i want to do is actually show you how that is true so instead of using letters so instead of using a comma b comma c for example i'm just going to use 1 comma 2 comma 3. i just think it's a lot easier to look at that and make comparisons with numbers rather than with letters okay but the idea is going to be exactly the same so let's say over here i have the numbers 5 comma four comma three comma two comma one and i said k is equal to one what does that mean well what that's telling me is that whatever i do i can only take the first letter and move it to the ending so in this case that's the value five so one thing i want to show you is we can actually just look at all these possible values in the first time and uh let me just do that right now so we have five four three two one and let's look at the other possibilities so now we move five to the ending giving us four comma three comma two comma one and then five so now we can move the four to the ending okay so let me just write all these down so we have three comma two comma one comma five comma four now we move the three to the ending so two comma one comma five sorry two comma one comma five comma four comma three cool and now we move the two to the ending so one comma five comma four comma three comma two right okay sorry and then finally we move the one to the end to give us five comma four comma three comma two comma one perfect now these are all the combinations so look 5 comma 4 comma 3 comma 2 comma 1 gets us back to this value over here and then we just keep repeating these over and over again okay and these are just all the combinations we have we're never going to have more than these combinations so now what we really do is we get all of these and out of these we see whatever is the lexicographically smallest so in this case uh whatever is closest to ascending order would be the best answer correct and we look at them like in a brute force way using and then we choose the best one and in this case the number of combinations we have is going to be whatever the length of the input is so in this case the length of the input is one two three four five so we have five possible values five possible combinations for this and you can look at this one two three four and five it's pretty simple right so basically what this is saying when k is equal to one we're basically looking at a circle okay and the best way to show you this is if i draw it out so five point two four to three and then to two one and then five so in the beginning we have five as a starting point so we have five four three two one cool but now we can take four as a starting point giving us four three two one five which is exactly this then we have three as the starting point goes three two one five four and then two as a starting point giving us two one five four three and then one giving us one five four three two and finally back to five so essentially when k is equal to one all that's happening is we're in we're kind of rotating this area around we're rotating the values that we have but the only thing that's really changing is starting point we're not changing uh the order at which they're in but we're just changing their positions okay so 5 is always going to be next to 4. we're not changing that in any way so this is the restriction that we have when we have k is equal to one and in simple words what is happening over here is we're rotating the array okay at the first place so like i showed you that circle we're just rotating it and we have a fixed number of possibilities which is well going to be the length of whatever the input is and when we have k is equal to 1 we get all of these values and then we just get whatever is the lexicographically smallest value and return that but now where it gets different is when k is greater than or equal to two so to start off let's start off with the base case of when k is equal to two so what i want to do is let's just take a smaller example i think that'll be easier so say we take two uh comma one comma three comma four okay so in this case what is how do we get the best value so the way we get the best value is when we get one comma two comma three comma four assembling order right so this is the best answer now how can we actually achieve this we can achieve that by swapping one and two now this is possible when k is equal to two but it's not possible when k is equal to one when k is equal to 1 all that happens is we rotate our set of values but when k is equal to 2 the big operation that we can do in this case is we can perform a swapping operation and when we can do that we can actually always guarantee to get the best value so we can always get the lexicographically smallest value or in this case we can always get the ascending order and let me actually show you how we can do that so when k is equal to 2 we can swap either the first number or the second number either of them can be swapped at one time so let's start off and really like i said we want to swap these two so the way we do that is we first pop out the 1. so that gives us two comma three comma four and then we have one and then we pop out the two so this gives us three comma four comma one and then we have a two perfect so now what happened is earlier it was two comma one but now it's one comma two which is the correct order that we need them in and all that's left to do is get back get them back to their correct positions so we first pop out the three giving us four comma one comma two comma three and finally we pop out the 4 giving us 1 comma 2 comma 3 comma 4. so as you can see we got the correct the best answer that we can get so the point i'm trying to show here is whenever k is greater than or equal to 2 we will be able to get the best possible answer so we don't need to actually look at all the possible values we can just directly just return the best possible answer that's it so uh just to show you another example let's say instead of two comma one comma three column four we have two comma one comma four comma three okay so i'm just gonna do it over here so again the same thing applies but in this case we gotta make two swaps one over here and one over here so it's going to be done the exact same way so first we pop out the 1 so giving us 2 comma 4 comma 3 comma 1 and now we got to get the 2 out of the way so 4 comma 3 comma 1 comma 2 but now we got to pop out the three first right because it's one two and then we need to get the three and then the four so this would now be four comma one comma two comma three and finally we gotta get the four in the correct place so that's one comma two comma three comma four so let's actually just look at something where the swaps are not next to each other so an example could be two comma four comma one comma three so look the swaps are not next to each other but we can still end up getting the correct value or the smallest lexical graphical value well in this case one comma two comma three comma four so just to actually do that real quickly what we could do in the beginning is we take the four on that side so four comma one comma three comma two that's what we get and then what we could do is we could take the one on that side so that would give us four comma three comma two comma one okay perfect now what we're going to do is we're going to take the four on that side giving us three comma two comma one comma four so right now we have three and two that we could swap out with but let's just do it step by step so first let's do the one and two okay so let's get rid of the two on that side so two comma one comma four comma three now again you could do this any possible way the end result is still going to be the same and again we don't need to we don't really care about how many times it actually takes us so at this point we swap the two and one so we would do that between two comma four comma three comma one and then we do four comma three comma one comma two and now all that's left is the four and three so we take three outside so that gives us four comma one comma two comma three and finally the four on the other side so that will give us one comma two comma three comma four okay so my point here is no matter what it is by performing swapping operations we will always be able to get this the smallest lexical graphical order that we need so real quickly when k is equal to one we gotta kind of brute force it and look at all the possibilities and choose the smallest one but when k is greater than e or equal to two then in that case we just directly return the smallest or best lexicographically sorted order so that's it so now let's see what this looks like in code all right so like i said first we check for the condition if k is equal to one now when k is equal to one this is where we gotta look at all the possibilities so over here we're gonna have a string called result and we're going to set result uh in the beginning to have a value of s so the reason i'm doing that is because each time we're going to be comparing result so we could actually you know set it to something like an empty string but when we're making a comparison the empty string is always going to be the smallest so that makes no sense so instead what we do is look in this case we have five possibilities so by setting it to the last possibility right what we can do is instead we just go through the n minus one possibility so we set it to this value in the beginning and then we compare it with the other n minus one values that we have and by the end of it result is going to have the smallest one okay so now we're going to go in a for loop and the range is going to be the length of s minus 1 like i explained right because res is equal to s cool so now we got to reconstruct s and what i mean by that is whatever is at the zeroth index goes to the ending okay and how can we do that well that's pretty simple so we take whatever is uh everything after the zeroth index so from the first index to the ending and after that's the ending we're going to add whatever is at this index so this is our new string and over here we're going to take the value of result and it's going to be the minimum between whatever the current value of result is and the new string that we have after taking the zeroth index value and putting it at the ending so by the end of this we're going to have the smallest value for this and we're going to return that in result so that's it but if this is not the case that means well k is greater than or equal to two so in this point it's very simple what we're going to do is we just go to sort s and the way we do that is we can do sorted s now one thing to note is that this returns a string sorry a list but we actually want to return a string so the way we do that is we could use a join function so we could use this dot join and we put the list over there so essentially what this means is that between each of the elements in the list this is going to be what's in between of them so in this case let's say we have a b's a comma b comma c it's going to just be joined to a b and b in this case right uh okay that's it so that's what the join function does and we got returned so return and that should be it so let's submit our solution and as you can see our submission was accepted so thanks a lot for watching guys and do let me know if you have any other questions
Orderly Queue
binary-gap
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. **Example 1:** **Input:** s = "cba ", k = 1 **Output:** "acb " **Explanation:** In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ". In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ". **Example 2:** **Input:** s = "baaca ", k = 3 **Output:** "aaabc " **Explanation:** In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ". In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ". **Constraints:** * `1 <= k <= s.length <= 1000` * `s` consist of lowercase English letters.
null
Math,Bit Manipulation
Easy
null
1,706
How are you all, today we are going to talk about question number 1706, where will D ball fall, so in this, you have been given a great gift of Ambrose and size and now you will understand better what to do in this. What you have to do is see in this, you are given N balls here and you will drop them from here. Now what will happen is see if you see like this here, if you drop this ball then why should the red one come out from the gap from here? If it reaches here then this column number is zero, this is column van, this is you, this is three, so the ball which was first in the end, came here on column van, so look here in the answer, van A has gone, right, it is not the first. Now I have come to the column, like this one said and this one said all the other words till now, look at the V-shop other words till now, look at the V-shop other words till now, look at the V-shop where it is also being made, this V-shop is being made, where it is also being made, this V-shop is being made, where it is also being made, this V-shop is being made, this topic is being made, so what is the word there because they have to go ahead. I am not able to find any part, this one came here from here and got stuffed here, so all the balls are extra in front, so look here, whatever will be extra in the rest, say there is a mine van, you have to print it in the answer, it is a ball. The key's responding ball number, which was zero, went to the van column and passed Puri. If Puri passes till the end, then tell your friend in which column it has gone. If it gets stuck, then -1. it has gone. If it gets stuck, then -1. it has gone. If it gets stuck, then -1. Now in this. What is that when such a one means when this one will be there then the grade given to it is 2D grade, the van will represent it there, you understand the meaning, see, there can be two types in it, one can be slant like this or else. If you understand the meaning, then there will be a cylinder which will send the ball to the right side. Okay, what will happen there that the van will represent and as if it is sending it here, then how to see the mines van here, see here. 1 is representing, so it is sending here, right, and this mines van is returning here, so look here, this mines van is here - 1, okay, so the van is here - 1, okay, so the van is here - 1, okay, so the question is, you will do this, how will you do that ? Let's see, how can we think about this ? Let's see, how can we think about this ? Let's see, how can we think about this question, what will we do here, as if we dropped each ball in the beginning from here, first on row number zero, we will see which ball reached where on row number zero. Now it has reached its destination. If any call gets stuck anywhere then it will not be processed further. Now like the ball number is zero. Okay, now you have seen that which is your ball here, now you have seen that now this one. If it is kept in grade or van, it means it will send here to the right, so now it will send to the right, so what did you see that if by chance, if your is this one, which means this one is this one, if it also happens like this, what is here is Look, this part was going to send the word to the right, this part is fine, but what happened that the one just here, look, it is sending it to the right, then we will see the next one in the index of that column. If he is sending it on the left, then a C-shop will be made here. Understand that if he is then a C-shop will be made here. Understand that if he is then a C-shop will be made here. Understand that if he is trying to send it here, then just look at him next. Is he not sending it here? If he is sending it here, a C-shop will be made here, then he will say that he will send C-shop will be made here, then he will say that he will send C-shop will be made here, then he will say that he will send it here. This truck is done, okay, so you look at it, this one is sending it here and this one is sending it here, okay, it means path, so what will you say, tell me what is your need, it was in the column, now this one will send it here. This one will go to the first column, this one will go to the second column, then we will make the index +1 of our place make the index +1 of our place make the index +1 of our place and like this one will say, this one came from here to here and both of them are stocked, now if If we process this ball then we will see where the next one is going, look, this one is taking it here to the right and this one is also here, then we will come here, doing this like this, let us see it with the code. You will understand well and do not take any tension, I will clear each and every thing, so see what you have done in the question here that macros of N are grade given, meaning M is the number of roses and N is the number of columns. But it is mine, I have taken it a little differently, meaning, N number of days seems more correct and what I have done is to put each bowl here that zero answer of I min kya dal diya aayi dal diya ki abhi need tell. वैन पे kya dal diya aayi dal diya ki abhi need tell. वैन पे kya dal diya aayi dal diya ki abhi need tell. वैन पे बोल वैन पे वैन पे बोल वैन पे वैन पे वान पे डाल डाल के लिए को वान पे बोल वैन पे डाल के लिए OK NOW WHAT HAVE I DONE? We will बोल वैन पे वैन पे बोल वैन पे वैन पे वान पे डाल डाल के लिए को वान पे बोल वैन पे डाल के लिए OK NOW WHAT HAVE I DONE? We will not process it like if this ball here is stocked from here, then we will put -1 in our widget so that when we put -1 in our widget so that when we put -1 in our widget so that when we come to the next row, like the first row is completed, now this ball will not be able to go till the bottom, then we will move it to the next row. Will not do the process and will keep the answer, now let me tell you what you are doing, look like this, first row, then second row, then third row, Puri is right and will take every ball as its own. Okay, so you have put on the look of income. For this row, the number of days is not right, neither have you traveled any time and then you have put a loop of J, which will go on each column. Now look carefully at this thing, if you have selected off. If you see first where is the first ball, then we will process it, then the second one, then you said that one is selected, look at A's look, the number of the rose is telling and what is J's look saying, first ball, second ball, third. Is it okay to do the ball like this then visit yourself, now look at yourself, what is it telling you in the answer, where is the verse you said is correct? The answer is of M size, and in the answer of 'I', I had answer is of M size, and in the answer of 'I', I had answer is of M size, and in the answer of 'I', I had put the 'I' group, now what have you done, put the 'I' group, now what have you done, put the 'I' group, now what have you done, remove the index. If you have taken it then it is processing zero bol. If it is J1 then Van bol ko ke is tu hai then it is okay to say second. Then, from the answer of ke, we found out in which first column the brother-in-law who spoke to us found out in which first column the brother-in-law who spoke to us found out in which first column the brother-in-law who spoke to us is in the first column. So he went to his index in India, now he checked, see, there is only one condition here, it is simple, one understood, it will be very easy in the second condition, look carefully, if the grade of I was given, if he said where he is. What has happened is like where is the first ball, now like it is here, okay now I said that if the grade is off, it is van, because it is sending it here, if it is sending it to the right side, then it will be van, look here, van is written. Okay, so what will we do, we will go inside it and you should look carefully at this thing, this was the most important logic of this question, so now what are you doing here, look, it has said that if I take it, your words are here. Hoti is in this column, the row number is fine, you are fine in roll number 2, this is the column, this one, look carefully, you would be here and if you drop yours, then it would send you towards the wall and there is nothing beyond the wall. Okay, this is the last one, that is our column number, so what would happen here if this grade of ours is being sent to the right, that is, it is in the last column and is also being sent to the right, then what would it mean that column If he wants to send the number in M, I understand the meaning, if he is sending it to the right and his ball is in the M-1 column, then he is his ball is in the M-1 column, then he is his ball is in the M-1 column, then he is sending it outside that too, then it is not possible, then it means that the ball is stuck, is it ok then he What will you do in this case, you will mark the guest with -1, the ball which was yours has mark the guest with -1, the ball which was yours has mark the guest with -1, the ball which was yours has become mines van, that means it cannot go further and in the answer of 'K' you also added 'mines and in the answer of 'K' you also added 'mines and in the answer of 'K' you also added 'mines van' is fine, in the answer of 'K' you added -1 van' is fine, in the answer of 'K' you added -1 van' is fine, in the answer of 'K' you added -1 and When will it be blocked on the second condition? Look, it will be blocked only on two conditions: either he is Look, it will be blocked only on two conditions: either he is Look, it will be blocked only on two conditions: either he is making a C shop or he is sending the man low to the right and the wall has come there. Do you understand the meaning? Last, in this column, your ball is there and it is to the right. If the word A goes, it means that if van A goes in bread, then he wants to send it in more M, that is not possible and the second condition is that if he is sending it in right, then grade of I means what came in your mind, see the next one in end plus van, is that? -1 is not there, end plus van, is that? -1 is not there, end plus van, is that? -1 is not there, even if mines is a van, it will be blocked. How to see your boll number, see the initials here, I was sending it in pay right, here van is in grade, only then I am in this one, because here pay grade is fine, now when my Do you know that he is sending it here, now you have seen where he is sending his next cell, he is sending it here, right, it is on the left, so if you look at the grade of I, it was the end here, what have you done, D plus van. If it means that the subject is being formed, then in both these conditions, I have put it here in the answer of K, what did I do in the column of which I spoke, I am sending it to the right of whichever column I spoke in, then the index will be plus one. Now see all. If the condition is true, you can go inside, then what did you do? If you came here in the other block, then tell me now that you are in this cell, that means in the column number van, this is the zero column. This is the van, so you came here. From now on the condition is our health part, meaning if the grade of I was 1 then it was now grade of high. If it is -1 then it was now grade of high. If it is -1 then it was now grade of high. If it is -1 then it means that the person is sending the ball in the left. Right, now it is like the man is sending in the low left. And in this one, the first cell in roll number 2 is this one over here and you take the man from here and drop it, brother, what will happen is that it is in your zero column and you are already in the -1 column. If you want to send and there in the -1 column. If you want to send and there in the -1 column. If you want to send and there is no column there, then what will happen to you when your grade of -1 means here in grade and your end is zero, that means you are standing on the column with zero and is sending you to the left. Meaning, I am sending you to the Mines Van column, when there is no column there, then you have to make Visitor of I K also -1 and Answer of I K also -1. The -1 and Answer of I K also -1. The -1 and Answer of I K also -1. The above condition is fine, right? There is a difference and here Pay Grade of I. Now look, if there is a condition on the left, then after your I, you will keep ID-1. In this, after your I, you will keep ID-1. In this, after your I, you will keep ID-1. In this, Pay Plus Van was kept here, that's all there is inside and you will check your. Now look in this cell, if it is in the help block. If it comes then Grade of I ID-1 is fine because there can be only two things, so I ID-1 is fine because there can be only two things, so I ID-1 is fine because there can be only two things, so van or mines, van, then the van is here, the case with the van is here, so this is the case, so this is mines van, so what are you looking at yourself, what is going on? So, my mines, which is like this, the number is this one, zero van, three, you have come to the purple colored block, now I have seen this, just what is the first sale doing, it is sending it to the right, so I have become a shop, so my Ne put -1 Varna Apna kya kar hai that he was Ne put -1 Varna Apna kya kar hai that he was Ne put -1 Varna Apna kya kar hai that he was trying to send in the left means if you decrease one column then Answer of Jamie kya dal denge ind - 1 Answer of kya dal denge ind - 1 Answer of kya dal denge ind - 1 Answer of JK is representing jhat gol apni abhi currently in which column. Okay, if the answer of K is -1, then it means that our ball has answer of K is -1, then it means that our ball has answer of K is -1, then it means that our ball has become a star and what will we do in our end when we return the answer, then what is its time complexity? The order of K is M*N complexity? The order of K is M*N complexity? The order of K is M*N because the rest is just inside. This is spread by us, so if you submit it, all this will be erased, so I hope you will like the video and its playlist is mine, thank you so much, you gave itna pyaar diya, you are watching its playlist, thank you so much from 30 29 30 I have finished the video so thank you for watching playlist. See you in the next video.
Where Will the Ball Fall
min-cost-to-connect-all-points
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Array,Union Find,Minimum Spanning Tree
Medium
2287
83
hey guys in this video i'll be showing you how to solve lead code question 83 remove duplicates from sorted list um so for this question we're given a sorted linked list and it's going to be singly linked and we're just asked to delete any duplicate elements um and so since this list is sorted um kind of the approach we're going to want to take is just to loop through the list and all we have to do is compare elements that are next to each other because any duplicates will appear in order and we can look at this example here so we would find a duplicate one when comparing these two neighbors and then duplicate three when comparing these two neighbors and we'd remove one of each of these to get this as the resulting list okay so to start coding this um we're just going to define another node variable because we're going to want to keep the head of our list since at the end of this algorithm we have to return that same head to give back at the beginning of the list so we can just define node and set that equal to head and then we're going to loop while that node is not equal to a null pointer so as we move this node it'll just go through the list until we reach the point where it's no longer in the list anymore and then to check for if there's a duplicate again we can just check it against its neighbors so we can say if node and val is the integer value if that is equal to the next node's value then we're going to want to remove one of those so to do that i'll kind of give another example here or a visual so say these are the elements in our list and let's say we wanted to remove this middle element so we'd have like another temporary pointer here oops um so this is the one we're trying to remove all we have to do to get it out of our list is change this pointer right here this like next pointer and set that equal to this node so it's now pointing over there and then using this temporary pointer that we have we can then delete this node from memory just to do extra cleanup okay so to code that um we'll make another list node pointer and just call it temp um set that equal to we'll actually delete the next node so that we can just stay on the node that we're currently on to continue checking in our list so that's equal to node next which will be deleted um and then the node next so this is the pointer on our current node so we're not actually changing like this temp variable at all but the pointer on the current node that we're on is getting changed so that it points at the next node's next node um so that is doing this change pointing at the next one um and then we have this temporary pointer which is still pointing right here so we can use that to delete that freed node from memory so we just do delete temp and that will remove this structure from memory um and then if we did not find a duplicate we're just going to want to move node along in the list right so the reason that we don't move the node in here is because um let's say you run one and found a duplicate and remove this one you still want to check this one against the two which would be the next element in the list because you don't know if there are multiple duplicates in a row okay and there is going to be one bug with this program since we're accessing node next value we're just going to want to add another check in here that node next is also not equal to null pointer because if we make this call and this node next is null pointer then we'll get a runtime error and um if this is equal to nullpointer then we're done looking through the list because we're already on the last element and then after our while loop we just return the head of the list that we're given and that should be it so we can try to run this oops list node okay and it works and you can see this is about as fast as we can be um and then the memory usage was also not bad but that's been changing okay so for the complexity analysis of this um we can first look at the space complexity um so we're not storing anything besides these two temporary list nodes and since these will be the same every time no matter how many elements you're given we can just say that we have a constant space so o and then for the time complexity we are going to loop through every node in the list and we'll only do constant operations on them so checking values um like moving nodes along or changing pointers even deleting the structure because the structure will be the same every time those are all constant operations so our time complexity is just o of n where n is the number of elements in our list
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
347
347 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 one we have an array one two three and case two so we need to get the two most frequent elements we see that one appeared three times to appear two times so one and two option one here's how to resolve this problem option one use a map where the key is the item and the value is how many times it appears so we need to count what is the frequency or how many times an item appeared the obvious thing is for each item to put it in a hash table where the key is the item and the value is the number of time it appeared now the only thing that is left is to sort this hashtable sorting is off and logan placing everything in as counting is often so it makes it overall air off and again option 2 improvement over option 1 instead of sorting use a heap this is a common theme when you need to sort but the core of the problem is not sorting but as in this example only get the top k then we could utilize the heap still build a map in option one which takes off and to build this map because we need to traverse all the items this is the counting map then we build the heap using a heapify which take off n a remove each item from the heap is of log of n until we moved k items so overall this would make it a of k log n and this would be better than option 2 of n log n if k is smaller than n option 3 offen use buckets for finding the top k instead of sorting start as usual by building a hash table for counting how many times each item appeared the same as the previous hashtable this would be o fan the value is the number of times each item appeared now create an array of size the number of items we have where in index i of the array would have list of the numbers occurring i times so if we get the item from index 0 this would be the list of items that appeared 7 times the maximum size of this array would be the max the number of items because we cannot have an item appearing more than n this is number of items as you see to get the top k we just need to traverse the top k elements of this list overall this means off n for creating both creating the hashtable intervals in the buckets list here is the actual implementation in python with a bucket solution of off n top k frequent we get its input the nums and the k step one put everything in a map for one we have it frequency two for free frequency one actually for four frequency one step two prepare the buckets from zero to numbers.length the buckets from zero to numbers.length the buckets from zero to numbers.length and the buckets are always sorted by index because it's by the index initialize first the map of appearances now go for each item in the numbers and increase it by one as it appeared initialize the buckets by the number of items that we have just initialize it the buckets each item in the bucket would be a list of itself of the numbers that appeared i times now for each item in the appearances map hashtable put it in the bucket according to the number of appearances so we have a bucket the index is the number of appearances and we put item x if it appeared number of appearances in the bucket now we need to get we finished setting up the buckets we finished checking out the cash map and we need to get back the actual top k so the result is an empty array we go over the list of buckets from the end to the beginning because the end is the item that appeared most times we get out the x the item that appeared i times we append it to the result and if we reached k we return the result so this was let code 347 top k frequent elements
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
6
hello and welcome to the sixth video in this leak code in c-sharp series in this leak code in c-sharp series in this leak code in c-sharp series in this video we are going to be doing the challenge called zigzag conversion so let's go over to lead code and let's start this challenge so if we load in and let's see what it does so the string PayPal is hiring is written in a zigzag pattern on a given number of rows like this you may want to display this pattern in a fixed format for better legibility so you've got three rows and it goes top to bottom pay pow is hiring in a zigzag pattern then read line by line you have this which okay line Valencia p-a-h-n this which okay line Valencia p-a-h-n this which okay line Valencia p-a-h-n phn then APL s iig APL Sig then y i r Okay so get the string you get the number of rows and other examples so for this p P or okay that was the original example so cut this one check out four races it goes all the way down then diagonally up down diagonally up okay so that should be easy enough I think okay to start this off we will have string array which equals number of rows so the value of numeries would be the amount of items in the array so the first item will be the first story second item secondary Etc so we'll be needing to iterate through each of the characters yes so we start off with the colon so now each row so I'll go zero one two three now I'll go back upwards to three two one then back down so I don't think this white space actually matters it's just going one two three four three two one like that so we'll do four and I equals zero I is less than length then I plus so I think it's this might be as simple as just doing rows okay so no that's not what we need to do this should actually be a four each it's a great thing like that then you have inch right equals zero pull Direct Direction down equals true so we'll then deuce string row plus equals C dot two string then row equals that's wrong way around if it's Direction down you do need to first I would check to see Direction down equals very equals zero Direction down no equals true so for equals zero yep true or row equals num Rose minus one just realizing this should be underneath here oh row minus one so you get to the so you do this to get the row number no this should be sixth round so which way should it be yeah we'll keep like that so radicals zero make it true or rho equals number is minus one false else just Direction down so where it equals Direction that's row direction or instruction down plus one okay I think that's correct for that then when we get to here for each right in string row Row in Rose actually change this to S through in rows output plus equals Astro then return output let's give this a shot I think this is right not surprised I missed semicolons as I always do so let's go through and fix all those so that's line three line nine identify yeah oh whoops wrong name Breeze row line 11 all the way over here I think that's all the mistakes now let's give it a shot okay that's promising I think that's the first time we've had all test cases accepted now let's submit okay index was outside the bounds of the array so okay we need to do a test case for numer reviews equals one if num Rose is greater than one nearly had it with those name mistakes but didn't think about edge cases like this actually we should include this in here it doesn't make a difference but may as well just run over the test once to see if it still works okay still works now let's submit okay cool I think that's the quickest I've done well definitely the quickest I've been with one of these challenges so that's pretty cool if you enjoyed watching this video where I solved the leak crew challenge called zigzag conversion make sure to like And subscribe so you don't miss out on any new videos in this code and C shop series
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
374
hey everyone it's me abdullah welcome back i do lead code and stuff you can check out other my liquid lead code problems and videos and you if you have any kind of questions you can ask them in the comments or just on my instagram of gulation956 so anyways we'll be doing another lead code today three seven four cash number higher or lower this is an easy one playing a cash game there is a game as follow if i pick a number from n2 from one to end you have to guess which number i picked okay every number you guess wrong i will tell you whether the number i picked were higher or lower than your guess again you can call a pre predefined api in gas and will be passing it num which return three possible results your guess result is higher than the number it will return minus and if it is lower it will return one and if it is equal it will return zero so that's it we will be doing it by binary search and just cutting out in half until we reached our guest result so we'll be starting from one because if they said we'll be starting from one they will be starting from one so r will be equal to n while left is less than equal to r uh we'll be computing our mid and l plus r down dividing it by two so now uh we will be calling the gas api and giving it the mid so if this res is less than you can say zero we know that our result is too high what we will do is our result is two higher we will take our right pointer and just subtract mid by one in the lf case if the result is greater than zero you know that we our number is very low so we will just wait plus one in this case and in the else case we know that we have found our number we will just return m and that's it let's see if this works and yeah this works and that's it
Guess Number Higher or Lower
guess-number-higher-or-lower
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible results: * `-1`: Your guess is higher than the number I picked (i.e. `num > pick`). * `1`: Your guess is lower than the number I picked (i.e. `num < pick`). * `0`: your guess is equal to the number I picked (i.e. `num == pick`). Return _the number that I picked_. **Example 1:** **Input:** n = 10, pick = 6 **Output:** 6 **Example 2:** **Input:** n = 1, pick = 1 **Output:** 1 **Example 3:** **Input:** n = 2, pick = 1 **Output:** 1 **Constraints:** * `1 <= n <= 231 - 1` * `1 <= pick <= n`
null
Binary Search,Interactive
Easy
278,375,658
795
all right guys welcome to our channel code with sunny and in this video i will be again talking about lead code problem the medium type problem number of sub arrays with bounded maximum you can see okay and its index is 795 and it is categorized at the medium type problem of the lead code right so before moving further to discuss this problem i just want you guys to uh vote up on this poll that i've created over here like i just want to know which is in high demand being required by our viewers and you just have to do one thing with it my channel and just uh what of your best like that you want among these four or five options that are present over here right so okay so moving further to discuss this problem so we have been given an array nums of positive integers and two positive integers are also given to us left as well as right and left must be less than or equal to right so return the number of contiguous non-empty sub arrays non-empty sub arrays non-empty sub arrays note that the sub array must be non empty and as it is a sub array it must be contiguous right such that the value of the maximum array element in that sub array is at least left and at most right okay so you need to find out what are the total number of possible sub arrays from the given array that can be built up that can be extracted such that if we try to find out the maximum array element in that sub array that we have chosen now then that value is at most right and at least left i guess you guys have understood that problem now moving further to the example and then we will together build up the solution for this problem right if you uh still haven't understood the problem yet no need to worry about i'm going to explain this problem in the little bit detail with the help of exa explanation and then we will together build up the best solution for this problem right many people have solved this problem with the help of stack we can solve this we can find out the total number of sub-arrays the total number of sub-arrays the total number of sub-arrays right but what i have done in this so like the solution for this problem is like i've used the binary search technique right so i am going to discuss that in little bit detail now uh for one thing that should be noted over here is like the constraints you can see the length of nums will be in the range of one two five into uh what is this value right 4 times 0 so 5 into 10 power 4 we can have a and like o of n log n solution okay and we will try to like uh improve my solution but i don't think like uh using like a stack technique is like better but we can use that but uh to understand this problem in a detailed manner you need to have the concept of binary search what is happening over here with the help of like mine research we can easily understand that right so let's move further to understand this problem with help of example and then we will together find out the best solution for this problem right so let's move further okay so here you can see i have taken one example and left is three and right is eight okay now uh if we have been asked to find out total number of sub arrays such that the maximum element in that particular sabaday is at least three and at most right okay so let's try to pick up one sub array like uh okay so i am going to try to pick up one sub-array pick up one sub-array pick up one sub-array like this one okay so if whether this is a valid sub-array so if whether this is a valid sub-array so if whether this is a valid sub-array or not uh let okay so let me try to pick up another sub array like this one okay suppose i have chosen this sub array what is the maximum element in this sub array you can see the maximum element is coming out to be five okay and what is the minimum element it doesn't matter what is the minimum we need to focus on the maximum length right so 5 is at most right i think the right is what the value is like 8 and it is like greater than or equal to three okay so this is the valid sub array okay so we need to find such valid sub arrays uh okay so we need to find such valid sub arrays and we need to basically report total number of valid sub arrays such that the maximum element present in that sub array is at least three and at most eight how we can start thinking upon this idea how we can approach the answer this is going to be like really very much important okay now if you have been watching my videos regularly you can easily understand the what is the approach that i am going to use okay you can easily see whenever there are some conditions like left is going to be like less than right or some condition two or more conditions like one or more conditions uh if i have been memorizing that problem okay so maximum performance of a team yes right okay so if you focus on this problem and if you have watched my video what i have been said that like we have been given two parameters speed and efficiency and we need to find the maximum performance and multiplied by the minimum efficiency and the sum of the speeds what i have done is like i fixed one condition like we need to work upon two conditions some of the engineer speed should be multiplied by the minimum efficiency so what i have done in this problem like i fixed this minimum efficiency because there are two conditions we know we are not going to simultaneously work upon these two conditions at a time so i have fixed one condition the exact same thing is going to happen over here like what i'm going to do i'm going to fix this maximum array element okay so what does this help us like fixing uh or let's say claiming some element or let's say saying some element as the maximum element then how we can find out the number of sub arrays corresponding to that maximum element okay so if you're not going to understand this no need to worry about let us understand this problem in a much more simpler way and what is that simpler way okay so let's say that this is a maximum element and we don't know the left bound of the sub array that i have chosen and that is the sub-array that i have and that is the sub-array that i have and that is the sub-array that i have chosen we don't know the left bound and we don't know the right amount maximum element of some sub-array we maximum element of some sub-array we maximum element of some sub-array we don't know okay so i am going to fix this that is uh you can easily understand that what is my idea that you can also think uh like uh start thinking like that like i am going to fix every element and let's claim this as the maximum element like uh if you recall this statement in your mind that let's say area of i is the maximum element then what are the number of sub-arrays then what are the number of sub-arrays then what are the number of sub-arrays that i can choose right okay so no need to worry about if you're not going to if you are not grasping this logic let me explain in a more much more easier way okay so let us say this is the maximum element and if you want total number of sub arrays such that this element remains the maximum element you can see if you try okay so l is the left bound of this sub array and r is the right bound of this sub array and there is this there is an element five which exist in that sub array right initially l is pointing to let's say i'm going to mark this indices like 0 base 0 1 2 3 4 5 6 and 7 right initially l is marking as 3 and rd is marking as again three now initially i have chosen the maximum element as array of three and it is the value of five and l is three and r is three now my sub array is of length exactly equal to one whose left bound and right bound is going to coincide you can easily see that if i will try to extend this right bound r to some greater index like if you try to extend this r to four still my maximum element remains as five right and if you try to extend this r2 up to three that is r becomes as five and l is still three you can easily see my array is my uh sorry my array becomes five four three sorry so barry becomes five four three and still my maximum element remains as five right and that's if you start thinking about like that what i have what i'm being doing here is like i'm extending the right bound of this sub array such that the maximum element to remain same this is going to be like very much important so i can extend up to three and if i will try to extend up to eight you can easily say no i cannot extend up to it because the maximum element changes right because it is greater than 5 so it means that what is the maximum right bound of the my current sub array where i can extend uh this that is my current chosen sub ad you can see i can extend up to three okay and what about the left one can i extend it to some minimum index yes i can extend it i can extend up to two you can easily see if from this one that is up to this two up to the index inclusive i'm talking about uh index equal to one inclusive i can extend my left bond up to this index equal to one okay so my sub array can vary from okay so i can i'm going to write below one thing my l can vary from index equal to 1 up to index equal to 3 right and what is the my right bound going to vary for my current maximum element it is going to vary from 3 up to what is the maximum right index you can see five right okay so my left one can vary up to this one and my right one can vary up to this one okay so if you need to find out the total number of subarrays what is the number of elements number of indices present in this one you can see there are three different indices and in this one there are three different indices right two three that is uh alic belongs to one two three and r belongs to three four five three different indices for this one and three different indices for this one so my answer as total number of sub is for my current maximum element area of y equal to five is going to be incremented by answer equals answer plus okay and this is the let's say the total number of values for this one is as the left okay so not calling as left i'm trying to call it as backward and let's call it as forward so my answer is going to be incremented by backward into forward y into that is why there's a multiplication sign the reason is quite simple there are total backward amount of left bounds you can choose for my current element to remain as maximum and there are forward amount of right bounds you can choose so such that the maximum element remains same for my current chosen sub array so there are total backward into forward amount of subarus we can choose for my current element to remain as maximum okay so what is my total answer would be like okay so i'm going to write it out total element total answer is going to be summation i equal to 1 up to i equal to n of let's say backward of i into forward of i this is my answer right so summation backward of fine to forward over what is backward of my backward of i is the what is the least index such that my maximum element array of i remains as maximum okay and not the least index it is the count sorry for speaking some wrong words this is actually the count you can see the backward of this one is actually the value count and it is actually the number of elements in this range and forward is actually the count the number of elements present in this range so backward defined forward of i are the respective values where the maximum element remains as maximum what is the least that is we can minimize this l that is the left one such that the maximum element remains as maximum also we can maximize this right amount so that the maximum elements remains as maximum and backward fi and forward eye forward of is basically you can easily say i minus l minimum you can easily say backward of i and that is i is current index minus l minimum and forward of i is like r maximum minus current index and we need to find the summation for every element why for every element we can we are trying to just figure we are trying to just fix it out that we are trying to just claim that the current element is the maximum element and how we can fetch the answer by considering this as the maximum relevant okay so how we can implement this in the coding part let us try to understand this in simpler words let's move further all right so in the previous one you have seen that like this is actually the array and if we sort the elements of this array on the basis of a pair and what is that pair i am going to say i am going to sort the elements on the basis of nums of i comma the index why i am going to sort this on the basis of this okay as i have already said that if you try to fix one of the element that is claiming that it is a maximum element the main thing that is going to vary upon is like what is the minimum index that is you need to find the next greater element and next smaller element right that is if you focus on the previous thing that if you are trying to claim that 5 is the maximum element the next greater elements index is 8 and the next greater element to the left of 5 is 9 okay you need to find the number of elements present in this range right if you try to focus one thing that both 9 and 8 is greater than 5 right it signifies that you need to process the elements from the backward side okay and how it is going to help us let us try to understand that it is going to help us if we try to sort the elements on the basis or norms of i and i then we will try to process the uh indexes note that i'm talking about index okay so if we try to process the array of vector pairs from the backward side and i am going to talk about the index i will store stored index in a set in stored index in a set how this is going to help us okay no need to worry about this is going to help us and the reason is quite simple okay so let us try to understand one thing also like if you move on to this one let's say i'm talking about this element four okay so this element four okay uh so this is actually being rubbish so this element right so what is the force next to greater element to the right of it you can see force next to greater element to the right of this is eight okay and what is the eight index is coming out to be six okay and what is the force next greater element to the left of it is coming out to be five and its index is three okay and let's say let's see how it is going to help us okay so i think i've missed some two three four eight nine okay two three four eight nine three elements six into eight elements three elements i think i've missed one element okay so i'm going to write as 5 as okay what is the index of this 5 is coming out to be 3 okay so what i'm going to do is i'm going to process the indexes from the backward side okay and let's say we are at a uh we are at an index and what is that index of 4 index f4 is coming out to be 4 okay so index of four is coming out to be four and okay so when we are at this index right when we are at index equal to four we can easily answer if we store the value of indexes in a set like four three six zero seven okay so let us store the values of indexes in a set and so set will store the values in non-decreasing order right now in non-decreasing order right now in non-decreasing order right now so zero three four six seven okay and let's say we are talking about this value element 4 the one thing that arises in your mind why to uh so go from the backward side and y to sort the elements on the basis of vector pairs as i have already said that for every element you can see i'm talking about the element four the next greater element is to the left of this five and next greater element to the right of is eight you can see both the elements are greater than my current element it means that you need to process the elements from the value that is from the maximum value and it goes up to the minimum value right that is you need to process from the back side of the array and the array must be sorted in increasing order okay so if you store the elements in a set it has the value 0 3 4 6 7 and if you claim that 4 is the maximum element then how you can increment your answer what is the backward of i and what is the forward of 5 you can easily see if you try to find out the next greater element of this 4 note that the term next greater element of this 4 what is the index of 4 okay so let us try to fetch the index of 4 you can easily see the index of 4 is coming out to be 4. okay now one thing that should be kept in your mind that all the elements in the set whose indexes are present are all that is all are all the elements of the value greater than or equal to my current value okay so if i will try to fetch the index equal to 4 the next index is going to correspond the index of the next greater element of the value 4 right and also the next greater element to the left of it that is the index being smaller than 4 this one is going to be this one okay and if you need to find the backward of y backward or pi the difference of this and forward of i is the difference of this six four is coming out to be two and four three is coming out to be one this is the backward of i and this is the forward open and you need to do the things in a backward in a backside manner you know that is when you sort the array and process the elements from the back side so this is the backward defined this is the forward of i and if you product this one you get the number of sub-values for the current number of sub-values for the current number of sub-values for the current element okay let's uh cross check it out if the values that i have getting is correct or not so if you look over this one like if you look over this 4 what is the backward of i you can see the next greater element is 5 so you can choose the l minimum as the index equal to 4 so the only one element is going to be corresponded in the backward of i and what is the forward of i what is the rmax you can see rmx is coming out to be this index equal to five so my answer would be like only two elements you can include this four or you can include this three you cannot include this eight it is present at index equal to six so i'm not going to include this eight i can include these only two elements so my forward of 5 is coming out to be 2 and if you cross check this value you can see as it is coming out to be correct so it signifies that we can process the elements from the back side of the array okay so let's move further to the coding part okay so where is that okay i've already submitted some bullets why not to show that one okay i have also tried to do this problem with the help of next creator element using stack and like with help of stick but i am getting a frequent wrong answer like i don't know the test cases were like this one and there is some flaw in this one i am not able to figure it out so i have done using binary search okay so moving further to the explanation of this i've taken answer as zero and as nums dot size i've taken a vector we have sort on the basis of numbers of y and i and you can see that push back the elements as numbers of y comma i index i and the value corresponding to that and sorted in non-decreasing order and now i'm in non-decreasing order and now i'm in non-decreasing order and now i'm processing from the back side right i equal to n minus 1 i greater than equal to 0 i minus you can see i have push back the minus one and an element and into my index uh index is basically the set that i'm going to maintain so that i can find the next uh greater element index and next is ma that is the next greater element to the light of my current element index and the next greater element to the left of my current elements index with the help of this index set by taking the lower bound or upper bound you can see what i have done is like start processing from back side of the array of vector pairs okay so index first have inserted the indexes note that the term that i am going to used over here like i am working on the index right each time why to work on the index because i need to find the number of elements okay so if my range current value that is vi dot first that is the numbers of i value is not in the given range just move further no need to find the number of sub arrays corresponding to this maximum element otherwise find the next pointer which is basically the index of the next greater element to the right of my current element and similarly the previous one with the help of this find one using set dot find and just decrement one position backward okay and what is the number of elements to the left of it by using this is actually the backward and it is actually the vi dot second minus the previous index value okay and this is the forward and total number of sub arrays possible would be like backward into forward considering current element as the maximum element right and finally return the answer so this is basically the accepted code so if you have any doubts do let me know in the comment section of the video and do not forget to like this video share this video and do subscribe to youtube channel for latest updates thank you for watching this video
Number of Subarrays with Bounded Maximum
k-th-symbol-in-grammar
Given an integer array `nums` and two integers `left` and `right`, return _the number of contiguous non-empty **subarrays** such that the value of the maximum array element in that subarray is in the range_ `[left, right]`. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,1,4,3\], left = 2, right = 3 **Output:** 3 **Explanation:** There are three subarrays that meet the requirements: \[2\], \[2, 1\], \[3\]. **Example 2:** **Input:** nums = \[2,9,2,5,6\], left = 2, right = 8 **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `0 <= left <= right <= 109`
Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?
Math,Bit Manipulation,Recursion
Medium
null
168
hello everyone so today we are going to solve problem number 168 Excel sheet column title or lead code so what this problem States is quite simple given an integral column number return its corresponding column title as it appears in an Excel sheet so we need to first see that how the column numbers are mapped in an Excel sheet so a is mapped to one B is map to 3 C is map 2 3 and similarly wise map to 25 and ready map 226 then when we see 27 it's mapped to a so what we observe in this number system is that there are no zeros so this is the main point to see here that there are no zeros what we naturally have in another number system is 0 should be mapped to a one to be and similarly 24 to Y 35 2 Z but what happens here is the our number system starts from 1. so that's the thing we need to notice and now let's see examples so similarly you can see the example one is you have to a and 28 is mapped to a b 7 0 1 is map 2 z y how can we solve this problem so what we normally do in a number system we simply divide by the base of the number system for example if here we are given one we would have divided it by 26 and the remainder is our answer going from bottom to top like we do bind it to decimal conversions similarly we have to do here also we have to convert base 10 number to the base of 26 but what's unique in this is that there is no zeros so we need to take care of that and it will be more clear when you see the next example how we change this to this so when the h26 divided by 20s 26. the one is quotient and our remainder here is 2 and again here is one so till now you might be thinking okay there is no problem if there is there are no zeros you can simply map this to be and these two is similarly here also we can have this today but the problem occurs when the number is seven zero one when you try to divide it by 26 the cocity 26 and the remainder is 25 here also if you follow the double convention we can map it to Y no problem but what happens next see this when we try to divide this we get one is percent and 0 as the remainder but in our number system there are no concept of zeros so which number will map this to so this is the where problem lies and we if we do it again so our result will be a something and Y so how can we recover from this problem so to recover from this problem what we do is at each step we first subtract minus 1 from here then minus 1 from here in similarly and so on so in each step we try to subtract -1 -1 -1 and rest of the procedure is similar to normal conversions so Baseline to Binary decimal to page 26. so what we can do let's take this example over here when the number is 701 what we do is first subtract minus one number becomes 700 and then we divided by 26 now the question will remain same but our remainder will become 24 and this we can simply and we can now follow the above convention 0 to a 1 to B and so on so now our 24 will map to y and as we are subtracting minus 1 in every step so we subtitude minus 1 and we get 25 as quotient then we again divide by 26 and our quotient is 0 and our remainder is 25 which is nothing but Z so now we can see that we are getting our right answer the code is very simple now let's move to the code so how can we code it so as seen previously what we need is an string answer to store the answers they will initialize it with NP string next we will Loop by the number is greater than zero and at each step we need to subtract -1 and at each step we need to subtract -1 and at each step we need to subtract -1 so we will do minus now what we need to find the character you need to find the character that should be added in the end of the string so you can say cash CH what will it will be me that's as you can see here it's the remainder and divided by 26. so column number modulus 26 so that's it now we need to edit in our answer as a plus equals ch and also we need to divide the column number by 26 for the next step but we observe that we are adding numbers from top to bottom here first we add y then we add Z so our final answer should be in reverse order CBC Infinity reverse it and so dot period and so dot and it's a property of the string class and we will try to return the answer let's see if it's runs now let's try to submit it so submitting well so what will be the time complexity of this as we can see we are dividing by 26 at each step so the total time complexity will be quarter number log 26. or log caller number to the page 26. and what is the space complexity will also be the same because the length of the string will be same as a number of times this while loop runs and the time complexity for reversing is linear so there's that thank you and see you in the next video
Excel Sheet Column Title
excel-sheet-column-title
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnNumber = 1 **Output:** "A " **Example 2:** **Input:** columnNumber = 28 **Output:** "AB " **Example 3:** **Input:** columnNumber = 701 **Output:** "ZY " **Constraints:** * `1 <= columnNumber <= 231 - 1`
null
Math,String
Easy
171,2304
1,480
hello friends in this video we are going to see how to find the running sum of an array so it's a one-dimensional of an array so it's a one-dimensional of an array so it's a one-dimensional array so it should be very simple so let's say we have an array one two three four 5 so how do we find the running sum so running sum means sum till current index and we run from left to right so when we are here at the first position the running sum is just one the sum of all elements to the left so there is nothing to the left of one so running some till this index is one running sum till this index two is sum of these two that is three running sum till third index is three plus two plus one that is six then we will add this complete thing 10 and finally 15 so this result will be same size as the input array so how did we find it so one naive way of doing this would be that for each index scan from 0 till this index current index and calculate the sum when you reach here the second index you again start from beginning and reach till here so on for nth index so that way you will take for first one time step for second one you iterate from beginning till second for third beginning till third and so on so this is very familiar sum and into n plus 1 by 2 so you see it's o of n square so this is a nice way of doing it but we will not do that so you if you see that if you have one two three four five so the running sum here is one running sum this is one plus two then we have 1 plus 2 plus 3 plus 4. so you see that while calculating this sum of first second third and fourth in the previous step we had already calculated sum from 1 to 3 so this was already there so we could have just used the previous sum and added the current element so that would be constant similarly while calculating the third running sum uh in the previous step we have already calculated one plus two so no need to again scan we could have used the previous value and added the current element so again constant time so for n elements it will take 1 plus 1 or some constant times 1 maybe 2 and so o of n and now depending on whether you are allowed to modify the input itself or not you can take additional o of n time of n space or o of one space so i will call it one so if you are not allowed to use not allowed to modify the input array then you can create an additional result so let's see this problem in lead code so this is the problem and you can go through a couple of examples so we will go with the case where we are allowed to modify it if it's a const then you are not allowed to modify it you will have to create another result vector but in this case we will modify it as it is so you see that running sum for the first element remains the same because there is nothing to the left of this and you could have added some checks if zero length was allowed but in this case length is always more than one so you can skip that check so what we will do we will start from one we are modifying this vector itself and zeroth index remains same and that's it so this loop takes off and time so overall is of n and spaces of one the solution is accepted and if you see the runtime we are pretty much here it takes 4 millisecond if you run a few times it can take 0 millisecond also now let's do it in java and python there is not much change required java solution is also accepted finally we will do it in python 3. and the python solution is also accepted
Running Sum of 1d Array
movie-rating
Given an array `nums`. We define a running sum of an array as `runningSum[i] = sum(nums[0]...nums[i])`. Return the running sum of `nums`. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** \[1,3,6,10\] **Explanation:** Running sum is obtained as follows: \[1, 1+2, 1+2+3, 1+2+3+4\]. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** \[1,2,3,4,5\] **Explanation:** Running sum is obtained as follows: \[1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1\]. **Example 3:** **Input:** nums = \[3,1,2,10,1\] **Output:** \[3,4,6,16,17\] **Constraints:** * `1 <= nums.length <= 1000` * `-10^6 <= nums[i] <= 10^6`
null
Database
Medium
null
148
hey what's up guys how's it going this video i'm going to go through this later 148 short list this problem was asked by amazon microsoft bloomberg apple and facebook in past six months as you can see this is not the most popular question of nico but i think it's pretty educational let's take a look at it uh we are given the head of a linked list return the list after sorting it in ascending order so let's say um the length list we are given is four two one three what we need to return is one two three four uh with the original one sorted okay uh this is like another example negative one five three four zero after we sort it you'll be negative one zero three four five um this is a edge case where if we are not given the hat just written empty linked list so also we have the same constraint on the number of nodes uh possible also the number of value possible we are going to solve this problem using a merge sort uh you're not too familiar with the concept of merge sort i'm gonna leave a link to that video in the description down below so we will apply the merge sort in linked list in here so um first uh we have a function i'm gonna graph the function later this merge function um so if so this is the main function uh short list right so uh first we have the edge case if the head is none or the head dot next is none just directly return the head yes that means if we have only one element in the list or if there is no element in the list we just return um the node itself okay and now first we use the fast and slow pointer to break up the given language in two halves and then when we get out from this while loop the slow will be the head of the second half periods will be the tail of first half and now we want to break it up right so we have to break we have to make the previous dot next equal to none so this is where we break it up now we have the left and also have the right so basically we recursively call this function and we so this is the basic concept of um the splitting in the merge sorry so basically we recursively call in this function until uh we get only one element in the list yeah in the list or they are sorted right so the left one is equal to self. uh sort list and then we inputted the uh the head of the first half and now because the slow is the head of the second half we also do the same thing i call it right after we have the left and right we just put them in the merge function that i'm going to go through with you so we have the dummy head i initialize the function as a negative infinity also of the current which originally points to the dummy head while a the given list given a list and given b list is not empty we pick the smaller value between the two and then we traverse the a linked list and the b link list and then pick the smaller one right so if a dot value is more than a b dot value and then the current dot next equal to a which is just the smaller one and then we'll move forward the a uh linked list right a equals to a dot mix at the same time we move forward the current one current equal to current dot next on the fifth side when um the b is smaller we're doing the same thing for b right at the end after we get out from this while loop maybe a is not finished or b is not finished and then we directly concatenate the remainder of a to the current at the end we just return dummyhead.next so this is it basically is a linked list version of the merge section of the merge sort algorithm submit that time complexity wise is going to be o n and sorry not b o then speak of n log n for a standard merging um merge sort algorithm and for space complexity equilibrium will be 01 as you can see we have only some pointer here and there we didn't have we didn't create any external spaces right and yeah this is my solution this problem i hope you find this helpful thank you very much so much for watching see you next one bye
Sort List
sort-list
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 5 * 104]`. * `-105 <= Node.val <= 105` **Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
null
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
Medium
21,75,147,1992
347
what is going on everybody it's your boy average leader here with another video today we're tackling top k frequent elements number 347 on leak code this question is commonly asked by facebook capital one amazon bloomberg oracle apple and a few other companies here um i actually got this question from my bloomberg phone screening interview and unfortunately that didn't go my way i did not move on after that one and it's mainly because i messed up on my run times so that's super important well we'll go through those you know towards the end of this video but um you know before we start if you guys can go ahead and hit that subscribe and like button that would mean the world to me really helps my channel out a ton by giving it more exposure to people that don't know me and also if you guys can take one thing from this video uh go to this time stamp okay it's a big key for solving many problems like this one and with that all out of the way here we go so given a non-empty array of integers given a non-empty array of integers given a non-empty array of integers return the k most frequent elements okay cool let me see some of these examples so when our input is one two three so we see that there's three ones two twos and one three so and it's asking for the two most frequent elements so we see that one and two have the most counts so that's why we output that and we're just given an array of one and we're asked for the first most you know the first most frequent element we just output that one okay so i think uh for this one let's just go to the ipad and just do a few examples try to figure out what we're actually doing in this problem okay so working with the example that was given to us in the problem uh you know like i said we are given three ones here and then two twos and one three and because of the three ones and the two twos you know these have the ones have the highest frequency of three twos have the second highest frequency of two um you know we know that these one and two ultimately will give us the output for the top two most frequent elements right so what did we exactly do there well let's just see really quick we went ahead and scanned our input array and we just found the counts of each of our distinct elements each of our unique elements so for one we notice that there were three of them right three there are three ones and for two we noticed that there were two of them and for threes we noticed that there was one of them so in order to get uh the k most frequent the top two most frequent how can we tell what's the most frequent element using these three things right uh well we see that one has the highest frequency and two has the second highest frequency so this really just comes down to ordering our frequencies somehow so how can we order our frequencies something that i'll typically do in an interview setting is think about all the data structures that i could use or maybe just think about all the data structures and then just narrow down what we could actually use so off the bat let's just think about this so we have array list linked list we have q we have stack um we have heap we have binary tree bst binary tree of sorts um what do we have a deck and oh hash map hash set okay so we'll just use these for now um but let's just think about this what could give us some sort of ordering well we have an array list uh and you know that one has like some sort of we have a collections that sort that we can use there so we'll keep that one in mind linked list i'm sure it also has collections that sort but you know it's just the same as arraylist q stack i don't really see being useful here so i'm just going to take those out um just because q and stack are like ordering in the fifo and rifle first in first out and last in first out so i really don't think we need that here keep this one's interesting because this one will always have access to the minimum element at the top or the maximum element at the top um and if we have the maximum element at the top then we'll have the second max element right after it we'll have the third max element right after it if we have a maxi so that's interesting we'll keep that in mind vst maybe doesn't make really doesn't make a lot of sense deck doesn't make a lot of sense hash map hash set uh doesn't make a lot of sense here and in our case so using our the ones that we have left right heap arraylist and link list i really like how the heap keeps like if we have a max heap we can keep the max elements or the most frequent elements at the top so most freak at the top and then the second most and the third most and the fourth most and so on and so forth which in a way is kind of what we're doing here right like if we were to somehow manipulate the heap so that we can put one so your output if we can manipulate it somehow so we can put one at the top because this one has three occurrences and then two after that because this one has two occurrences and then three after that since this one has one occurrence and just popped out k elements because we're looking for the k frequent elements if we just say in this case k is two so we just pop this thing twice we'll get one and two which is exactly what we need so this one will run in uh n login and login time um let's just use this for now and we'll talk we'll think about optimizing later so using this strategy what are we exactly doing let's just do a quick rundown all right so step one get the counts of each element and then step two is store elements in heat by count and step three really just pop out okay elements perfect so uh yeah that's how we'll start with this problem let's get into the code all right so first things first like we said let's get the counts of each of our elements um and i guess before we do that one important thing that i think we should know is will our input our numbers in our array always be positive because if they're always positive we can get our accounts uh we can store our accounts in an ins array but if they're negative also then we need to use a hash map so that's something that i'd clarify with the interviewer up front in our case let's just make a custom test case and we'll put some negative numbers in here and if we uh if this runs properly then we know that this can handle some negative numbers and if not lead code will tell us uh hey you know we you can't be using negative numbers so i'll just return null for now for the sake of the test let's run it oh well would you look at that what is this size frequency oh my bad because it says k is always a valid number so yeah now we see that uh with negative numbers and we make our max number one we see that it's still we're still expected to output negative one so that being said we're going to have to use a hash map to store our counts okay so i'll call that counts hashmap awesome uh the first thing we're gonna have to do is iterate through our nums and basically if it's already in our hash map let's just increment whatever value is held in our hash map by one and if it's not in our hash map we're just going to make a new we're just going to put a new key value pair with the value being one for that element okay so we do something like four and num in nums basically iterating this num is iterating through all these uh nums um we will put the key value pair in our hash map so we'll do clowns.put in our hash map so we'll do clowns.put in our hash map so we'll do clowns.put num which will be our key and our value will be counts.get or default counts.get or default counts.get or default num or zero plus one so for those of you guys who don't know what this method is it's a very cool method provided to us by the hashmap where basically uh if our key is already in our hash map okay if our key is already in our hash map we're going to get it get that num and we're going to get that key and we're just going to increment one now if the key isn't in our hash map let's just say uh we're putting in one for the very first time okay it's not in our hash map right so if it's not we're gonna default to zero and we're just gonna add one to that zero it's a very cool method provided to us by the hashtag very useful and yeah so now we have the counts for each of our elements now the next step is to make a priority queue right that's what we said we're going to do so and this priority queue will hold integers equals new priority q now we what are we storing in the priority queue we're storing the elements based off of our counts so we have the elements here in our nums and we have the counts here so how can we put those elements in our priority queue this is going to be another question another type of problem where we need to change the implementation of our priority queue and do you if you do you guys know how a priority normally works well if we have a min heap okay and we're going to put in values 3 2 1 it's going to hold the min heap will be one two and three assume assuming that uh the left is the top of the heap and the right is the bottom of the heap so how is it actually like reordering these well in the priority queue implementation there is actually a comparator that's passed in one thing that we can do is define our own comparator just like we did in the reorder data in log files problem that we just did a few videos ago so once again here we're gonna have to make a custom comparator and luckily since we watched that video we're like pros of that so let's just do that up here we'll make a custom comparator this one will hold integers since we're comparing integers and we'll call it comp equals new come comparator oh my gosh if i can spell and inside of it we're going to need what that's right we're going to need a compare method like we did before and we're going to compare integers in this one okay into b now how can we get the counts uh of each of our numbers that we're going to be passing in well first things first let's you know obviously this comparator to get the counts all we're going to have to do is do something like counts dot get a and this will get us our counts for our frequency of a and counts dot get b will get us the frequency of b but obviously you know counts is in a whole new method counts the visibility of counts is between these two curly braces so to ensure that counts can be seen everywhere in this comparator as well as this method let's just uh make this global let's make counts a global okay so now this has visibility uh now counts can be visible in this method so now similar to the last problem we're making a max heap in this situation right and i want you to visualize this a max heap is kind of like it's you know a heap is backed by an array so let's just kind of visualize it like an array in heaps the top of the heap is the left side of the array okay so top of heat will be left and then the bottom of heap will be the right of the array okay so knowing this let's just say the counts of a and here uh that the way i'll do this i'll say frequency of a equals counts dot get a and the frequency of b is uh counts dot get b now remember there's three situations and i explained this much more in depth in that last video so if you guys in my reorder log files video so uh if you guys want to go check that one out i think it would be very helpful for you guys to watch that video through especially the my compare parts compare method parts my comparator parts and then come back to this video but a quick summary this compare method will either return a negative one uh a positive one or a zero and if it prints out a negative one that means uh that means these two based off of the positions of these parameters if we print out a negative one the first parameter will come before the second parameter okay so that will output something like a b or in other words in our max heap a will come before b and hence a will be at the top of our heap now what does this mean we that means that a needs to be greater than b for it to be in our max heap right now if we print out a positive one that means according to our parameter order since a comes before b if we print out a if we output a positive one that means we're saying that b needs to come before a or in other words b needs to come before a and what does that mean that means b is at the top of our heap that means the counts of b the frequency of b has to be greater than a so with this information we could basically say if our frequency of a is less than our frequency of b that means we want b to come before a in our heap right we want b to be at the top of our heap so what do we have to output a positive number or in this case we'll just output a 1 positive 1. else if frequency of a is greater than frequency of b well that's great that means we want uh our order to be so that a is at the top of the heap and b is at the bottom of the heap so what do we need to output to get this order where our parameters of where the first parameter will come before our second parameter we need to output a negative number so here we'll output a negative one and in case either of those two don't trigger uh you know let's just say we have two of the same numbers like if we are if our input is one here and one here well we don't really want one to be greater than you know not one won't be greater than the other one won't be less than the other so that means we'll just return them in the order that they came to us uh so we'll just return zero that's the equivalence of returning zero so now we have our comparator this will be the comparator for a max heap okay so let's pass in this comparator as one of the parameters of our priority queue since it since the priority queue takes a comparator as a parameter now perfect we have a priority queue that will function the way we want it to function so now let's just uh iterate through our numbers and put everything in a priority queue so here is one problem that i see us facing if we iterate through nums we are going to put in one two three but in reality all we want is one two and three because if we were to put all of these and we were to pop out k elements if we popped out two elements then all we'll get is one and one since these are the highest frequency um but in all three of these will be at the top of our priority queue so is there a way where we can just get these uh unique elements in our accounts well there's another method that the hashmap has and it's called keyset and this will give us the unique keys that are in that hash map so let's just iterate through whatever is in our key set so for enter key in uh counts dot key set it looks like this oops looks like this let us put those elements in our priority queue uh pq dot offer key and since in our comparator we're getting the counts up here right it's only going to sort uh it's only going to sort its elements in the order of its counts which we've defined up here okay and finally we need what's our output it needs to be an array so let's just make an output array uh answer equals new ins and how many elements are going to be in it there's going to be k elements so let's just iterate through our answer array nice less than that length i plus and we're just going to pop off k elements from our priority queue and we're going to store those values in each of the indices of our answer array so answer i equals pq dot pop or it's not p dot pop it's actually remove uh in a priority queue and um yeah finally we'll just return answer and let's run that see if that works they ask you how you are you just have to say that you're fine when you're not real oh my gosh i'm so sorry guys hashtag uh two parameters here it needs to be two integers because uh remember the first parameter here or the first argument here is the key and the second parameter here is the value so just remember that sorry about that let's run that awesome so that works let's submit that yes all right nine milliseconds faster than 83 okay so now let's think about the runtime of this we've already mentioned that this would be an n login runtime now at this point the interviewer will ask like okay is there any way we can make this even more efficient and even leak code has this little hint on the side your algorithm's time complexity must be better than o and log n where n is the array size so let's think about this um and i think the best way we can do this let's just go back to the ipad and uh and think about this problem so this current solution like we said earlier will run in n log n time so let's dissect how we get this n log n times log n so this n log n represents the worst case time complexity so what would be a worst case example well let's say we were trying to find the top two most frequent elements but let's just say everything had the same frequency like one our input was one two three four five everything has the same frequency but we would still need to go and iterate through everything once right and that iteration is happening with this end and upon each iteration we're adding to our heap and we know the add operation in a heap is log of n where n is the size of the heap at each iteration we are doing a log n operation and since we're doing a login operation n times where n is the size of our array uh input array our overall runtime becomes n log n but can we do better than this okay well i'm thinking at a worst case we always need to iterate through the entire input array so i feel like this end is important i don't think we can do better than that but now let's think of the this end right here could we do better than that well let's see that's that n represents the size of the heap do we need to always keep all of n elements in the heap i don't think so because in this situation we're only looking for k elements so what if there was a way where we could store only k elements in our heap and this kind of makes sense right because after all of our uh work that we're doing at the very end we're only popping off k elements so why would we need to put in n elements then pop off k right after i think it would make more sense if we can just always store k values k elements in our heap and then just pop those um so what would that look like well right now we're working with a max heap right and now in a max heap let's just say i'll just make a one right here uh bottom so at the top of the heap we would have the max value um by frequency so what if we just kept k elements in our heap let's do a little example and see how we could possibly do that i think it's and here let's just say k equals two so i think it's safe to say that no matter what let's always add k elements so let's iterate through this input array okay so we have one two these will be our two elements in our uh heap and what are we storing in our heap remember we're storing or sorting our values based off of its frequency now since each of these has a frequency of just one let's just store them uh in the order one two it doesn't really matter since they're the same uh frequency now let's check three does it have a frequency that's greater than the top of the heap uh in this case one well no three there's only one three in this array so let's just keep going uh four is there a better frequency is there a greater frequency of four than one no is there a greater frequency of five than one no but now let's go to six we see that there's two sixes so the frequency of six is two that's greater than the frequency of one so let's just pop off the last element in our heap it's assuming that there's less occurrences of two than one so let's just pop off that number and then we will put six at the top we'll compare it to one since there's only one and there's two sixes we'll put two i'm sorry six at the top of the heap okay so this works in this example this would be an n log k example um let's see if this method works for another test case so in this particular one we see that like our most occurring thing happened at the end of our input array let's try having the most occurring element in the beginning of our array so i'm going to do some erasing here so off the bat we're going to store k elements in our heap so we see that there's three sixes and there's one so we'll put six at the top and one at the bottom right one right next to it now let's go check two is two does two have more occurrences than the top of our heap no there's only one there's five have more occurrences than the top of our people it has two we see but it's not greater than six so we're not going to put it in there but we notice here just by doing like the eye check a visual test there's three sixes and there's two fives so uh six and five should be the k most frequent elements but according to our algorithm it's not really going to work in this case the only way we can put five in is by comparing it to something that we know is smaller in the heap like for instance let's just say in an alternate situation if one was actually at the top of our heap and six was at the bottom then we can we could check to see if the occurrences of five is greater than the occurrences of one and in this case it is so we then we would just uh put five in our heap but what did we just do there so in this case uh we had six at the top one on the bottom this was the maxi right but now if i put one at the top and six at the bottom that's just a min heap isn't it so what if we just changed our max heap to a min heap and kept adding elements into our min heap only if the occurrence of that element is greater than the top of our min heap hmm i think that would make a little bit more sense so let's just run through this example one last time or better yet how about let's run through uh the example that was given to us so in only code our original example was in this case uh you know the most occurring number happens in the beginning so we don't need to worry about anything now we're going to make this not a maxi we're going to make this a min heap so let's store k elements off the bat we'll store one and two now remember since this is a min heap there's two there's only two occurrences of two and three occurrences of three and according to our comparator which now we're gonna have to change let's make sure that it's still gonna be ordered based off of uh the total number of occurrences of each character of each element each number since there's two twos and three ones and this is a min heap that means two needs to be at the top and one would be right after that now let's look at three is three uh does three have more occurrences than two no okay good so then now we just pop off these two values and we have an array but now just so we get a really big picture of what's going on let's say we have four threes okay so now we go to three we notice that there's four of them now does uh three have more occurrences than the top of our heap well yes there's only two twos and there's four threes so let's remove the least occurring element which is this number two and let's add three now three would go at the bottom since there's uh more occurrences and that means one has now the least occurrences but once we're done iterating through everything we are left with the k most occurring elements in our array so hopefully that made a little bit of sense um and this is the approach we're going to do let's get right back into the code and let's change up a little bit of things okay so first things first let's make our priority queue a min heap so currently it's a max heap because of our compare implementation but to make it a min heap it's really simple all we're going gonna have to do is change it just make our current comparisons the opposite of what they currently are so this less than we'll make it a greater than and that's greater than we'll make it a less than okay now we have a min heap okay so now let's only store k elements in our priority queue where are we adding to our priority queue it's only right here so in case the priority queue is empty let's always make sure that there are k elements in our priority queue the way we can do this is if the priority queue size is less than k let's just go ahead and add those elements to our queue so we'll do offer a key ls will have the number of elements equal k which you know we just want uh elements that are less the number of elements to be less than k or equal to k at all times so if we add something we're going to check to see if the number the frequency of our key is greater than the frequency of the top of our priority queue and the best way we can do this is by doing if hash sorry counts dot get key is greater than counts dot get pq dot peak will give us the top of the priority queue without actually removing it then we're going to want to add this key but to ensure that we'll always have only k elements in our uh in our heap let's remove the top of our cube first so we can do that by doing a poll that's a method to remove the top of the heap and then let's add our key and um this would all stay the same so let's just run this really quickly uh oh this is the first time i've ever seen this that is the first time that's ever happened so luckily nothing changed run the code okay that works let's submit make sure everything works perfect runtime is about the same but we have uh changed our run time before it was o uh of n log n and now it is what it's o n log k since we always have k elements in our priority queue instead of having all n elements so that's reducing the runtime um this would pass in an interview situation so yeah guys that's how you do that problem um you know if you have any other problems you want to see me do please let me know in the comments i'll make sure to go on and do them uh let me know if there's anything i can improve on and uh if there's anything you'd like to see different and the last thing i want to do for you guys is i want to show you guys a big interviewing tip a big interview and key so you know this is a problem that i received a while ago and i think i messed up on the run time i messed up i also wasn't sure if i had to use a priority queue at the time and ever since then i loved i love and i still do love all the priority q problems so you know in my practice i went and i did a bunch of pq problems a bunch of heat problems and here's something that i realized let me show you something on leak code i if you filter out the heap questions and i'm just going to make them order by frequency just because i like doing that notice this merge case sorted list okay closest points to the origin top k frequent words top k frequent elements uh k the largest element of stream k smallest element sorted uh matrix k and more k's and all these find the kate's smallest of distance so you guys see this little problem this sorry this little pattern if you see a k and a frequency in the same problem title just know you should probably start at least with a heap all right that's a big tip that i will give you guys something that has helped me a ton in my interviewing if i ever see anything that has a k and a frequency i go straight to heap or i'll think of like a worst case a naive brute force solution knowing that a heap was going to be used to optimize later so this is a big tip a big key for you guys um and yeah you know hopefully you guys found a little value in this video i'm really trying to make a few you know hopefully two videos a week um so get ready for the next one guys please let me know if you uh enjoy this video and if you guys can give me a good like and subscribe that would be very helpful um and yeah guys hope you guys have a great rest of the day killing our patients depressed we are the pain you can trot crooked it works
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
1,782
hey everybody this is larry this is me going over by weekly contest 47 q4 count pairs of notes so this one is a weird hard problem uh that a handful of people got at least you know an hour in and it is a way optimization problem i don't know and you know to be honest i'm not confident that my solution is the intended solution or even the best solution but it is an idea and it passed the test and it had a couple of optimization um so it became a sort of an optimization problem and i had two wrong answers uh one real wrong answer because i was i had a premature optimization that was wrong and then the second one was just timeout that i fixed value optimizing um so hit the like button hit the subscribe button join me on discord and let me know what you think you can watch me solve it live in the contest afterwards as well um but the idea here is taking note that obviously n is really big relatively so you can't do anything n square but yi is you know it's bigger but it's not n squared so that's going to be your choke point and then the other thing is just that curries is less than 20. so i don't know how that factors in that much but uh but that's the way that i thought about it um and then so we start the problem by just pre-processing into uh just pre-processing into uh just pre-processing into uh so a couple things one the core component that i thought about was uh and i'll try to do this with ascii art let's start from the beginning a little bit but the idea is that okay so you know we have degrees of every node so for example we have you know let's say we have these cases right this edge case um and then we just basically reason out the formula a little bit so we say these edges so degree of one um is equal to one two three so three degrees of two is equal to uh you know one two three four so degree is four and then so then now you can get uh the number of edges incident with any you know so for the number pair how many of them has at least you know to one of the edges right well that is just equal to degree of one oh sorry the number of incident uh edges it's just equal to degrees of one plus degrees of two this is of one two uh minus the number of edges between one and two so that's basically the formula you can kind of draw it out why this is the case because um this is because uh we count for every edge between one and two we counted both in degrees one and degrees two so that's basically how we get this formula and once you have this formula um we can con the way that i thought about it was to construct um you know now so for you know you're looking at here you can look at one right so if you know so now you can construct if degree um if node one then you know um you have then that is just you know i'm gonna write shorthand so you have this minus g of one two um i'm copying and pasting a second hang on so you have these things right and then if you look at it here this will give you a number you know let's just say a uh b c d i'm lazy right so someone like that right and then here if you put these numbers on a list you would have a b c d and let's just say that they're sorted and you know we'll talk about the implementation about it later right let's say no now we sorted these and then now we have to um now we have all everything we need to calculate how many um how many you know coming from one how many number of incident edges has greater than a query right um so basically for example let's say this looks like you know uh three four five six or something or seven i don't know it's a seven right um and of course you know that d1 is common on all the pieces so you get minus d1 on all the sides or something like that so you know so there's some optimization you can do but let's say you have that and then now you know you now you just have to search for the query for two how many you know now we can binary search on this array to be like okay uh and let me just actually rewrite this a little bit because um so now using the actual test cases um you know this is actually um i oh this is actually just copy and paste from here so it's five four there's no five so yeah so this is five four so you know so this is just in the list of four five after sorted and then you ask yourself okay you know for a query or secret two how many of our pairs are for number one right well here all three of them so three for node one and then so forth i'm a little bit hand wavy here but that's basically the idea so that and then now we repeat for each node so id so that's how we start right so now we have a pseudocoder for each node we binary search to get the answer and if we do this correctly this roughly speaking this might be n log n right um yeah and the reason why this is the case is because for each node is n and we binary search to get the answer so that's basically the idea that i had to solve this problem um i know that this is a little bit disjoint and this is a i think like conceptually it's not that hard but it's just about optimization in code and i'm gonna go over that next but basically once you have this idea um you should be able to kind of play around with the idea hopefully to kind of get the answer maybe not because it took me a couple tries right um but yeah so this is basically what i have what you would have um and then now this is how i do it so i make some optimizations which i'll go over in a second so um yeah so here we just pre-processed elder yeah so here we just pre-processed elder yeah so here we just pre-processed elder edge list we count the degrees for each node and then we just count the number of node edges oh sorry you know uh number of edges from u to v and then we just count them in an edge this kind of edge uh adjacency set if you want to call it that uh kind of like a sparse adjacency matrix if you will uh that's basically how we did it and then here um i'm gonna delete some of my debugging code um i have a this is what i call like a delta list so d list con contains uh you know before after for this note this what is before after before meaning um the degrees impact of a given um node after as you go to the degrees impact of a given node taken account node u right um given node we um so that's basically how i did it i put it in the list um and this may not make any sense in isolation so we'll go over to the next step and you can kind of see my thing right so the thing is that um if we the thing the difficulty about this problem is that um right now because we only do math on the notes that have an edge have a common edge with the um with node u right um what does that mean that means that it you know for every node in u there's another there are there's some other nodes that have common edges with you and then there's some other nodes that do not have any common edges with you right so um so here we pre-process right so um so here we pre-process right so um so here we pre-process these in um the edges that have come in uh the edges or the notes that have common edges with you uh with yeah um and their impact so the thing is that if you have to reconstruct the of and this every time and then sort it every time it's going to be too slow so because that's going to be n um ends you know for each n you have to do an n log n for sorting that's going to be too slow so we have to do something faster and this is kind of tricky and i don't know that there's a better way um maybe we'll go over it later but basically what i did is i keep a sorted list and of course every degrees and you can do this in a uh a multi-set or a multi-map multi-set in a multi-set or a multi-map multi-set in a multi-set or a multi-map multi-set in different languages or um i don't know uh maybe if you have a suggestion in your language let me know but in python the way that i do it about is using sorted list and then i just um and then i have this thing where i just you know for each query i start with zero and then i invert the so then um and if you watch me solve this live which you can watch afterwards i actually initially got um have this for loop this uh loop of the queries well in the outlet loop but i had to i'm gonna optimize it in there because of the things that we will do later which you'll see so basically for here we have a sorted list or degrees and then now we try to figure out for each node how do we modify the degrees list to answer queries for node you so that's basically what i do here and yeah and basically for you know first of all you remove the current degree because um because it doesn't make sense to kind of you know like degrees of u uh node u is not going to connect to node u so you don't have to consider it so we remove that um yeah do not consider pair you because that doesn't make sense right and then here is what we calculated earlier right um here uh um how do i say this factor in the degree impact of this node uh of these edges and as we said the be fun after is um we remove the before because that's basically the degree that um that's in the that's the total degree that is in before and then after is now this takes account the negative c which is the common edges right so this basically be like hey for each node um for each delta we just um subtract the common edges from it and then put it back in the sorted list so now we have the degrees list with respect to you right to node you to be clear and then we just do it for each query a binary search uh for each query we sum up the answer to the binary search and this is i'm not going to explain this part that much but now that you have the degrees um you know an adjacency list of degrees you basically um you know take the query that you're looking for you subtract it by the current degree because you know so you have um how does i think it's something like this you run a so for each query we want a degrees of u plus degrees of re whoops um my you know minus uh the common right and then of course this part uh we already did in the array so this is uh everything that's in the array so you plus uh this sorted list and of course you can subtract uh this thing over there so q minus degrees of u uh no and then we have to sort the list and then we have to count and yeah and basically once you find the entry point you have to count the number of things that are bigger than it right so that's where the n minus uh or this thing is and just um inclusive so that's why there's a minus one um but yeah oh let me remove this debugging and then now after we're done fix this again so that's basically the answer um it's really hard uh for me i don't know that i don't know i don't think um uh yeah but um but yeah um so basically hopefully that makes sense it's kind of tricky it's kind of hard i don't know how to tell you how to stop this but at the end we do it by two because um you see that we do we double counted the answer because we basically have like for example for each pair um here we need to play one two so each for pair one two we also count two one and one three we count three one so now so we just divide two to get it out to kind of fix the double counting and that's pretty much it um so what you may ask what is the complexity of this um so note that for each edge we will remove it uh at most uh one time from the sorted list and then add it back i guess but yeah uh so a couple of log n operations for each edge um because if you do the amortization you can notice that uh even if this looks really scary it only shows it for each edge right in total the total number of edges will be the number of operations that are done by these removals and for each edge um so this is going to be g log n or v let's say v for vertex we use to go to vertex number of vertexes is equal to the number of edges and yeah so this is going to be your laggy yi log read time because you know that gets dominated by this and of course uh you know we times it by q because that's the number of curves so q times this uh stuff yeah and this is log b still of course so yeah so that's the time in terms of space we just have uh over e space because we for every edge we store something somewhere and that's gonna be your worst case um technically i guess it's v plus g in case there's no edges so uh yeah so that's your space complexity um that's all i have i said a lot of stuff i don't think that this is very cleared um but i think if you're able to kind of manipulate it from here uh the tricky part is getting this and then the second tricky part is kind of come up with an invariant such that you can um you know modify the state and then go back and then just do a binary search i'm gonna make this a little bit smaller so you can uh screenshot it and then zoom in or whatever you like this is gonna be really simple this is a lot of code uh okay i'm just gonna uh yeah okay and i also finished uh 63rd or so you can find my code there though it doesn't have my comment but this is my code take a screenshot whatever you like let me know what you think and you can watch me solve it live next okay all right this is okay you really could explain this but okay only 20 crews that's weird so um okay oh a little bit duplicate edges that makes it weird play and log in for each undirected you so oh all right okay 2. no that's not right okay so you um hmm what that's not what so you hmm three plus one two three four this is not that's right okay oh i see what's n that's annoying the other ones wow i don't know how to do this then i was doing it another way hmm did the math wrong a little bit okay let's think about it for a second hmm that is tough if we produce one factor you now this maybe not fast enough but doesn't seem to be right that's not right i'm just messing around too much oh so this uh oh is oh because of the smaller case oh no hmm that's fine that's just this i'd like to i don't know this is too slow though maybe timeout but we're for your low because i don't know how to do it i don't well it's gonna take me a long time to figure out how to do it otherwise yeah well timeout oh wrong answer so four or five why'd i do four so these two this thumb is a little bit okay so one four connected five one two three all right and then just press the two means again so that means that you i don't know if i could solve this one to be honest okay that's correct and three hmm this is cool watch let's also collect five i mean not correct is consistent i think i double count a little bit in a weird way because i can't i only have six it should only be one actually what am i doing here so the four fours two are that good but the three this one has two which is wrong because we're searching for strictly greater than one and the two things are two degrees why is that uh and one of them it's no one there was three and one there was four so then the three one is not good why is it a two oh i messed up because i did this thing okay still maybe timeout though but at least this is better where's my other print statement but if it times out i don't know how to do it i think about a smarter way of doing it yeah so this is fast enough just not for all of them together that's the problem with lead code in general is that you have these kind of things where i did the math and it should be all right it's n log n but it's a very tight and log n well and being uh the number of edges with very tight so that's why it doesn't work see like an inspiration here how many people have solved it so far well people started very quickly uh hmm can i do this in a smaller way that's too much if i try to sort it every time i do it backwards i have to combine the curse can i combine the curse okay so much faster but is that right now this is already clearly that well uh oh i just think i just multiply by two so it should be okay so come on be fast enough it was like 10 times faster but nice yeah okay hey uh thanks for watching uh hit the like button subscribe and join me on discord let me know what you how you did this contest and how you doing each of the problems um yeah have a good day have a great weekend um you know to good health to good mental health and i'll see you next time bye
Count Pairs Of Nodes
smallest-string-with-a-given-numeric-value
You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`. Let `incident(a, b)` be defined as the **number of edges** that are connected to **either** node `a` or `b`. The answer to the `jth` query is the **number of pairs** of nodes `(a, b)` that satisfy **both** of the following conditions: * `a < b` * `incident(a, b) > queries[j]` Return _an array_ `answers` _such that_ `answers.length == queries.length` _and_ `answers[j]` _is the answer of the_ `jth` _query_. Note that there can be **multiple edges** between the same two nodes. **Example 1:** **Input:** n = 4, edges = \[\[1,2\],\[2,4\],\[1,3\],\[2,3\],\[2,1\]\], queries = \[2,3\] **Output:** \[6,5\] **Explanation:** The calculations for incident(a, b) are shown in the table above. The answers for each of the queries are as follows: - answers\[0\] = 6. All the pairs have an incident(a, b) value greater than 2. - answers\[1\] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3. **Example 2:** **Input:** n = 5, edges = \[\[1,5\],\[1,5\],\[3,4\],\[2,5\],\[1,3\],\[5,1\],\[2,3\],\[2,5\]\], queries = \[1,2,3,4,5\] **Output:** \[10,10,9,8,6\] **Constraints:** * `2 <= n <= 2 * 104` * `1 <= edges.length <= 105` * `1 <= ui, vi <= n` * `ui != vi` * `1 <= queries.length <= 20` * `0 <= queries[j] < edges.length`
Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index.
String,Greedy
Medium
null
1,716
hello and welcome back today we have 1716 calculate money in leod bank in this problem we have a user hery who wants to save money for his first car he puts money in the leod bank every day the first Monday he puts in $1 and every the first Monday he puts in $1 and every the first Monday he puts in $1 and every day onwards he adds a dollar more than the day before then on every subsequent Monday he will put in a dollar more than the previous Monday then given n which is the total number of days he has to save up for his first car return the total amount of money he can have in his bank at the end of the end day so if we look at a calendar it's basically saying hery will start by saving a dollar on the this was not a good calendar a dollar on the first Monday and then two on the second Monday three four uh it goes on and any more weeks and then every subsequent day he adds a dollar more than the previous day so 1 + dollar more than the previous day so 1 + dollar more than the previous day so 1 + 1 that's two three four then in the next week instead of adding one to the previous day instead we added to the previous Monday so instead of adding one to seven to be eight we add one more to the last Monday so we had two and from here we have three four five six so this first week we start with 20 days once we process the entire week we have 13 days remaining once we process this week we have six days remaining so if we have six days remaining that means uh we have four eight and nothing for the seventh day then if we subtract what would be a full week's worth let's say seven uh we basically end up with no more Zer no more days to process okay so then what is the total we can get the total by uh summing the range between first week is 1 to 7 so 1 2 uh 7 + 1 that's week is 1 to 7 so 1 2 uh 7 + 1 that's week is 1 to 7 so 1 2 uh 7 + 1 that's 8 since it's non-inclusive so this is 8 since it's non-inclusive so this is 8 since it's non-inclusive so this is going to be 28 then sum from two 2 8 would be 2 8 + 1 is 9 this is 2 8 would be 2 8 + 1 is 9 this is 2 8 would be 2 8 + 1 is 9 this is 3 5 and then sum from 3 to 8 is 3 to 8 so 8 + 1 is 9 8 is 3 to 8 so 8 + 1 is 9 8 is 3 to 8 so 8 + 1 is 9 33 so here we have 33 and then if we sum those up which is 28 + 35 + 33 we have 9 those up which is 28 + 35 + 33 we have 9 those up which is 28 + 35 + 33 we have 9 and that's also what we get here and they do illustrate this well um I thought the calendar might help a bit to visualize that every week gets one incremented from the previous week and every day for that week gets one incremented from the previous day Okay then if we translate what we did here into code uh basically we what did we do we had some total that we were tracking and we're going to get the total per week and we had some number of days which is n I'll call it days just so it's easier to understand what it is and we also keep track of what week we're on first week being one every subsequent week being one uh added to the previous week okay and we say uh what do we care about as long as we have some days remaining so while days is greater than zero uh we process that week which will be 4 day in range of the minimum of whatever days we have remaining and that's just in case we have six days remaining um instead of seven being the whole week but if you only have six days remaining we only add want to add for the 6 days so minimum of days or seven being representing the full week we will add to Total uh whatever is the week we're on plus whatever is the day we're on so the nth week plus the nth day is what we add to the total and once we do that we say okay we process this week so let's yeah let's increment our week but also uh make sure to decrement from our total days remaining so a full week is seven and in case this week has less than seven days that's okay because days will no longer be greater than zero and we will exit out of the while B weights and end my return total and submit and there you have it uh this was 1716 calculate money in Leal Bank where we have a user that's saving a dollar more than the previous week every Monday and a dollar more than the previous day for every day of that week for each week this is running in your time we're visiting each day at most once and we're using constant variables so uh constant space and next time is O M spaces o1 and there you have it um thanks so much happy coding hope to see you next time
Calculate Money in Leetcode Bank
maximum-non-negative-product-in-a-matrix
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Array,Dynamic Programming,Matrix
Medium
null
1,002
yeahyeah Hi Hi Hi everyone, I'm a programmer. Today I'm going to introduce to you a problem titled finding common characters. The detailed problem is as follows, give us an answer. table A is a piece of broom hit by this cursing net has only unknown characters Hoa Return list a list of all characters that appear in all strings in the master lists that include including duplicate characters then we have an example if a character appears 3 times in all the strings but not 4 times then we need to include that character three times in the argument The owner of the returned results is that you can return the results in any arrangement. In any order, we go into the clear oil with the set group when we have a table A consisting of Ba curses the first owner is Bella, the owner says it's level and the 3rd owner Royal, we see the letter b only appears once. Ask the character Bella in the level character without the letter B. The checkered character also doesn't have the letter B so B does not appear in all the characters in the string in all the characters in this piece, so B is not in the cabinet. As a result, we see that E and e appear once in this string. In Dara's main channel, the letter e also appears once in the word label and the letter e also appears once in the string Royal, so he. The brother will appear and will also appear once in the network. As a result, we see l appearing. appears twice in the photo Ella Eyre also appears twice in the topics bo a&amp;l + appears twice in the letter R a&amp;l + appears twice in the letter R a&amp;l + appears twice in the letter R so we have L also appears twice let's plant a tree with that result then These are the ways that the case of this letter l is the case that we're going to explain to the parts that they specify to include low-key characters. specify to include low-key characters. specify to include low-key characters. That is, the least number of occurrences of all the letters. The character will also appear in the resulting revolution for the next bit and then it will appear in the vastness once the text level 1 will appear but the text Royal will not appear so think. So again, we don't have the letter A in the resulting network. Finally, we can see strongly. Our result will be E ll. Let's go to example 2. In the example, we also have a table. A consists of 3 bare mole, the second root is rock and the 3rd root is little then we see that the letter C is the letter c that appears once in the string of khu appearing once in the hundred years rock and appears once in the Chrysanthemum chain, we find it strange that we will have 1 letter c appear once in the high result cabinet in similar result tables we have the letter o a for Size appearing 2 times in the string area appearing once in the word water and appearing twice in the word quail so we will take the series with the most favorite occurrences Very rare in our age There will be the letter O again in the result, then similarly. The remaining characters will not appear in all three of these bananas, so in the end result we only have the letter c in the letter O Anyway, I think you have already grasped the requirements of this problem. Now I will go through the thinking part to solve the problem. For this problem, our task will be We find the lowest number of occurrences of the least number of occurrences of a character ah of a character in all the ages in this piece a and then the result for us will be the number of times For the lowest occurrence of that word, use the fragment a. For example, let's say the letter B, but on this side, I said the lowest occurrence is in the character three, which means it doesn't appear once to generate the number of times. Its lowest appearance should not be in the result or in the resulting revolution, we don't have to add it, right? Well, I can try to give you one. Ha, for example, give us an example in example one. We consider the letter b, e, l, a, R, o ha, then now we clearly have lists of letters like that, we can use these characters and save them as an index. The number that we will save as indexes in a piece, I can call it a piece Heart meme completion ha Then this piece I will change It these characters it will change into one number it will change to a number 53 My Intex ha will change to a number in that I the number of our Organ menezes string, we change it by the way we use our Asian field - for the letter a we use our Asian field - for the letter a we use our Asian field - for the letter a we - given its upper bound a we - given its upper bound a we - given its upper bound , for example the case We is the , for example the case We is the , for example the case We is the letter B we - given the letter a then letter B we - given the letter a then letter B we - given the letter a then we will get the saddle 57 Intex is the number one, I infer that the letter B is yes The representative is the economic number 1 in this table. Similarly, suppose we have the letter a here, if we treat - give the letter a two letters a - here, if we treat - give the letter a two letters a - here, if we treat - give the letter a two letters a - together, it will produce the number 0, then the number zero is a 57-stroke tree. of the character a is a 57-stroke tree. of the character a is a 57-stroke tree. of the character a in the integer array a permanent. That's how we represent an Intex of the characters. Okay. Now I will have the task of counting the number of occurrences. The lowest expression of the first word B is that I will divide by b. I see that the word b gives the husband the pillar alone. How many times does it appear ? In the ? In the ? In the Ballad theme, it appears once in the age of e. Then the letter e in the bala cabinet appears once. The letter l in the theme like in two times. The letter a appears once. When tr, it means not recognized. And when it's free, it's zero times, and then we go back to the letter level, so in the label owner we have the letter B appearing once, the letter e appearing once, the letter L, and the letter e appearing twice. The letter a then we will have the letter R appear zero times and the letter O we will also appear zero times if the last string is Royal then we see that this Google owner we will do one Come out again, I'll call you. Let's make it beautiful and look at these two dollar signs. Now the letter B will appear. No. The letter e appears once. The letter L appears twice. The letter a appears zero times. The letter R. appear once and cure cough appear once 2 then what will we do? We will find the admin We will find the meme of this paper to put in the Heart almond piece and then we will now Pin of 110 will be 0111 will do 1222 will be two 110 will be 00001 will be no and 001 will be no like that Finally the finger has 1 e and two L's A one e and two L's in the piece our result is the result we are a girl and two girls l2vn I understand very well that you see that the idea is like that for us ha What about the thing that lets us calculate the number of times a thing appears? Any character in this cabinet is simpler. We just need to browse through this place. We'll let a variable run y a. We'll let a run Y run from the first character position of This place calculates the last character of the string in each Vietnamese , we will check its Index , we will check its Index , we will check its Index in the array output is more than 1 a piece, we check it, we increase the occurrence coefficient for it. Up to 1, I hope the fighting [ __ ] will I hope the fighting [ __ ] will I hope the fighting [ __ ] will grasp the problem of our solution. Now I will proceed to install this problem in the Vu Lan programming language. First, I will declare a Is the variable zezo Minzy strawberry? I'm the type that says my final result will be a string. Then we will return this zezo, then first I will declare a piece Min Organ play like that This is mine ha So this piece of mine will be an integer piece and the number of its elements will be 26 equivalent to 26 keentech of 26 characters are lowercase letters in English as extended abcde to xy&amp;z, right? Well, to xy&amp;z, right? Well, to xy&amp;z, right? Well, say there are a total of 26 characters and its value will be the meaning of the number of times those characters appear. In the pin table, it is the lowest number of times the characters appear. From there, now we first calculate this main, we will assign its initial values ​​as large numbers, then we its initial values ​​as large numbers, then we its initial values ​​as large numbers, then we will initialize our monogatari piece with a large value then I will take the one I will browse through all the good minv hemi not drain engines I will have this filter powder so I can get bored with the initial value for it I have a shape Why do I have to use paper like that Because I am looking for a battery I have to assign it a very large value so that when I compare later, I will compare if I take the smaller value, then I will have a big number that cools the air or does my house have a number that makes me lose my virginity 16 This is the largest number of the unsigned integer 16 The initial value is a very large number and I am sure that with the constraint of the problems that only the length of each string is less than 100, I will definitely ensure that this number is always the same. is the largest number, then after we have initialized it, we will be able to make a temporary loop through all the words in the category in this piece a. I put the variable and destruction as the meaning. is from using the Land syntax to eliminate all the millions through all the strings in each of these pieces, I will have a machine, this Oki guy only stores the number of times it appears. occurrence of characters in the what the word sign what we're doing And this piece we're going to keep the number of occurrences of all the characters for all the banana trees that have the smallest occurrence then similarly we will declare it is a piece of type int girl with a quantity of 26 molecules then for next we will go through all the characters in this cabinet ha Then we call the characters Similarly, Vietnamese strong father follows the above syntax with all the words in here, every time I browse like that, I will increase the Ok play in the 3rd position to check the bitch's upper limit needed for the upper edges. of the filter, the string that we are being represented with, the coefficient a is small and then we will increase it by one unit, then after we finish this Filter, this piece of ours will contain everything. The values ​​of the number of will contain everything. The values ​​of the number of will contain everything. The values ​​of the number of occurrences of all the characters in this flower pot are easy to sleep. Next, I have to check the interest rate number. This PIN number. If you have this, it is smaller than the pin. I have to try to be what Min gives it to be what is this new thing. How many times has it appeared here? I check the weak line or the final position. I know y = 0, then this is the cure. It is know y = 0, then this is the cure. It is know y = 0, then this is the cure. It is contained here. How many times has it appeared? Is it smaller than the number of times it appears? Is Min in the piece we need to build? If it is smaller, we will assign this smaller value to Min or Kali. Just like hotgirl. Okay, after we finish the ring By setting this up, our Min drjays will always keep the smallest value that these words have ever gone through, the smallest value of the characters in these words that we've ever gone through, then After we are done with this set up, we work through all the characters in all the words in the A side and the minoura so we are keeping such values. Reasons for stacking For example, this one is preserving such value, now let's follow him and give paella the results table. Well, giving you the results is extremely simple, so we just need to go through it all. elements of minoccurs arrays of Min of care II Okay + + Then each time Okay + + Then each time Okay + + Then each time each character is added, we will have to add the number and take the value of the high amplitude out at the medical knowledge position. District 1, we add one digit 2 add two digits 3 add three digits then I have Di Long filter powder in it or something, it will run Viettel means of cause great at the final position y&amp;j + + and then at the final position y&amp;j + + and then at the final position y&amp;j + + and then we will take 10 vegetables to increase the zezo battery of the Trinh for the y function + for A the character we need to for the y function + for A the character we need to for the y function + for A the character we need to add. The result is the character at this y&amp;y position that is doing the at this y&amp;y position that is doing the at this y&amp;y position that is doing the Intech co for us. For the characters, we add 1 to the upper bound. If y = 0, then adding this will get the upper bound. If y = 0, then adding this will get the upper bound. If y = 0, then adding this will get the solution. If y = 1. Add this spoon to get the solution. If y = 1. Add this spoon to get the solution. If y = 1. Add this spoon to get the letter B if y = 2 + get the letter C. That's the record. Remember letter B if y = 2 + get the letter C. That's the record. Remember letter B if y = 2 + get the letter C. That's the record. Remember that we have to switch to the string so that we can say in and out strongly. This result is strong. How old are we? Let's try running this to see if there are any errors. It will give us the example 1 when playing. If we play like that, we will be successful with a return result of e l which is equivalent to the result of the program and now the collapse to solve other examples. Okay. So we have solved it. succeed in all the examples of the problem. We will talk a little about the complexity of these algorithms. We see that we have a first iteration that is independent of this 26 times due to this version. is always the number 26. This is a fixed length. The second loop is the filter loop. If we call N the number of elements in array A , it will meet N times inside the input. , it will meet N times inside the input. , it will meet N times inside the input. It will have a nested loop. Let's call M the number of characters in a word. Then we will have n multiplied by m and the second nested loop will also have a length of 26 sets 26. times a fixed number, so we can also skip it and wait until the last iteration of the program is only performed 26 times, so we will have a strange math hole to accept for M. n is the number of elements of i m is the number of characters in the word in the temple then the complexity of the storage space we will have one because we have used a piece However this table is there The fixed size is 26, so we don't, so we can see it as a number row, like you, I will end the video here. If you find it interesting, please give me a like, sub, like and share your experience. If you have any questions or comments or have a better solution, you can write them in the comment section below the video. Thank you. Goodbye and see you again.
Find Common Characters
maximum-width-ramp
Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**. **Example 1:** **Input:** words = \["bella","label","roller"\] **Output:** \["e","l","l"\] **Example 2:** **Input:** words = \["cool","lock","cook"\] **Output:** \["c","o"\] **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of lowercase English letters.
null
Array,Stack,Monotonic Stack
Medium
null
948
Jhaal Hello Hi Guys Welcome To Cash Today's Question Is Back Options In This Question Behavior Lifestyle Power Of P N Initial 480 And Certificates Were Taken A Representative And Job Is To Come Forward To Maximize The Total Score Back Water Ship Will Take This Token In Any Update On 20th the river front is that is on current power is at least equal to Kansai Delhi mein place is to confess now losing Deepa and request to un eye and gaining Vansh is second this current is to reject list Vansh me pleasure is to confess down and gaining Power Equals To Canada And Wings To This Token Must Be Amazed At Most One And Order Will Have To Play All Set To Return The Largest Possible To We Can Achieve After Pregnancy Number Token Okay So Basically Satire One-by-One Darkness Of Open Sit Satire One-by-One Darkness Of Open Sit Satire One-by-One Darkness Of Open Sit Represents Ab Particular Value And Where Given Them In Excel Power Pivot Upper Advanced Course 120 B To Maximize Co Into His First Visit Approach Token Of Agrotech But The Can Do Also Must Have At Least Power Different To That To Kal High Value Of Power Is Great Nikhar Token I Will Doob Will Give Are Power And Take Vansh To Attacker School And Increase To One Second West Supported To Un I Hai Sanwarlu And Power Is Enough To Organize Inverter We Can Do Being A Certain Amount Of Power In Not Original Power And Vipin through 101st schedule power and tech and weight gain power and 101 days to be drawn to 120 b c d games subscribe to power at least five increase power to the democracy value serial to z10 to panvel to so they can not give this power Sudhir Will Not Be Able To Increase Are You Will Not Be Able To Increase Ur Score And Second's Sweater Decades Gone To Power In Royal Power That Is And UP Vikram Fifty Plus Has But In That Case How To Give To Reduce By One But Way Should invest in these issues to switch off but do not to reduce and mix it will not benefit 1000 in this case of 5000 examples might have two tokens as an initial power is 15210 middle aged person to give at least token power equal to terms of 150 We can give hundred power swar meaning of 150 and they can increase to one election links isco admin increase the 1000 villages hello friends then power and come into next token and current power steering power lifting more than 150 sir karnapal shetty and they have to give 210 Power Should Not Possible To Give Power Be Positive Only From Its Powers In That Case Will Not Be Able To Increase Is Token Increase Dhodekar Soein Din Navdin Ek Simple Laddu CID Shilpa Verses And Art Open Viewers Them Must Maximize Your Own This A Good Example For Independent candidate at work and you will be destroyed but they can increase the giving power a power cord individual's governor power and subscribe our life in the world loot what do we can see 9554 morning we can do vaikuntha gives positive and used to be one can Reduce after and by one and again this water power solar power will be them 0f just 400 because being and one point by giving someone to power and have lost 1.5 giving someone to power and have lost 1.5 giving someone to power and have lost 1.5 allegation on its power saurabh ka rasa 9 vikram zero and power is vikram phase so after five Words can go to the is token and wicket is token of 122 hunter power to get token 95 153 105 episode watering also all is token what they did you forget to convert to back to give three and want to power and voice of wealth and also will Give all sorts of this power also ander token apoorva increase aaval begum do and sudesh bhosle and the question and definition not direct approach how will prove this question c forget to increase of vitamin a and lag increase co points video give button take power from the Power to give power to increase the school will be very difficult for giving power to the least 50 years - 100 salute to power generator years - 100 salute to power generator years - 100 salute to power generator to increase the power man vs not possible to withdraw this article is power and it is to convey your inner power by Giving up giving Amazon amount of score so a big way to get maximum value and by giving lift to power in the one but will need a question B.Sc first year b.a. First Year To All How To B.Sc first year b.a. First Year To All How To B.Sc first year b.a. First Year To All How To Conduct For Who Are Top Guns Dot And Sudhir Will Declare Available Call Max Points Wistoria Mexico Induced Illnesses Are Available With Us To Appoint Current Points Difficult 2018 Point Is That In IPL 2018 Advocate Vinod It's All His Moral Values Will get started gandhi zero this early phone telephone tower against index next president which point is this point above last indices media to ball power and main and students way either ball power wekendi maximum tower which can welcome wick and a maximum of power they can gain And Where To By The Way To The Point To Fall On Power Rama2z Slow Amount Of Power They Can Use For Gaining Points Up 20120 Daily Point Starting Dark And Boiling Point To The End Of The Year How To Cons Dot Size 8 - 1m 8 - 1m 8 - 1m 209 Button To Extinct Sunday Ludhianvi Jo A What Do Is Aadat Power Plants SPD Power Per Current Power Grid Request To Conserve The I This Front Token 512 Big And Scored By One Day Teacher Useless Increase The Point By One Will Ooh Will Update The Value Of Max Point is equal to make fennel max points which work you points a note via increase the point but for increasing the point where to spread this amount of power monday original power supreet is equal to - fennel 8 - now tokens i the ka 8 - now tokens i the ka 8 - now tokens i the ka contract period and want Be Done With As Possible To Convert Back To Back Both Thakur Log Is Token Again In The Fifth Aap Tarf Trophy Problems World Will Do I Plus Sukh-Shanti Ke Winner Initial Power Sukh-Shanti Ke Winner Initial Power Sukh-Shanti Ke Winner Initial Power Boss Battles And Antonyms Of Value Surya Supply The Token Value From Power And increase the point in that no rate cases that supports that approach campaign left with a certain amount of power and were not able to by 20 not able to take a particular is taken into account siddheshwari back to increase of power and well increase power By giving away the beginning duration iso swapnil do and saffron points 104 ki redmi deadliest 1.0514 injured in ki redmi deadliest 1.0514 injured in ki redmi deadliest 1.0514 injured in discussion with every one side effect current to reject least one and only way can gain power morning to right a condition refer stories battery 20 vipin jain and power Press the switch Power will be equal to two Plus is equal to a How to conserve Jan White token Abe development Back to count Maximum power by measure giving any one points Paste open the end points will reduce 1.5 Will take only one points will reduce 1.5 Will take only one points will reduce 1.5 Will take only one step at a time when was the First Indian to the point to give power to not the third point is which theorem satellite plus and a plus in this law will and you will be over again will return next point inner power function Sudhir Vid oo yes max possible to max of undeclared var Max Points Is Yes Ok Max Points Will Be Of Table No List A Certificate Not Submitted On Well Organized Reduce Hole Ko Digger Is Ok Pet Commission Selected Video Thank You To
Bag of Tokens
sort-an-array
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Merge Sort,Bucket Sort,Radix Sort,Counting Sort
Medium
null
221
Loot Hello Bhaiya Yeh Bolo Phir Hum A Great Time Friends Welcome To Cases Channel Subscribe to the Page if you liked The Video then subscribe to subscribe our Ki Remedy Stick Pan Shark Slide Show Aur Sudhir Very Famous Interview Problem That Request You Kindly Go Through The Good Deeds Not To Withdraw Maximum Kar Do Play List Festival Swan In Matrix Square In Difficult Sperm Select Query For Simple Subscribe Swa0 Subscribe Over All Subscribe Listen Elaichi Phir Vo Subscribe Zurur And Subscribe Viewers Hindering The Complete Grade To Be Coming Astitva Liye Seetha-Sidhe Liye Seetha-Sidhe Liye Seetha-Sidhe 201 Hair Raw subscribe and subscribe this Video plz subscribe Channel subscribe Subscribe subscribe to Shubhendu wear look out for this Baalveer wali subscribe and subscribe the Channel Please subscribe and subscribe the Channel subscribe Video to plus one give me to under updater Subscribe subscribe button and other subscribe Video subscribe Sudhir and subscribe now subscribe The Channel Please subscribe and subscribe Loot metrics and it's too late for this point Clerk Grade Three subscribe this Video give and subscribe The Channel Please subscribe and subscribe this Video also share C Ravan Co Hair Serum One And All Its President And Second Idli Sandwich Subscribe Button More Subscribe Must Subscribe And Subscribe Share and subscribe the Channel subscribe Coat With The Side Length Ball Subscribe To Do Subscribe To Me Shift Simple Straightforward Video Channel and subscribe the Channel Please subscribe and subscribe the Til Top Up Sid subscribe Video Ko subscribe kare subscribe hua ki akshay lead 90 ke liye gud vriksha Video subscribe and subscribe the Channel subscribe thanks for watching
Maximal Square
maximal-square
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\] **Output:** 4 **Example 2:** **Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\] **Output:** 1 **Example 3:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Matrix
Medium
85,769,1312,2200
134
lead codee problem number 134 gas station so this problem gives us a end gas stations along a circular route where the amount of gas at each station is inside of the gas up so over here for example in this index there will be one gas two gas three gas and so on so we have a car with an unlimited gas tank this means that this car can store an unlimited amount of gas and it cost as much cost as it says here in the cost array to travel from let's say this index to the other Index right it will cost three so here it will begin the Journey of the empty tank and basically what we have to do is return the starting gas stations index if we can travel around the circuit once in the clockwise Direction otherwise we return negative one okay so what it means is we have to find the starting index for example the starting index in this case is here so from here if we want to move to another gas station like for example uh if you want to travel to station 4 which is this station it will cost us one gas right that's stated over here but we will get five gas in return so for some gas stations there will be net lost right where the cost is more than the gas given and for other stations there will be net gain where the cost of the station of traveling is lower than the gas we could would get right so this is my approach to this problem so let's have an example so I'll be using these two the example again okay um let me rearrange it a bit so okay right here I have a integer called Surplus so Surplus would tore whether or not we have more G or not right so Plus for this instance is zero so total is the one that we will check whether or not we could complete the circuit or not so total is basically would include all of the Surplus so for now it starts at zero and start is basically the starting index that we will return which will start at zero as well so here I have a for Loop that starts at the beginning of both arrays right and here I have a another integer called net which will calculate the difference between the guas and the cost so for this case we are starting at index zero the net would be one minus the cost three so net would be -2 right the cost three so net would be -2 right the cost three so net would be -2 right so I update total and surplus and here if my Surplus is less than zero what I'm going to do is skip this starting position and start somewhere else instead right Sur plus more than less than zero I'll update so that Surplus equals back to zero since Surplus is already zero we don't have to do that and start will now increment plus one so I in this case is 0 + 1 is 0 + 1 is 0 + 1 is one okay so Surplus was the one that was netive two and then since surus now becomes zero okay next I increments by one we calculate the net again so in this case the net now is gas which is 2 - 4 so this net gain plus -2 again it's - 4 so this net gain plus -2 again it's - 4 so this net gain plus -2 again it's not a night gain but we would increment the total again to 4 so -2 + -2 will the total again to 4 so -2 + -2 will the total again to 4 so -2 + -2 will give us4 Surplus plus -2 this will give us Surplus plus -2 this will give us Surplus plus -2 this will give us -2 and since Surplus is less than zero -2 and since Surplus is less than zero -2 and since Surplus is less than zero Surplus goes back to zero and start to increment once more okay again I will increment now we are at gas Tre cost five net us again with -2 right 3 - 5 give us -2 so the total -2 right 3 - 5 give us -2 so the total -2 right 3 - 5 give us -2 so the total again minus 6 the Surplus will become -2 once again 6 the Surplus will become -2 once again 6 the Surplus will become -2 once again and since the Surplus is less than zero so we don't want to start at this index so we move Surplus back to zero and count again we start incrementing three now that we are at the index which we have four gas and one cost so if we calculate it we will get 4 - 1 is - 1 is - 1 is three the total plus the net if you WR so plus three this will give us3 and the Surplus we will get three now since Surplus now there since now there is an actual Surplus so meaning we are good with this starting position we don't need to change anything for now and we are good to move on to the next gas station right so I increments we calculate the increments I increments we calculate the net again so this time is 5 - 2 this net again so this time is 5 - 2 this net again so this time is 5 - 2 this will give us three as well total plus equals to net so this will give us the total of zero the Surplus plus equals to net so this will give us another three this is six and since Sur plus is more than zero we don't have to do anything about it meaning that from here on out since we have iterated through the entire list of gas and cost we have concluded that to travel around these gas stations the total cost would be zero meaning that we have just enough gas to travel around the travel around right if the total number is let's say -2 meaning that for number is let's say -2 meaning that for number is let's say -2 meaning that for every round we do we will lose one gas right because gas is lower than the cost right which means that for this case we will have to return negative 1 right but since the total is zero meaning that we have just enough gas we can return the starting index which in this case would be three right that's where we started off okay otherwise we return negative 1 like I mentioned if the total was less than zero if the total was more let's say five that is still completely fine right because that would just mean that for every round we do we will get extra five gas and that does not mean that we will run out of gas when we are traveling so we can still return the stting index tree no problem okay so this solution is another example of a greedy Solution that's all I to show thanks
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
1,261
hey everyone today i'll be talking about leeco 1261 fine elements in a contaminated binary tree so we're given some tree it has all negative ones so it's been contaminated apparently and to recover it to make it not contaminated anymore we have this rule set so the root's value is zero and then for any given nodes value x the one to the left will be two times x plus one the one to the right will be two times x plus two so kind of like looking at these diagrams here so we have this and uh we know this becomes 0 because that's our base rule and we know to the left it's 2 2x plus 1 and then to the right it's 2x plus 2. so that's true go to this one two x plus one is three two x plus two is four so that's for covered now you could do this a number of ways the naive way and it's actually easy to do and it does work is you can kind of like uh recover this tree like build and mutate all the values and then you could just uh do binary search and search through each tree but that would be a on constructor and a o login a find and it can actually be better we can have this find be constant time so when we think of constant time we usually think of hash map hash set for constant lookups so we're going to do that and we're going to have a set and we're just going to mark it as private for now we're gonna have a set in the class now and let me go ahead and also get rid of this here hold on okay there we go and then what we want to do is we want to construct this using this rule set and populate the set so ideally the set should have every recovered value in it so for this find we can make it a one right we could just simply go set contains target because we're going to assume we've built it at this point so in the constructor we want to initialize the set just make it a new asset and we also want some helper method which i'm going to call a dfs and basically this dfs method is going to build the root and it needs to have some base truth and the base truth is that the root value is always going to be zero so let's pass in a zero and we'll make the function definition here and it can be void because it doesn't it's just a builder a recursive builder it doesn't have to return anything it's going to take some root and it's going to have some current value so i'll call this x rather because if you look at this rule set uh they're talking about x so we'll just do it exactly how this is structured and so we've covered rule number one here uh just by passing in the zero at the beginning that's our root so the root is zero right so we do need a base case because we don't really wanna add anything if this root doesn't exist and there's actually nodes if you look here it does stop eventually so if root is null we just simply want to break or return next what we want to do is we want to add the current x into the set so we'll go this dot set dot add x we do this because if you think about it when we start it's zero right we have to add that root it'll be zero it'll go here and it'll add it to the set so then we want to go left and we're going to go right and we want to start to recover this tree so and it'll terminate as so long as uh or it'll terminate when the root is null eventually so we want to go left first so we'll call this recursively and we'll go left since we root left if we look at these rules we're covering the second rule so going left is two x plus one so we're gonna do that we're just gonna literally copy this so two times x plus one and then if we go right it's two times x plus two like such so following this it actually this is good as is now because it's going to go through it's going to populate it if one of the nodes is null it's just going to stop and it'll just kind of like bubble through and like populate that set then once it's finished it's reconstructed the tree put all the values in the set and then this is o of one here so let's run this okay that looks good let's submit it and yeah it looks like this is yeah this is actually really good so let's talk about time and space complexity i kind of went over a bit but this is a this is an object-oriented but this is a this is an object-oriented but this is a this is an object-oriented solution this is a class so there's multiple methods so let's talk about the time complexity for each so let's talk about this constructor here so this constructor actually has an external dependency on uh this uh dfs function and this dfs to populate it is just o of n uh where n is the amount of nodes because it terminates when it's null right so it's just going to be the amount of nodes in this tree so i'm just going to call it of n here this find is actually o of one time here because simply uh we're just looking it up in the set right and that's over and look up now for space these are both for time by the way space all in all is just going to be and i'll put space up here it's just going to be on and the reason why is you have to store every single node's value in the set so it uses on space right so yeah i hope this is helpful um try to make it a little bit easier than the medium they marked it as so yeah hope this helped thank you
Find Elements in a Contaminated Binary Tree
swap-for-longest-repeated-character-substring
Given a binary tree with the following rules: 1. `root.val == 0` 2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1` 3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2` Now the binary tree is contaminated, which means all `treeNode.val` have been changed to `-1`. Implement the `FindElements` class: * `FindElements(TreeNode* root)` Initializes the object with a contaminated binary tree and recovers it. * `bool find(int target)` Returns `true` if the `target` value exists in the recovered binary tree. **Example 1:** **Input** \[ "FindElements ", "find ", "find "\] \[\[\[-1,null,-1\]\],\[1\],\[2\]\] **Output** \[null,false,true\] **Explanation** FindElements findElements = new FindElements(\[-1,null,-1\]); findElements.find(1); // return False findElements.find(2); // return True **Example 2:** **Input** \[ "FindElements ", "find ", "find ", "find "\] \[\[\[-1,-1,-1,-1,-1\]\],\[1\],\[3\],\[5\]\] **Output** \[null,true,true,false\] **Explanation** FindElements findElements = new FindElements(\[-1,-1,-1,-1,-1\]); findElements.find(1); // return True findElements.find(3); // return True findElements.find(5); // return False **Example 3:** **Input** \[ "FindElements ", "find ", "find ", "find ", "find "\] \[\[\[-1,null,-1,-1,null,-1\]\],\[2\],\[3\],\[4\],\[5\]\] **Output** \[null,true,false,false,true\] **Explanation** FindElements findElements = new FindElements(\[-1,null,-1,-1,null,-1\]); findElements.find(2); // return True findElements.find(3); // return False findElements.find(4); // return False findElements.find(5); // return True **Constraints:** * `TreeNode.val == -1` * The height of the binary tree is less than or equal to `20` * The total number of nodes is between `[1, 104]` * Total calls of `find()` is between `[1, 104]` * `0 <= target <= 106`
There are two cases: a block of characters, or two blocks of characters between one different character. By keeping a run-length encoded version of the string, we can easily check these cases.
String,Sliding Window
Medium
null
1,689
the code challenge one six eight nine let's go here's the site problems page and we are looking for one six eight nine i can just scroll down to it you can see it's medium difficulty five eight nine lights four three eight people struggling select your language i'm going to go with javascript and let's have a look at this question called definite binary if each of its digits is either 0 1 without any leading zeros for example 101 and 1 zero at deci binary while one two and three zero one are not given a string n that represents a positive decimal integer return the minimum number of positive deci binary numbers needed so they sum up to n here's the first example so we've got the input of 32 output three and the explanation there is one zero one plus one equals three two example two input eighty two thousand seven hundred four output eight and in example three we've got a fairly large number that's how much money i've got in the bank and the output is done and we've got some constraints here one is smaller than or equal to n dot length which is smaller than 10 to the power 5 n consists of only digits n does not contain any leading zeros and represents a positive integer so how we're going to do this i think somebody thinks so how we're gonna solve this it's quite a big number go for the smaller one first thing we should do is like scaffold out the answer see what we think so how many deci binary numbers do we need one made a slight mistake there that's actually done so we've already hit two there zero yeah and we've already got three one you can see as we go we're getting fewer ones so it took us it's gonna take us eight iterations to get our final number which is the same number as obviously the highest number there because you can only get to eight by adding eight ones so clearly what we need to find is the highest number in the string that's always going to be how many desti binary numbers we need so we can just do n dot split so we're going to create an array from the number that were passed and then we're going to use math.max going to use math.max going to use math.max to pick out the highest number in there and we're going to split that array so the max can do its job and we've got the wrong answer output undefined what have we done wrong here um we've just forgotten to return the value from the function so now i'm expecting a positive result that's right accepted answer i'm going to submit that and you can see run time 96 milliseconds faster than 83 percent of javascript online submissions and uh there we go so it seems complicated but actually it's not delivery
Partitioning Into Minimum Number Of Deci-Binary Numbers
detect-pattern-of-length-m-repeated-k-or-more-times
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._ **Example 1:** **Input:** n = "32 " **Output:** 3 **Explanation:** 10 + 11 + 11 = 32 **Example 2:** **Input:** n = "82734 " **Output:** 8 **Example 3:** **Input:** n = "27346209830709182346 " **Output:** 9 **Constraints:** * `1 <= n.length <= 105` * `n` consists of only digits. * `n` does not contain any leading zeros and represents a positive integer.
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Array,Enumeration
Easy
1764
764
alright guys welcome to our channel code with sunny and in this video i will be talking about the problem you can see largest plus sign its index is 764 and it is the medium type problem the leak code okay so to be honest i really like this problem and the reason behind this is if you look over the constraints i was trying to have the different type of solution like first i've used the brute force then i've used the binary search and then finally the ultimate best solution so like i was aware that these type of solutions like brute force in the binary search is not going to pass since the constraints like the n value is around 500 and this brute force will take a time of around o of n cube so this is obvious that i think it is not going to pass but if you look around the binary search approach it took the time like the time complexities around o of n square logarithmic of n and space complexities over pen squared but still you can see i have been delivered this verdict like all the test cases passed but your code took long to respond yes so i need to optimize again so then finally i came up with the solution like time complexity of n square and space complexity open spread now uh to be honest to come up with these type of solutions like directly this one is quite difficult but if you are practicing enough that is the if you have still solved these type of problems where it is google kickstart yeah i've already opened it for you guys okay so you can see that this is the problem has been asked in like this year google kickstart round a2021 and it is the second problem i think here yes it is the second problem so like the problem is quite similar and it is called the variation of this problem like in this problem also you need to find out total number of l-shaped find out total number of l-shaped find out total number of l-shaped figures all consisting of i think oh yeah i think the values are one also yeah the cell containing the values of one i don't know but you have to be like finding out the total amount of l-shaped figures possible okay and that l-shaped figures possible okay and that l-shaped figures possible okay and that is possible in the grid and if you are done with this question i will strictly recommend you guys to do this problem and again if you are stuck up on that go come out to the playlist section of my channel you will find out the okay so i will guide you from the very beginning come out to this playlist section you will find out google kickstart round day editorials and here are the four problems and this is the problem around like the second problem l-shaped around like the second problem l-shaped around like the second problem l-shaped plots round a two zero two one you need to click over here and there's a 17 minutes video and it will explain you all the concepts okay so coming back to discuss the original problem yeah so what we have to do is like we have been given an integer n and there is an into a binary grid with all values initially one except for some indices given in the array mines that is we would be given a 2d vector also and uh size of like mines like named as mine and like initially we would have a we would be having an into n binary grid like it can consist of one or zero and initially it is all filled with one and we will be given some mines vector where it will be denoting two values x i and y i for every particular input and where if we given x i and y i then the grid of consisting of this coordinate will be filled with zero and what we have to return this the largest x aligned plus sign of ones contained in this grid you can see that this is the largest one that is being possible over here okay and if there is none return zero an axis aligned plus sign of ones order of k has some center grid rc exactly equal to one you can see that this is the center and with four arms of length k minus one that is the lengths are same and k minus one you can see there are four arms left right up and down each having the length one you can see over here going up down left right so on and made of ones note that there could be zeros or ones beyond the arms of the plus sign only the relevant area of plus sign is checked for once you can see that this is the largest one you cannot extend either of the arms to one mode length because you need to maintain the lengths of each of the arms to be having the same length because same length having k minus 1 where k is any integer okay if you are not getting the problems right now no need to worry about i'm going to explain this with this examples so let's head over to the explanation part where i will be explaining how what this the problem is going to show off and what could be the best solution for this problem so let's move further okay so suppose that we would be given this grid consisting of like everything is going to be filled with let's say one like this is not zero consist uh imagine that there is one now we will be given a minus 2d vector where every input is going to consist of two numbers x comma y if it is given x and if it is y then the corresponding value and this grid becomes zero so we will be given some like this type so let me raise this to one and put over zero over here so here in this case my vector 2d vector is of size 1 and the inputs are for this coordinate that's why here it is 0 okay so we need to find out the largest plus sign so you can see that largest plus sign can be like of this one so let me just draw this one so you can see that this is the largest plus sign why this is the largest plus sign over here you can see that here it is the center and all those lengths that are length of the arms that are to the left of it of the center and to the right of it of this center and similarly to the up and down are of same length let's call the length as k you can see that one length and again it is length of one length of 1 and the length of 1 that's why you can see that this is the plus sign valid plus and all consisting of ones and all the arms have are having the same length exactly equal to 1 and if i will consider this as the plus sign what is our answer will be what is the length of the common arm to the all the surrounding the center it is 1 plus the center value that is 1 that is exactly equal to 2 you can also consider the answer as like this one you can see that what is the length of the longest arm considering the plus center of this plus sign and including that plus coordinate you can see that here it is of length two and here it is of length 2 and here it is of length this is the largest plus sign that you can get over here and you cannot like extend this plus sign to some more extent let's try to have a different plus sign over here let's try to explore something more consider this as your center if i will consider this as your center let's try to understand and suppose that i am going to extend this one this part that is the right arm to the one more length and right uh up arm to one more length and left arm to one more length and similarly the arm that is present over down to one more length okay so this is the answer like here the answer is two right now note that you need to ensure that left up down and right arms consisting of ones should be of same length now you can see that here is also one i can extend this to the one more length that is the right arm in that case also you need to ensure that all the up down and left arm should also be extended to one more uh one more cell consisting of once but you can see that when you try to extend this down on it is zero you cannot do that so it means that the extending the either of the arms to one more length is not possible so our answer is two and this is the maximum answer that you are going to get okay so doing these type of brute force is not optimal so what you are going to do is let's try to understand how this plus sign is going to play an important role now consider all those arms left arm right arm up arm and down arm having the zero length now you can see that all these arms are having the zero length okay in that case our answer is one right and consider that length of the up arm down left and right are exactly one like plus sign having this type like this one this is a valid plus and all consisting of ones okay this is all that consisting of our answer in this case is two okay there might be some cells okay so there is one more important thing there might be some cell to the left of the left arm and similarly to the upside of this one so similar to the downside and all those one okay but you need to ensure that whatever the cells that you are going to consider with respect to the center of this plus sign should be consisting of all those ones that is suppose that here it is zero over here okay and you are saying that uh i'm going to consider this plus sign because note that i'm talking about the plus sign contained in the yellow okay so i'm going to consider this plus n as the valid plus and this is not going to be possible because here it is one of the zeros if you look out the problem statement it is saying that all the ones contained in this grid okay so you need to focus over the only ones and the thing is i'm talking about the plus signs right now because this is going to be important how this is going to be important let's try to understand this by fixing the center and extending the arms okay so let me just erase this one okay so let me take this color now consider the case like if you try to say that this is the cell and this is the center of this plus sign okay and you need to find it out that what is the largest sub array consisting of ones and ending at this cell and coming from the right hand side that is i'm talking about the right arm if you're not getting it right now let me explain let me speak out again the thing is you need to focus over the right arm right now and i am talking about the largest sub array ending at the current cell that is this cell and coming from the right hand side and all consisting of ones okay so suppose that there is this these type of cells that are present to the right of it okay if these type of cells are present to the right of it and this is the center of this plus sign you need to ask to yourself that what is the largest sub array ending at this position and coming to the right hand side and all consisting of ones you can see that this is the sub array you are not going to consider this zero okay and similarly if you are being able to find out for all those arms that is for the up one and for the left one and for the down one okay what is the largest sub array that is coming from the upside and all consisting of ones and ending at this current cell which i have considered as the center of this plus sign you can see that here it is of length equal to 3 yes right and similarly what is the largest sub added that is coming from the left hand side and all consisting of once and ending at this position you can see that it is of length three here also it can be of any length okay and similarly you are going to find out for the downside also and let's call it as let me write down r and let's call it as u and l and d where r is the length of the largest sub array that is coming from the right hand side of the current cell coordinate and ending at this particular cell okay and similarly use the largest sub array that is coming from the upside that is the same column okay and ending at the current cell and all consisting of ones it is going to be denoted by u and similarly l and similarly d then our answer would be like if i would consider this cell as the center of this plus sign our answer would be what minimum of l are u and d obviously because so i need to ensure that all those left arm up arm and down arm and whatever it is should be of same length okay that's why i'm taking the minimum okay now the thing is like we have already approached the answers we need to find out the largest battery or consisting of ones ending at the current cell and all containing ones and what how do we find out for all those left arm right arm up arm and d like the down arm for every cell at every position of this matrix how it is going to be done and like if you say that if i am fixing this cell you need to know for this column also and for this row also and from coming from the downward also for the same column and for the same row coming from the right word also you need to know the directions values for all those four directions let that is the largest sub array ending at this current position and all consisting of ones okay so before approaching to this one you need to understand for the linear array okay now consider that you have a linear array and this is the linear array and let's say you have this and zero okay and if you have been given this one and you need to be like you need to find out the what is the largest sub array that is the all containing ones and ending at this current position any position i and coming from the leftwards okay so if you need to find out for this position let's say what is the largest sub-array that is coming from the sub-array that is coming from the sub-array that is coming from the leftwards ending at this position and all containing once you can see that it is of length equal to 2 that is this one and similarly if you try to find out for this position it is of length equal to 3 but how do we find out efficiently in o and time okay so what you are going to do is like consider the solution first okay now whenever you are going to encounter the one you need to do the prefix sum and whenever you are encounter encountering the zero just leave it as it is so okay so that is i am going to do the prefix sum that is from the leftwards so i'm encountering one so i'm going to do the prefix sum one plus zero is one and again i'm encountering the one i'm doing the prefix sum one plus one is two and again i'm encountering the one i'm going to do the prefix sum so 2 plus 1 is coming out to be 3 and i'm encountering 0 just leave it as it is so let's try to have this modified adding like i'm going to erase this first so it will be like 0 1 2 3 and 0. can you just elaborate that yes i am getting the valid answers that is what we want if you try to focus over the statements if you just say that i am going to try to find out for this position what is the largest sub barrier that is coming from the leftwards and ending at this current position all containing once should be answer equal to 3 yes it is because that this is the largest sub array okay so we have already found out the approach we need to do the prefix sum that is if you try to find out for this position considering this as the plus sign and if you need to find out the l value that is the length of the largest sub array all containing one coming from the left hand side you need to do the prefix sum for this particular row like this like in this way and you are going to get the answers for every coordinates of this particular row and similarly you are going to do in the right hand side also and similarly you are going to do for the upside also for every column and similarly you are going to do from the downside also okay so if you are going to do from the downside that is for every column you are going to do in this case also you need to do the suffix sum for every column right like in this manner and if you are going to done if you are going to do in this way then for answering this cell you are going to answer this in o of one time and you need to do some prerequisite calculations the calculations and it would take off and square time to do that okay so you are going to do for every row and for every column what is the largest sub array coming from the respective sites and ending at the current cell you are going to find out for every cell and you are going to store it in a row like format for every row and similarly you are going to do store for every column also okay so if you are not going to understand this i think you would be better at understanding with the help of coding part let's try to understand this with the help of coding part okay so let me just open up the code here you can see that the time complexity so of n square space complexity is also of n square and uh like what i have done is like i have written down the five vectors so original vector m a t is going to store the matrix and there is a left also right also up also down also being all initialized with one okay and we are going to fill the certain cell values with zero when we try to traverse the mines vector you can see that i have filled mat left right up and down with zero at the corresponding coordinates okay now this left 2d vector is going that is the left of ij is going to store longest consecutive plus ending at this ij coming from the left direction of the current cell and similarly the right up and down now i need to just fill up this all these four vectors so i have iterated for this n times like this is i and this guy i being iterated n times and for every g i need to fill up this left ij and need to fill up this down ig okay and similarly i'm going to fill up this right and similarly i'm going to fill up this up and i'm leaving this up to you to understand this how this is going to work because this is pretty much easy you can do it with your own by uh writing the two or more lines of code if you are not going to understand this compact code okay so you can do that and what we are going to do for this answer is like i have initialized answer at 0 and i am going to consider every cell like consider every cell at the center of this plus sign and we are going to consider only and only when this mat of ij is consisting of one that's why that's when we are going to consider this at the center of this plus sign and we are going to find the answer for every cell being considered at the center of this plus sign our and like we need to maximize the answer and our answer should be max of answer and minimum of this value if i am going to consider this current cell at the center of this plus sign note that you are going to have the left of i j right of i j and up of i j and down of i g that is the if you understand the meaning of lift of ij what is the length of longest subatic coming from the left of this current cell that is the same row and coming from the leftwards and ending at this current coordinate of the cell and all containing one and similarly the right up and down and you need to maximize your hands and finally return the answer okay so if you have any doubts do let me know in the comment section of the video i will be happy to help you and i will be asking for you to like this video share this video and subscribe to you youtube channel for latest updates thank you for watching this video
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
43
hey what's up guys think white here I do tech encoding stuff on twitch and YouTube check the description for all my information I do all the leak out solutions got a playlist do the premium ons on my patreon and yeah I have a discord as well if you want to join that but this is a problem called buddy strings it is definitely has mixed reviews here and I know why I mean it's kind of specific I would say so here's the problem given two strings a and B of lowercase letters return true if and only if we swap two letters an a so that the result equals B so we have a method buddy strings it returns true or false a boolean value we're given two strings and we return true if two if we swap two letters and disperse string and we can get the second string B then we'll return true so you can see here if we swap the a and B we get B a so that would be true here if we swap a B we would get B a and that's not what we're trying to get we're trying to just stay at a B so that's false if we swap a we get a that's fine and then you know you can go through the rest of these examples as a few other ones but I guess I mean maybe we can just go through them there's only two more if you swap B see you get the CB right here see that so the A's don't matter because it's only two characters and if you have an empty string then you're not swapping anything so you're not going to get this so that's false okay there we go so how do we do this first of all it's two characters for some reason really specific so we have to make sure that the strings well first of all the strings have to be the same size for them to be you know equal after a swap so first we'll do is okay if a dot length is not equal to sorry not equal to B dot length what is going on with the type in there we're gonna return false because it is impossible so that's good start what else okay also there has to be a difference of two characters besides one edge case so we'll go over the edge case at the end but to handle the characters we're just going to need a list of integers and this is going to hold the different indices that the array is that the strings are different at so for example it's going to put in the seat for this example one it would say okay we're gonna loop through the strings and if they're both different at index zero we'll put 0 into the array and if they're both in different at index 1 we'll put a 1 into the array so yeah we're looping through they're both the same length so you could pick whatever you want a dot length or B dot length to loop up to and then you just do ok if a dot char at I is not equal to B dot char at I well then that's a difference so we'll say diff to add the index so we put the index that they're different at and there can only be two right so we'll have a condition okay if diff dot size is equal to 2 then that's good right so we would return true else return false okay so we're getting close here so first of all we need two different indexes that the characters are different at in the strings right for example if you look at all the examples there's two indexes where the characters are different there's one there's two this one doesn't have it so it's false two indexes would be the first character in the second character even though you know you just imagine they're different letter A's this index in this index and then this index in this index so that has to be size 2 for us to return true but not just that there's it one more well not one more but I guess yeah kind of one more the characters have to be you know corresponding to each other I guess I would say you know this a if the two indexes that we find where there's a difference the case character at the first index in the first string has to be equal to the character at the second index in the second string in vice-versa in the second string in vice-versa in the second string in vice-versa in the character at the first index in the second string has to be equal to the character at the you know whatever I don't even I lost my train of thought but whatever that's you know what I'm saying otherwise it wouldn't work so if a Dutch are at gift get 0 is equal to B it's really an easy problem so it's not too bad diff duck get one you know then that's good and B touch are at DIF get 0 is equal to a dot char and DIF get 1 because if we're dealing with and we're dealing with you know a bunch of different letters then it's not going to work because you can only swap it's only a one times you know it's only swapping the indus indices so two different indices so it's not you know we don't have the ability to change you know if it was an a B and a DC you know we don't have the ability it's not like we're changing you know a to D and B to C you know so you have to check that's the indices at right there's one edge case the edge case is this one basically when we see two A's it has to return true you would you might not you know you might think this is weird so basically we have to account for that so we'll see if it's all the same character we'll say okay that's fine so to do that we'll say okay if a already equals B so if they're the same string then what we want to do is we want to create a hash set and make sure that everything is good here so we're gonna create a hash set and we'll say unique chars is equal to new hash whatever you want to call your hash set is fine by me we'll loop through every char in a dot - char array and we will add it to a dot - char array and we will add it to a dot - char array and we will add it to the unique chars hasha and once we have that we want to do ok if unique chars dot size is less than a dot length meaning that so for example if it was 1 then we return true else false and then this is the whole problem but this handles it because if we're dealing with you know 1 character a if we're saying if the input was like a and a well this would be false because we're not changed we're not doing a swap to get from here to here that's it so this handles that because you know the unique characters as we loop through and put them in a hash that would be equal to a so we would get a false so that's right we would you want to false there when it's multiple is like this we go through and we only put one a right because hash let's only keep unique values so as long as the unique values is less than the length then we know that there are repetitive values and we can just return true so that's pretty much it just the edge case you want to make sure that the corresponding indices are the same for I don't know if I'm saying that right but you know what I mean like index 0 of the first string has to be index 1 of the second string index 0 of the second string has to be index 1 of the first string you know what I mean to swap and become the same you know this has to swap for these characters to swap like they have to be equal you know what I mean like it's hard for me to explain it like this has to be equal for to this and this has to be equal to this so that we know when we swap them that it's going to become the correct string I don't know how much more clear to make it but yeah that's it as long as the lengths are equal you account for the sorry you account for all of this string with just all the same letters and you check this and you check the sizes too then you're all good that's a pretty easy problem I mean it's fine it's just pretty specific and weird and kind of has weird rules but definitely still pretty good so good practice let me know you guys think let me know if you have questions probably not even worth making it's probably not worth making a video solution to some of these because some of them are just like dude just look it up in the solution but you know I said I'm doing them all so thanks for watching see you guys next time
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
158
hey guys they want you try to solve the redone characters give away the four to call multiple times actually I have explained this problem and the related trouble with the white bowl but I think you maybe I should call the life maybe data will help you understand this problem well okay let's see the problem give it a 5-under soon there you can give it a 5-under soon there you can give it a 5-under soon there you can only read the file using a given masseria for employment a master read that you read on characters your master read may be called multiple times master the real for okay the difference between this problem and the previous problem is that this time when you read when we call this reader for we only use one character but next time we do not have it you call this really for again because we still have three characters on use so we can just use them so as I explained it is obvious that we need to make this temporary array and the temporary pointer and the temporary how to global because in this case we can use them next time when we call this reader function so sorry and I say that we need a three global function first is the temporary character which will be four as in the private into temporary pointer this means we which position are we now in this temporary array and the temporary tout which means how many characters we read in this temporary array okay we also need our total index which means how many carry I will read while the turtle Nestle which made we have to read oh if the temporary Poynter equal to zero which means we have one can see that what we have used up all the characters worried oh we are we haven't read it and in characters so we should read them code is read the full function and copy this character into the temporary array okay so now if the temporary is out equal to zero which means we have not read and we cannot read any characters anymore so we just break and why the turtle.turtle.turtle.turtle less than an Ender temporary pointer less then temporary code which is a copy the character in choose a buffer remain temporary pointer okay and if the temporary pointer equal to the temporary culture which means we should reset this temporary pointer equal to zero because we have used up all the characters and we also have to check if we can read oh we have read the characters anymore because if we have used up all the character in the file we can even if we call this relief all again we cannot read any more so if the Tamarack how the less than four which means we cannot read any cards anymore and finally returns Turtles so basically I think it's right okay thank you for watching
Read N Characters Given read4 II - Call Multiple Times
read-n-characters-given-read4-ii-call-multiple-times
Given a `file` and assume that you can only read the file using a given method `read4`, implement a method `read` to read `n` characters. Your method `read` may be **called multiple times**. **Method read4:** The API `read4` reads **four consecutive characters** from `file`, then writes those characters into the buffer array `buf4`. The return value is the number of actual characters read. Note that `read4()` has its own file pointer, much like `FILE *fp` in C. **Definition of read4:** Parameter: char\[\] buf4 Returns: int buf4\[\] is a destination, not a source. The results from read4 will be copied to buf4\[\]. Below is a high-level example of how `read4` works: File file( "abcde `"); // File is "`abcde `", initially file pointer (fp) points to 'a' char[] buf4 = new char[4]; // Create buffer with enough space to store characters read4(buf4); // read4 returns 4. Now buf4 = "abcd ", fp points to 'e' read4(buf4); // read4 returns 1. Now buf4 = "e ", fp points to end of file read4(buf4); // read4 returns 0. Now buf4 = " ", fp points to end of file` **Method read:** By using the `read4` method, implement the method read that reads `n` characters from `file` and store it in the buffer array `buf`. Consider that you cannot manipulate `file` directly. The return value is the number of actual characters read. **Definition of read:** Parameters: char\[\] buf, int n Returns: int buf\[\] is a destination, not a source. You will need to write the results to buf\[\]. **Note:** * Consider that you cannot manipulate the file directly. The file is only accessible for `read4` but not for `read`. * The read function may be **called multiple times**. * Please remember to **RESET** your class variables declared in Solution, as static/class variables are persisted across multiple test cases. Please see [here](https://leetcode.com/faq/) for more details. * You may assume the destination buffer array, `buf`, is guaranteed to have enough space for storing `n` characters. * It is guaranteed that in a given test case the same buffer `buf` is called by `read`. **Example 1:** **Input:** file = "abc ", queries = \[1,2,1\] **Output:** \[1,2,0\] **Explanation:** The test case represents the following scenario: File file( "abc "); Solution sol; sol.read(buf, 1); // After calling your read method, buf should contain "a ". We read a total of 1 character from the file, so return 1. sol.read(buf, 2); // Now buf should contain "bc ". We read a total of 2 characters from the file, so return 2. sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. Assume buf is allocated and guaranteed to have enough space for storing all characters from the file. **Example 2:** **Input:** file = "abc ", queries = \[4,1\] **Output:** \[3,0\] **Explanation:** The test case represents the following scenario: File file( "abc "); Solution sol; sol.read(buf, 4); // After calling your read method, buf should contain "abc ". We read a total of 3 characters from the file, so return 3. sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. **Constraints:** * `1 <= file.length <= 500` * `file` consist of English letters and digits. * `1 <= queries.length <= 10` * `1 <= queries[i] <= 500`
null
String,Simulation,Interactive
Hard
157
1,967
hey everyone welcome back to the channel so in today's video we will be solving it for 1967 which is number of strings that appear as a substring inward so in this problem we are given a array of strings patterns and the string what uh we need to return the number of strings in patterns that exist as the substring inward so basically we are given this pattern and then uh we need to find how many of those patterns actually exist at the substring in what so here the word is abc right so if you see a exists in abc and substring abc also like this bc also exists but d doesn't exist so the answer is three in this case right uh and again for this a and b exist but c does not exist so the answer is two in this case right so basically uh we have two approaches to solve this since the constraints are pretty less since the constraints are like 100 right we can basically uh think about solving in something of n cube because n cube will be 10 to the power 6 which is still less than the number of computations the computer can pop modern day computer can perform in less than one second right so yeah so basically we can write a brute force output and how the brute force approach will look like uh let us see that so let us look at the brute force right so the brute force approach would be something like this so we initialize the variable count and then we look through the patterns and for each pattern we find the index where it occurs in the word sub string so we can use it word dot find and then the particular pattern i so the find is basically of the complexity order of n into n which is the two string that you are using to uh find the substring so here word uh length is n and the patterns length is m so this would be like order of n into m and then this we can say order of l which is the number of elements in the list right the pattern list so overall complexity will be order of l into n into m so what happens is if uh this function what will return is if the iterator doesn't point to the last character or la the element at the last right which is after the last character there is this end post we can so if uh this if this abcd is the string then just then the iterator will point to something a pointer which is just after the d which is n so if that is the case we can uh say that uh the string doesn't exist the word i mean the what doesn't contain the pattern but if it is not equal to that then we are sure that the word contains the pattern and then we do a count cluster so find will basically give us the index the first index of the pattern line in our word uh so yeah that is the brute force pattern and the complexity will be order of l into n into m right but let us now look at the second approach so basically what second approach is let us see that yeah so in second approach we can see that we are using the kmt algorithm so those who are not aware of the kmp algorithm i will share two videos in the links uh sorry one video and one link right one link would be from cp algorithm which is like a bible for competitive programming and then so what happens in kmp algorithm is you first uh for the pattern right you calculate a prefix table which is also known as the pi table right if you go through the video in the link actually it is still clear with the concepts uh i will recommend uh going through that first and then coming back to this video and continue so uh you calculate the prefix function so function is basically uh at any index it tells us how many if there is a suffix which is also same as the prefix for the particular strings for example if my word is something like a b c d and a b c then my prefix will look like 0 1 2 3. so if you see right uh in this string is there in this thing is there a suffix which is also same as the prefix no right here no and but in this string yes there is the one length suffix which is also same as the prefix in this there is two lengths of thing which is same as the prefix so basically pi table calculates that uh data and then once you have that data you can easily uh basically you can easily uh use this logic to just i mean basically it's sort of pre-computation to tell us when you are pre-computation to tell us when you are pre-computation to tell us when you are comparing two strings not to start comparing at the beginning position again when we have a mismatch but just to go at some previous position that we're sure that okay we have already matched this number of elements we need not to go back or look back to the starting position itself will backtrack to the position we know that okay we have the exact match uh till this position so you basically loop through the world and pattern and then uh i mean this logic would be clear from the video actually and the link so and then uh if they don't match you go back to the previous entry into the prefix table for the j else you increment i by one uh if j not equal to zero you have to write increment uh i by one actually oh i mean this might not be clear here but yeah so basically it's like you calculate the prefix uh table and then if word i is equal to pattern j you don't bother you just increment j and i right and then else what happens is if they are not equal and j is not equal to zero you said that go for j it should be prefix table of j minus 1 right else if j is 0 you just do an i plus at the end if you see that we have already covered the pattern you just implement the count and break out and then you return the count the complexity in this case will be order of l into n plus m where l is the length of the patterns uh and m is the length of the pattern psi and would be the length of the world so this way we can save on complexity the crux of this problem this user problem would be that you should know kmp string magic algorithm which is a very efficient uh string matching algorithm that uses some sort of hashing optimization to compute the uh like string matching and pattern match so yeah that's it for the video if you like please hit the like button share subscribe see you in the next video thank you
Number of Strings That Appear as Substrings in Word
longest-substring-of-all-vowels-in-order
Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc " **Output:** 3 **Explanation:** - "a " appears as a substring in "abc ". - "abc " appears as a substring in "abc ". - "bc " appears as a substring in "abc ". - "d " does not appear as a substring in "abc ". 3 of the strings in patterns appear as a substring in word. **Example 2:** **Input:** patterns = \[ "a ", "b ", "c "\], word = "aaaaabbbbb " **Output:** 2 **Explanation:** - "a " appears as a substring in "aaaaabbbbb ". - "b " appears as a substring in "aaaaabbbbb ". - "c " does not appear as a substring in "aaaaabbbbb ". 2 of the strings in patterns appear as a substring in word. **Example 3:** **Input:** patterns = \[ "a ", "a ", "a "\], word = "ab " **Output:** 3 **Explanation:** Each of the patterns appears as a substring in word "ab ". **Constraints:** * `1 <= patterns.length <= 100` * `1 <= patterns[i].length <= 100` * `1 <= word.length <= 100` * `patterns[i]` and `word` consist of lowercase English letters.
Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring.
String,Sliding Window
Medium
2186
1,047
Hello hello viewers welcome to my channel it's all the record problem remove all odds and click ads in spring so basically in this problem given in this strange facts and need to remove the duplicate latest correspondingly cases were getting this letter in alwar district former they are not Able To Delete Favorite More Stupid Leaders Will Stop At And After Verses Subscribe Indian Student Of The Book We Will See A Severe Subscribe And Will Remove This And Finally Bigg Boss ccl2ncl Cricket Live Account Remove Any Duplicate Sunao Edison Replicates Will Stop That Youth Subscribe Thank First Yourself Into Thin The Solution For Solving Problems We Can Use And Basically Tried To See Where You Can Be Removed From Jaundice And From That Point Subscribe Like Or Subscribe Now To Receive New Updates Reviews And Order Of River Subscribe Element In Delhi On One Side Blunder First Saw This Listing Fast Destroyed And Widening Leo Sperm Subscribe And What's The Correct Top Most Obscure Subscribe Channel Subscribe Videos Subscribe Now We Characters subscribe The Amazing Overseas Note Add Post This Character In To Our Strike A Balance Will Find Difficult No Veer Vo Element Ko Suli Element Which Is The Results And Remove Duplicates subscribe and subscribe the Video then subscribe to the Page That And Sew Distance From Nowhere To Treat Harvesting Coffee And Any Character Invest Deep Silence Tej Dhawan Will Not Distract You Can You Subscribe Rimpa One Subscribe Share Subscribe To More This Would Tell One Anything On Currency Sunna Howie Define Spin Boldak Hua Hai Hua Ki Stringbuilder Novi Team Royal Stag Effect Size Music Clip Siemens Notification 05 Characters From Big Star Entertainment Awards Winners And Intuitive Thursday that and two strings result and answer is a so let's compile record and fierce fighting for details whom who looks like compiling taking too much time will withdraw it is very slow this time not subscribe to the fact that accepts all what is the time In Cases Where Like Trading Between Characters 151 Hindi Our Springs During That Time Collector The Time Complexity Of Dissolution Click On The Like Button The Few Lines Of Wave Jeff Sid Dip Character From Bottom subscribe and Share and subscribe the Channel and subscribe the Video then Amazon Sleep Separate Strike Is Data Structures How We Will Do It Fennel Fail Let's Move District Courts Should Be Used For Testing Weather String Will Be Used As Widow Of Land In Sydney Subscribe Nov 13 - subscribe and subscribe this Video Subscribe - Operation Pillar Of A Meeting Last Train Accident Se this one so let's clean your Hair victory clean 9 we will do subscribe to first quarter rain and unemployed na this what is feeling pit bune this pack number character messed up hair in the or else security not so let's subscribe and dont consider a specific Subscribe Like and Subscribe Problem and Subscribe Thank You
Remove All Adjacent Duplicates In String
maximize-sum-of-array-after-k-negations
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them. We repeatedly make **duplicate removals** on `s` until we no longer can. Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**. **Example 1:** **Input:** s = "abbaca " **Output:** "ca " **Explanation:** For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ". **Example 2:** **Input:** s = "azxxzy " **Output:** "ay " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters.
null
Array,Greedy,Sorting
Easy
2204
1,601
hey what's up guys this is john here so today uh let's take a look at uh this week's weekly contest uh problem 1601 maximum number of achievable transfer requests this is the last problem of this week's uh weekly contest i mean the other three problems i are not that good i know especially for the third one you know the uh the product the description of the problem is really confusing i mean i spent a lot of time you know trying to understand what the problem was i mean what is really asking you to do i mean i would spend a lot of time on that i mean once you figure it out it's nothing more than a dfs right basically you just maintain like the uh a hash table with a parent and child and then in the end you just do a dfs based on the hash table okay cool enough talk about that one okay so let's take a look at the last problem of this week's uh weekly contest so you have we have n buildings number from zero to n minus one and each building has a number of employees okay and it's transfer season some employees wants to move to another building okay and the next one is that you have a few uh transfer requests here so the first one means that uh one person from building zero wants to transfer to one and the other one this one is this one person from building one uh one wants to transfer to zero same thing so on so forth okay and it asks you to return the maximum number of achievable requests so what does the achievable request means it means that after all these requests all the buildings number stays the same okay basically you know after the maximum trans the transfer request the in degrees basically the numbers the indegrees of each building should stays at zero okay and for this problem you know i spend some time you know trying to solve it by uh by some greedy approach you know like the uh i will just try to just cut try to calculate all the integrate first and then in the end basically i loop through all the other the request and then i find out the uh only the degrees the integrate that is that's not equal to zero okay and then i just uh try to uh calculate the final result based on that but then i realized that's not the right approach the why is that because if you do that right basically if some of the requests by adding that request will make like two buildings in balance okay so which means for some requests we don't want to use it but so and then i just abandoned my previously approached so i start trying basically now the problem comes down to the uh we just need to try all the other combinations okay then what are the other combinations so now this one come becomes to you know at each of the in the request here we only have two options we either use it or we don't use it and again so then the problem actually becomes to the what a backtracking problem right basically you know at each of the step here right you have two options right you either use this one or you don't use this one and we just need to try out all the part the possible combinations and in the end we check the uh which one can give us the uh so basically by the time we have a loop through to the end of this request here we check if the buildings right if the buildings the indegrees they're all zero and if that's the case we'll basically would will use the current uh current use user request to update our final answer okay basically that's the yeah that's the basic idea here so to do that i'm going to i define like an integrate here okay i'm using a default dictionary as an integer here okay and then we have answer equals to zero so like i said i'm going to use a backtracking method here and the first one is the i here and second one is the count so and then in the end uh we call the backtracking my third we start from the first request and the column is it's also zero okay in the end we simply return the answer so how about the backtracking here right let's try to do the backtracking first so the backtracking is the first one is that we take we use we take ice request okay and then the second one is we do not take ice request okay so if we take the ice required so what do we have the in degrees here right the in degrees here basically you know the from and two okay we have a from and two so the from is the request zero okay and the two is what request one so with the in degree right so the f the integrate will be decreased by one okay and the same thing for the two in degree will be increased by one okay so now we have a backtracking here right so now let's move to the next one the i plus one and then the count will be account plus one because we know okay we take the current request so which means the count should be increased by one so we call it backtrack because after this one here we're gonna return we're gonna mark it back because the next one is not take this one and also because every everyone is sharing the same in degree dictionary here that's why for this one we're gonna after this one we're gonna basically uh set it back to the original value here um now the second one is this the second option is we don't take the uh the current one okay which means we have a backtrack just i plus one and then the count basically it's empty uh we don't change the count because we didn't take the ice request so what's going to be our the base case basically the base case is if i equal to the uh the length of okay let's request length of request okay if i equals to the r here and what and now we need to check if all the indegrees are zero okay i mean we can just use like a like the easiest way right or we can actually use if any or anything but i'll just use this if key in degree for this if the in degree okay in degree key is not zero uh we return basically we just return okay else it means that any everything in every all the keys in the in degree are zero which means that this is a valid state it's a balanced state we just update the uh the answer is the uh with the current count okay yep i think that's it let's try to run the code here unhashable list oh sorry here i need to get the ice request and then the front two oh yeah okay which one is out of the range oh sorry we didn't return here okay so cool submit all right cool so it passed all right i mean uh i think this one is it's like a it is a good problem you know uh it's just that you know okay sorry so for the how about the uh the time and space complexity right so the space com time complexity is that at each place we have two options so basically the it's going to be the 2 to the power of r here right that's the total backtrack options times what times uh do we have a times here do we have another uh yeah and we for each of those okay so for each of these options here in the end we will have this one here so that's going to be the n here right times n because we will have a for loop here to check everything in this in all the buildings in other buildings so to get the uh the final to check to validate the base case yeah so that's the time complexity here yeah and actually there's another way of doing this you know since if you guys scroll down here right so i mean as you guys can see the request here is only uh the maximum request length is 16. and like i said each one of the request only has one uh two options we either take it we or we don't take it okay so then what that reminds you guys is that we can use the mask okay we can use the mask to uh to represent the state of this in degree here because you know right now for the current approach here basically we're using like this in degree to uh to help us to track the uh the current state uh sorry the in degrees plus the count to help us track the uh the current state okay and what another thing is we can do is here that we all we need to do is we just use like this like the bead mask here okay we just need to check basically for anything that's if these requires are marked uh it's what i mean it is used we just mark that request to one so still we have a two to the power of our total possibilities right for all the combinations of the requests and then in the end we simply check among all those combinations okay what are the valid ones and if there are valid ones can we get the total what's the uh the total number the total request for that state and we just need to get the maximum of that similar like this one but the way we are i we're out identifying the state is different we're not using the in degrees and the count instead we only use a single mask here because with the current mask uh we know which request uh it's marked to be used and from that we can simply reconstruct the in degree here okay and you know what i would probably out i'll try to implement that real quick so just for those ones for people who is interested in the beat mask solutions i'm not a big fan of that but let's just do it okay so that's that i'll do it really quick here so the r is this the length of the request okay and then the uh like i said you know in the end right we have uh so we just loop through all the possible solutions of this other possible state of this beat mask so what are the possible states it's 1 to the 2 to the power of this length okay that's the basically the final state and um and then for each of the state here right we have a mask here right and then we just need to have like another helper functions here however function has to help us check with the current mask if it's valid or not and if it is valid what are the total ones in this mask so and i'm going to use the same integrate here okay so default int interior okay and then we have a total count of zero and then so to say it's just similar here similar idea here right in range r here right in range for the because we have this number of the uh the beat the beats here right so uh if and we just need to check if this uh current bit has like a one right how do we do the check if it is one we just do this where we move we do a bit shift to the left by the eyes here and then sorry okay by eyes here and then we just do a and with the mask okay if this one is true it means that uh the current one is the current bit is one and then we just do a count plus one and then we do what we do uh from actually i'm just going to copy this one here from one two okay i'm going to copy this one here okay right because now we know okay for the ice request we mark that one to be used so to use that it means that the f indegree will be decreased by one the two degree will be increased by one okay so and then in the end same thing here right we check this once this is done we simply check if this uh if this in degree has everything equals to zero okay because otherwise we simply return zero else uh we return the count basically the count is the number of the request for this mask okay and the same thing here right the answer equals what the max of the answer of this what uh the helper of the eye here okay return it's an answer yeah i think that should work oh here okay run it submit yeah as you guys can see this one is pretty slow maybe it's because i'm i shouldn't have used the default and this one maybe i can instead of a dictionary i can use like uh a list that will maybe improve the performance a bit but you know you guys get the idea here right i basically this one it's just it's similar like this one but we're doing like in a in the reverse way right here we are like uh taking this state with us in the end we simply uh validate that right divided the final state and here we are doing the similar things but instead we're using a bit mask so and then we just loop through all the uh the bitmask from zero to uh to this one okay that's all the possible combinations of the of either use or don't use uh each one of the requests here and with the current mask here we are we do the same little thing right we uh first we check we get the uh the used request and for each of the use requests we check we populate this in degree here and in the end we check if this in degree is a valid state and then we just return the count to be so that we can update the final answer here cool yeah i think this i think it's a good problem you know uh but for the last one i'm i was expecting a little bit more yeah maybe some graph problem or a dp problem you know something like that but this one is just nothing else than uh then like i would say it's kind of like brutal force way plus a little bit of backtracking yeah anyway thank you so much uh for watching the videos guys stay tuned see you guys soon bye
Maximum Number of Achievable Transfer Requests
maximum-number-of-achievable-transfer-requests
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
null
Hard
null
139
hello everyone welcome again to my channel and rickerson with dp memo video so here we will solve another problem that is 139 word break and it is quite a famous problem and it has another problem called word break too so here for this word break problem we will use recursion with dp memorized technique which we solved in the previous problem where you used it in minimum cost problem so the problem statement is saying given a string s and a dictionary of strings what dictionary return true if s can be segmented into a space separated sequence of one or more dictionary words notice that the same word in the dictionary may be reused multiple times in the segmentation so what basically it is saying is you will be given with one string say lead code and another what dictionary or collection of words you can say that is lead code like that you have to tell this word you can form using this word of dictionary or not any word you can use multiple times and if you con concatenate those things then you can form this word s or not that you have to return like true or false here if you check lead code you can form easily by just appending lead with code then it will be a true if you take another example apple pen apple and the word dictionary is apple and pen here also it is possible because apple you can take twice means apple then pen then apple so you can make use of this dictionary words and form the string so here also it is true here we will check another example cats and dog so the word dictionary contain the words cats dog sand and cat if you check here cats you can get here then the remaining part will be and that also we can get here but og is not present here so if you get dog also then also it is not matching so no way you can form this word using this dictionary words so in this case it will be false though it looks like that these words are present here but if you look carefully if you add them or concatenate them you never can form this string word and here is few constraint that the string length will be 1 to 300 and the dictionary length will be thousand means thousand words can contain and the word dictionary length will be 20 means one single word what can be of length 20 so these are and all letters will be in lower case and all the strings in the dictionary will be unique means no repetition now to solve this kind of problem why it is a bit hard is because you don't like that what part of the string you will cut and then append the other part because cats also you can cut from here or cat also you can cut from here and after that whatever decision you will take then the remaining part you have to check and match with the other words so it's a step by step decision what you can do so now we will check in this case how recursion will help us and how we can optimize this problem using dp memorization technique so here we will take our first example and apply recursion to check how we can solve this kind of problem so the string is cats and dog and the word dictionary is cats dog sand and cat so as i have mentioned in the earlier videos of recursion or backtracking that in recursion or backtracking kind of problem you have to first think as a normal human being that what are the steps we can take and what are the decision i am taking and based on that how i can growing suppose if i have to think normally then what we can do cats and dog one string is present first i have to match that the first part of the prefix part because anyhow if i have to form this string then initial prefix also will match with some of the word right then we have to think about other part so our first job is to find if any of these words matches with the prefix so here i got that cats can be a match or cat can also be a match right because both can match as a prefix in this word so that is the two decisions we have to take once if i am taking cats then what is the remaining string that is undog okay another decision is if i am taking cat then the remaining string is sandog cool now we have to proceed again and apply the same logic for the remaining part also for and dog i have to match the prefix here what part will be match and will match only that means if i match with and then the remaining part will be og okay and as in the recursion call we will go as dfs manner first we have to complete one single substring and then we have to return back and check the other possibilities so actually if we start from cats and dog first when we are matching with cats and growing this part of the tree first i have to complete this part but to train our mind i just shown that the next part of the job will be with the sand dog okay so after and dock when i got that and is matching the remaining part is og from here if we have to go forward then we have to match that for og is there any prefix matching or not but unfortunately nothing match we found here that means this path we can't proceed and this path is returning false means if we go like that we can't get a match then you have to check for the other possibilities so from here also nothing matched apart from and so we have to return back and check from sand dog how we can proceed for sand dog what is the matching prefix here sand is a matching right because this part we can match then after that what will be the remaining string again it's og that means here we can't form the string cats and dog using this word dictionary because we run with all the choices but not got a correct result let's try with another example here the string is apple pen apple and the word dictionary is apple and pin here also we'll run with our choices so first we will match one prefix from this word dictionary so the first match is apple okay so if we match with apple then the remaining string will be this pineapple now we have to check with pineapple something is matching or not as a prefix yes pain is matching then what is the remaining string that is apple and now we have to check if something is matching with apple or not yes it is matching the prefix then we are done means it is true we can form this string so if after that my string will become empty right a empty string empty means i have consumed all the word dictionary to form the string so if i go via this path and we are done so it's a true so if we have a very long word and a long series of word dictionary and if we keep on drawing the decision tree things will be like more example or more cases we can handle and we can see but i think you understood right so how we can solve this and as we have to return true and false or you can say we just want to check that it is possible or not that means if any of the tree you can get true you have to just break out so if someone is saying that how many less what you can use to form this and all that is a different question then you have to compare between all the paths but here they just want to know that it is a true or false so if you find somewhere stop there and return true our job is done now the question is why i told that along with this we have to use dp memoization also where that thing can come into the picture that i will discuss now so now where dp will come into the picture let's say we have a very big word and when we are breaking them down we found that word og okay and suppose after breaking down og or take some paths we got to know that we can't proceed with og and og will return us false that time if i again get og somewhere we no need to proceed further with our choices so one table we can form they are all the sub strings when i am going i can make a note that for og it will be false or say for sand dog something and all so next time when i'll get og i will check what is the value present there if it is false that means no need to proceed in this path it will give me result as false so think about a very big decision tree so there if we take help of this dp memorization table then so many calls we can reduce right so here we don't have to go deeper maybe somewhere else also we can find a string where already i have a calculated result in this dp table and i don't have to go further we can directly pick the table from the say hash map or something right so that is the advantage you will get if we have a big tree so that's why this kind of problem is of recursion with dp now we will go jump into the coding and i will understand this thing better now i will code this part how we can do the coding so this word break method is what it whatever it is passing is one string s and a list of string which is what dictionary so i will repeat this method as a recursion call and what will be the base condition for that so if we reach to the end say our ace dot length equal to 0 then we'll return true means if you remember from the diagram so every step will reduce the string after matching the prefix part so at the end if it is 0 means everything got matched that time will return true and that will be the best condition for this recursion call if that is not there string s has some length so what we can do is we can fi we will try to find that if any prefix is present in the dictionary or not so for that purpose we will iterate over the dictionary word dict okay and we will check that if any matching prefix is present or not but first we can do a check here that if this steer dot length means the word length is greater than the string length that means there is no prefix possible right so that time will just continue means if this apple itself is bigger than this word length then it will not be a prefix of that thing right so that is why i am continuing so now we can take a variable called boolean result which i have to check that it is what it is returning so if ah this string is starts with means its a prefix of string like str is a prefix of string s that time i have to check what is the remaining string because that i have to pass to the next recursion call so that will be substring like s dot substring up from str dot length means after cutting the str whatever is remaining so our result will collect from the recursion call say result will be again this what break we have to call and here i have to pass this suffix and word dict okay so next time my word will be the suffix because prefix already matched and here if we get that for that call if this result equal to true that time we have to return true or else after end of this loop we can simply say nothing matched and we can return false so now if we run this problem so this is working right so if we submit now the solution is perfect but it is time limit exceeded because we have done things correctly but we have not used dp memoization technique that's why it is going through all the recursive calls right but the expectation is we should use dp memoization technique to reduce the calls so now what improvement we can do is we can define a map hash map of type string and boolean okay so where we can store uh like suffix string and the result what we got from the previous recursion calls so now if we have to look up into this map same memo if it contains ah this string key okay this so it will be contains this string key s then we have to return the result from the memo map which will be s okay and how we can store this result here so whenever i am getting the result here that we can store memo dot put i have to do and there it will be suffix and result now if we run this problem it is working here and now we will submit also and it is working so this is the way we have to solve it using recursion and dp memoization technique thanks for watching
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
445
hello and welcome to another Elite code video today we're going to be doing the problem of the day for July 17th add two numbers too it's a good link list problem helps you know use linked lists also you have to know how adding actually works like in normal Edition which is kind of important okay so you're given two non-empty linked lists you're given two non-empty linked lists you're given two non-empty linked lists representing two non-negative integers representing two non-negative integers representing two non-negative integers the most significant digit comes first and each of their nodes contains a single digit add the two numbers and return the sum you may assume the two numbers do not contain any leading zero except for the number zero itself so we have this first example where we have seven two four three and we have five six okay and so what we're actually doing here is we need to be adding like down this way and the least significant bit is going to be over here so we're going to be adding from the right so we're gonna have a seven here we're gonna have a zero we're gonna carry a one here then we're gonna have a seven plus one so that's going to be an eight and then we're going to have seven here so that's going to be our answers for this and finally they're gonna look like this okay so that's going to be our linked list for the first one and similarly for the second one I'm not going to draw out the whole link list I'm just going to draw out the actual numbers so we have two four three five six four so we're going to be adding from the right again and so we're going to have a seven a zero carry the one and eight it's gonna be eight zero seven and then finally for the third example it's zero plus zero so obviously for zero plus zero it's going to be a zero so how do we do this and how do we make it easier on ourselves to do this well the thing is if we start with like these last elements right so let's just go back to the first example let's use another color maybe so let's use green okay so like let's say we have this essentially seven two four three and five six four so we can get to like the very last element to add them but then how do we Traverse backwards right like we can add these two elements but how do we Traverse to these two elements so what can we do here to make life easier for ourselves essentially and wouldn't it be nice if our lists were reversed okay so let's take a look what that would look like right if our lists were reversed so instead of this we're going to have the same seven to actually we're just gonna keep it like this but we're gonna delete these and we're gonna put them in Reverse right so let's say our list now are this way well now this is a lot more straightforward right like we can compare two elements then we can just go to the next two because we can use the next pointer the step number one what we are actually going to do is we are going to reverse the list and so we're going to make a helper function to reverse the list that's pretty straightforward just how to reverse a linked list you know that type of thing and it's pretty straightforward you just use a previous and a next pointer or a current pointer and you just you know swap these arrows I'll go over that in my code um I actually I guess we can go over it really quick maybe some people aren't familiar with other person like list so let's do that really quick so let's say we have a five six four show you how to reverse it really quick so we're going to have a head so let's just say we're going to have a head and it's going to be like this okay and then we're gonna have a previous pointer previous point is going to be null and that every step we're gonna what we're gonna do is we're going to make a temporary variable that's going to be the next of the head so let's just call that here so we're going to make a temporary variable here and then we're going to say let's make the head point to previous so we're going to make the head point to null then we're going to delete this thing and then finally what we're going to do is we're going to make the previous equal to where the old head used to be and we're going to move the head up over here so now the head is actually going to be let's delete that as well and let's actually make a new head so now our head is going to be over here our previous is over here and then our arrow is pointing there and then we can finally this previous okay so our head's going to be there and we just keep repeating this so once again our previous is over here our head is over here we're going to do the same thing so we're going to make a temp node over here now you know at the head.next we're going to you know at the head.next we're going to you know at the head.next we're going to delete this so now this is like this then once again we are going to make the head point to the previous we're going to make the previous come over here right so previous is going to come over here delete this and then the head is going to go to where the temp used to be so now the head is going to be over here and this temp is deleted and now finally one more time right so we're going to have a temp again except now our temp is out of bounds so we're going to make the head point to the previous so that's going to look like this and that'll be there and we're going to move the previous to where the head used to be we're going to make the head out of bounds and then finally so this previous is gone now finally our head is out of bounds so we're done and we just returned the previous so you can see how this 564 looks like this list over here but yeah that's how you're going to do that pretty straightforward for that part so we're actually going to get rid of all this now so we did reverse the list now what are we doing now that I showed you how to do that now what are we doing well now we can just add one number at a time right so what we're actually going to do is we're going to be adding one number at a time we're going to first make my dummy node which is I'd recommend you to do a lot because that'll give you the new head of the list so let's say we are going to make a dummy node you know just over here and now what we're going to do is we're going to be adding and now we have to figure out pretty much how to add correctly right so when we add what we need to do is we need to have one more variable in an ad the way an ad works is you have a carry in and Carry Out bit and so R so it's going to be number two add so we're going to have a carry in and carry out of it but actually we're gonna use one bit to do that we're going to use a carry so we're going to make our carry equal to zero then every time we add we are going to add these numbers so like we're going to do three plus four here that's going to be 7 and we're going to add the carry so it's going to be let's write it over here so it's going to be L1 plus L2 plus the carry value and if one of these doesn't exist then we're just going to take the other one right so like in this case we would just take this value only because this one doesn't exist so that's what we're going to do we're gonna do L1 plus L2 plus the carry values the carry value starts off at zero so let's do this so it's going to be 3 plus 4 plus the carry value which is zero that's gonna be seven and now that we get the seven our actual value we need to be putting in so our value let's call it is going to be whatever this ad is so add mod 10. okay because like let's say we get 17. if you think about what would you do if you have a 17 you would put in a 7 and then you would carry the one right so our value is the add mod 10 and then our new carry is the add divide by 10 and it's going to be an integer divide so if we have like 17 this carry would now be a one but anyway so let's do this so this is a seven we don't you know seven mod ten is seven and then this is like this we're gonna make this here and then we're also going to have a current node that's going to be you know it's going to start here and it's going to move every time so we start here we're going to move over here and now we need to add these and what's our carry so our carry is the add uh divide by 10 to the 7 divided by 10 0 so that's going to stay zero okay now let's just say this is L1 this was where the node was now they're going to actually move over here now right because we just use those values so L2 is going to be here L1 is going to be here and now we have our current is going to be over here it's going to move right we make a new node we move and we move these two okay now we need to add one more time so when we add our total is 10 but our value is total mod 10 which is zero okay and now what's our carry is 10 divided by 10 which is one so now our new carry is one we're going to put in a zero our current is going to move over here and now our L1 is going to move over here and our L2 is going to move over here so we have an L1 we have an L2 now we need to add these two so we have a 7 but remember it's L1 plus L2 plus carry and our carry was one so it's actually going to be an eight and what's our value so our value is the add mod 10 so 8 mod 10 is 8. right and then what's our carry is ADD divide yeah our carries add divided by 10 so 8 divided by 10 is zero so that's going to be back to a zero and now our current is over here and now these values move so this one becomes none and this one becomes seven okay and so now we have two more values so this is none so we can just say like if it's none let's just give it a zero and well let's take the other value so this is a seven so we're going to have a seven we don't have a carry bit so it's going to go over here current is going to come over here and now our carry is zero so now we finally have a linked list where our current is over here but from a picture you can see that this is like reversed right so if you look over here we need to reverse this list one more time so how do we do that well we actually want this node over here right so we need our list to look like seven and then next eight next zero next seven so what we need to do is we actually we're going to move our carry or not our carry our current node all the way to the this is why we use the dummy node so we're going to move our current node all the way to the next of the dummy right so we're going to move it over here so we're going to have our current node here then we are going to break this little chain because for our reverse list we don't need to include the dummy node and now we're simply going to reverse this right so we're just going to reverse this set 7087 list and that's going to give us a reverse list so that will give us 7 8 zero seven not really sure why this is doing this but I'll figure that out later but anyway so we're going to have this list and that's what we're going to be returning and this is going to be the new head of the list here so that's what we're going to be returning so that's the final step is once you actually do get this whole 7807 you have to do a reverse and there is one more thing right there's one more thing let's say you added some numbers like let's say here this was like a seven and we added these numbers right and then these both become out of bounds and then this becomes whatever but now we actually have a carry out bit right so we do have to check once we're actually done adding these two lists if we have a carry out bit we actually need to put a one in the front of like the new list of that we made before reversing obviously so if it would actually go like over here so that's going to be like our condition like if we do have a carry out because we added the last two even though both of these are out of bounds now we actually need to add a one and so that's gonna be the final thing so let's review our steps so one is going to be reverse the list right and then two is going to be sum up the lists and then three is going to be reverse the result okay and we're like I said we're going to use the helper function to reverse this because we're going to do multiple results so we might as well straightforward as long as I'm saying how a carry inbit Works in a carry out bit and that you have to know that when you add you have to actually add both of these and the carry bit so essentially in a normal um in like a normal like low division Edition it would be something like you know one like if you had two numbers you would add like a plus b plus C in would be your carry in and then you would get your total and you would get your C out and then you'd use your C out to be the C in of the next thing which is kind of what we're doing here this is the carry in the carryout so let's actually code it up we have enough now so first let's make a reverse list function so that's pretty trade forward right so we need to make it def reverse concrete is going to take the head of a list we're always guaranteed to have a list here too so these lists are one length so we're never given like an empty list so we're gonna have a previous standard reverseless problem we're gonna have a curve equals the head and we can just say while Cur and this is what I said what I showed earlier so we're going to make attempt for occur next because we are going to take her next and make it to point to previous so we need to save the current next that's going to be over here then we're going to say previous equals Cur and Cur equals temp to move that up and then when so we actually have some formatting issues here fix those okay I think we should be good now okay so and then finally we return previous because remember our head is out of bounds here and our previous is actually the new head of the list okay so now we need to reverse these two lists so let's do that so let's just say L1 equals reverse of L1 L2 equals reverse L2 and now we're going to make a dummy node it's not going to point to anything we're going to make a curve it's going to equal to the dummy node we're going to make a carry bit it's going to be zero and then finally now we need to do our Loop for the addition so while L1 or L2 while either one of these has a value let's get these values so we could say like L1 Val equals L1 Bell if L1 equals none l0 right so if our L1 is out of bounds we can just make it zero because we're not going to be able to get the value right like let's say our list Y is only two nodes two is like seven nodes we're going to be out of bounds here for a long time so we're just going to say let's get the value if we can but if it's out of bounds if it's none no let's uh let's make it zero same thing for L2 Val so if it does exist let's get it otherwise it'll just default to zero okay and now we need to actually move both of these L1 and L2 because we just took them so we need to move the pointers to the next note if we can but if we if they already know then let's just leave them the way they are so we can say L1 equals L1 dot next if L1 does not equal none also a one right so if l1's already null let's just do nothing let's just leave it the way it is same thing for L2 dot next if L2 does not equal 9 L cell two and this is just going to be a little bit cleaner because we can just do all our logic in one while loop instead of like having to check if we do have something out left in the end so you can definitely make this like take more lines of code if you wanted to okay so now let's get our total so our total is going to be the L1 vowel plus L2 Val plus the carry in bit right and then we're going to divide that by or sorry we're going to mod it by 10. that's going to be the total is like the number we're actually putting in it's going to be all this added together modded by 10 because let's say we get 17 we just want the seven and now finally we do the carry and it's going to be similar so this the carry is going to be all the same code except instead of divide instead of mod 10 it's going to be divide by 10 right so if we get a 17 our carry should be a one so 17 divided by 10 is 1 because it's integer divide so it's going to drop the remainder now finally we do curd.next now finally we do curd.next now finally we do curd.next so our current starts with the dummy node equals we need to make a new node with the total that we just got then we need to move our current over okay so now once we're out of this Loop both L1 and L2 are pointing to null but remember we do have to check that final carry out bit because if that carry output is a one we need to actually address that so let's do that so we can say if carry we can address that right so Cur dot next equals list node one okay so we can do that now we need to do a couple more things so let's just get some more space here so now that now our list is actually looks like this right so it's going to look like the dummy node with these nodes in reverse order but we actually need to reverse them so we're going to make our current over here we're going to make it over here so get rid of that it's a little laggy okay we're going to make it over here and then we're going to reverse this list and we're going to sever this connection because we don't want the W node inner outcome so let's do that so we can just say uh over here per equals dummy dot next and dummy dot next equals none that's why we use the dummy so we knew where the head of the list is going to be that's why the dummy is really useful now we can finally return a reverse occur that's going to be the reverse list right so essentially our list is going to look like this we're going to reverse it and then the new head of the list will be over here and that's what it will return reverse occur and finally let's take a look to see if it works it looks like it does okay and it's reasonably efficient so let's look at the time and space complexity here usually time and space for Linked lists is almost always open but let's take a look so we are reversing out one and we are reversing L2 so we have to do we have to Traverse them both right so because we have to Traverse them both that's going to be like let's say L1 is n and then L2 is maybe like M or something or M and N whatever it is so that's already going to be you know Big O of M plus n essentially whatever if m is the length of list one and N is the length of list two because we're traversing both of them we're reversing them okay now we make this dummy doesn't cost anything now we Traverse these lists and so this part is actually going to be o of whatever's greater L1 or L2 so it's going to be the max of L1 or L2 but that's going to be less than this value here so we can ignore this uh and then we can ignore this carry and then finally for our reverse that's also going to be the max of L1 and L2 which is smaller than this so that's going to be our time complexity here now what about our space so what are we doing so we are actually reversing these in place so that costs us nothing and then what else are we doing so we do create a new list right we do create a new list and then our new list is going to be linked like I said it's going to be Max of M or n essentially that's going to be our space complexity here so space time so for example you know if this is four nodes and this is three nodes then our list would be four nodes maximum five nodes if we do have a carry but that's going to be negligible it's going to be the max one of these you know maybe plus a node but it's plus one is negligible for bigger notation so that's going to be that it's just going to be the maximum one of the list because we are reversing these two lists in place if you were to make two new lists then it would be M plus n as well because you're making two new lists but because we're not we're just doing Max M plus n and for the time it's n plus n all right so that's gonna be it for this problem hopefully I explained it pretty well and uh definitely a good one to know definitely a good one to practice link to this problems and these linkless editions or just like these kinds of additions where you need to either add node by node of a linked list or an array are really common so I would encourage you to get familiar with how audition works with a carry bit and you know just like practice that make sure you get it right make sure you handle the edge cases where you do have a carry out even though you're out of bounds on your list and things like that but that's going to be it uh if you like this video then please leave a like And subscribe to the channel and I will see you next video thanks for watching
Add Two Numbers II
add-two-numbers-ii
You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. **Example 1:** **Input:** l1 = \[7,2,4,3\], l2 = \[5,6,4\] **Output:** \[7,8,0,7\] **Example 2:** **Input:** l1 = \[2,4,3\], l2 = \[5,6,4\] **Output:** \[8,0,7\] **Example 3:** **Input:** l1 = \[0\], l2 = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in each linked list is in the range `[1, 100]`. * `0 <= Node.val <= 9` * It is guaranteed that the list represents a number that does not have leading zeros. **Follow up:** Could you solve it without reversing the input lists?
null
Linked List,Math,Stack
Medium
2,1774
218
Hello and welcome. I'm James Murphy. In this video,&nbsp;we're tackling a hard interview question: The Infamous Skyline Problem. I'll explain my C++&nbsp;solution which beat 98.24% of other submissions in speed and 100% in memory. In case you've never&nbsp;looked at a beautiful city view and thought: I wonder what mathematical function describes this&nbsp;skyline. Don't worry. The more practical view of the problem is finding the pointwise max of a bunch&nbsp;of piecewise functions. But thinking about it like buildings is just easier to visualize. We're given&nbsp;a bunch of buildings represented by their left, right and height. And we're supposed to produce&nbsp;the skyline formed by those buildings which are represented by x, y points. That description&nbsp;is a bit dense. So, let's look at it visually. First, we have the buildings defined by their&nbsp;left and right x coordinates and their height. Their outline together with the implicit ground at&nbsp;height zero forms a skyline. Because the buildings are perfectly level and two-dimensional, the&nbsp;skyline itself is piecewise rectangular described&nbsp;by its corners. Since the rectangles are perfectly&nbsp;level, we don't need all the corners to describe the skyline. Since whenever there is a change&nbsp;in height, the x-coordinate doesn't change. That means, we can fully specify the skyline using just&nbsp;the points where the height changed which is what the problem statement for this problem expects. So, we take in the buildings as a list of left, right, height coordinates And we output the skyline&nbsp;defined by those points where the height changes Okay, let's get to the code. The first thing I want&nbsp;to point out is this horrible decision that leetcode has made. According to leetcode, buildings and&nbsp;points are represented by standard vectors of ints. Even though both of these things have&nbsp;fixed sizes where structs like these or at the very least arrays would be the&nbsp;fastest choice we're forced to use a vector. I'll use these using declarations for now. But at&nbsp;the end, I'll show you how we can go way faster if we just use fixed size types. I'll start off&nbsp;defining these getters for the building and point attributes. Don't risk using the wrong index by&nbsp;accident. These are all going to be optimized away anyway. Again, if buildings and points were just&nbsp;structs, we wouldn't need any of these functions. Okay, let's get to computing the actual skyline. First, let's make a vector of points to hold the skyline to return. We're going to reserve two times&nbsp;as many points as there are buildings because a building can contribute at most two points to the&nbsp;skyline. The algorithm I'm going to describe is a single pass algorithm which means that we're just&nbsp;going to look at each building once. And by the end of it, we'll have the entire skyline. The idea is as&nbsp;follows. We loop through the buildings one by one. When we read in a building, the goal of that&nbsp;iteration is to compute all the points of the&nbsp;skyline up to and including the left endpoint&nbsp;of the current building. As you can see in the animation, sometimes that means adding a point&nbsp;at the current building. Sometimes it means filling in points from right edges of previous&nbsp;buildings. And sometimes no new points are added. First, let's focus on how do we tell if we need&nbsp;to add a point for the current building's left&nbsp;endpoint. Well, we only add a new point to the&nbsp;skyline if the tallest building so far changes. So, in particular, we need to be keeping&nbsp;track of what's the tallest building so far.&nbsp; We'll use a priority queue that&nbsp;compares buildings by their heights in order to keep track of which building is&nbsp;the tallest that we haven't accounted for yet. Here's how you define a custom compare function. And here's the priority queue that we're using. We're just using a standard vector as&nbsp;the underlying container for the queue. We're also doing a little trick here in&nbsp;order to reserve space for the priority queue. We create the vector that we want to use as&nbsp;the underlying storage for the priority queue&nbsp;&nbsp; and reserve the number of elements that we&nbsp;want. In this case, we reserve enough space for the total number of buildings. Since, at&nbsp;most, all of the buildings can be active. One of the constructors of the priority&nbsp;queue then allows you to steal that data.&nbsp;&nbsp; We chose a priority queue because we want&nbsp;constant time lookup of the tallest thing. And it only costs us logn time to insert&nbsp;and remove. Okay, back to the loop. Whenever we see a new building, we go ahead and push&nbsp;it on to our active list. Then we go ahead and try to update the skyline with the current&nbsp;x value and whatever the new tallest height is. Getting the maximum height is pretty&nbsp;straightforward. Just look at the top thing on the priority queue or 0 if the queue is empty. Here's&nbsp;where we're using that the skyline is zero in the absence of any buildings. Updating the skyline just&nbsp;involves pushing the x, y coordinate onto the back of the vector. Of course, we only add a point&nbsp;to the skyline if it changes the height. So, if we try to push something that has the same height&nbsp;as whatever is on the back of the skyline already, we just do nothing. If all the buildings had&nbsp;unique left endpoints, then this would actually be fine. But it is possible that the two buildings&nbsp;both have the same left endpoint. If multiple buildings all have the same left endpoint, I'm&nbsp;still going to add just one point to the skyline. For that reason, I just push all of the buildings&nbsp;that have the same left endpoint in the same&nbsp;iteration of the loop. So, this works for finding&nbsp;the skyline points that are left endpoints at the beginning of buildings. But what about ones that&nbsp;are defined by the right endpoints of buildings? When we go to the next iteration of the loop, it's possible that we missed many right endpoints. Whenever our current x exceeds the right endpoint of the tallest building, that means that the tallest building is about to drop off. And that's&nbsp;a candidate for when we need to add a new skyline point. The logic for this one is a little bit&nbsp;complicated. So, let's put it in its own function. So, here's the function. The purpose of this&nbsp;function is to handle the case when the tallest active building is about to drop off. I know it's&nbsp;just a few lines. But there's a lot of thought that goes into making sure that they do the correct&nbsp;thing. The idea is simple. Just pop off whatever the tallest thing is and then try to add a new&nbsp;skyline point at whatever the new tallest thing is. The subtle issue here is that, for speed, we don't want to go through the entire priority queue and get rid of all of&nbsp;the things that should be deactivated. That means that whenever we pop something off the&nbsp;queue, the next tallest thing might be something that should have been removed a long time ago. We keep popping things off the top until we see something whose right endpoint is strictly further than the tallest building that we started with. Any tallest building whose right endpoint is left&nbsp;of our original tallest building's right endpoint, cannot be part of the skyline. It was either a&nbsp;shorter building that had the same right endpoint or it was something that should have&nbsp;been removed from a previous iteration that we didn't remove in order to avoid&nbsp;traversing the entire priority queue. That's why we're removing a bunch of&nbsp;things but only update the skyline once. That also explains the name of the function. We keep popping off the tallest thing until the right endpoint that we find is&nbsp;past the current tallest right endpoint. Returning back to the main loop. We keep popping&nbsp;off the tallest building and stale buildings updating the skyline until we find that the&nbsp;tallest thing remaining has a right endpoint further than our current x or&nbsp;until nothing active is left. This takes care of everything up until the end. But there's a little bit more work to do after we&nbsp;get to the end of the buildings. We basically just pretend that there's a building at infinity. And&nbsp;then pop off all of the remaining active buildings. Then of course don't forget to return the skyline. I wrote a bunch of tests. And I'm timing both how long it takes in total. And how long it takes&nbsp;just to run the actual get skyline function. Running it a bunch of times, we see that it passes&nbsp;all of my tests and does decent in terms of timing. But I think we can do better than&nbsp;that. I looked back at the code and once we put something into the active queue, we&nbsp;never actually use anything except for its height and its right endpoint. We never use the left&nbsp;endpoint. Additionally, since this active queue is something that's internal to our algorithm, we can choose a better data type than a vector. Here, we define a fixed size struct that's&nbsp;just the right and the height of the building.&nbsp;&nbsp; And we give it an explicit constructor to convert&nbsp;a building into just the right and height. Then we change our compare function and our priority&nbsp;queue to take in these fixed size structures instead of vectors. This allows us to get rid of&nbsp;two of our getters. Then everywhere that we used getRight or getHeight, we change to dot write&nbsp;or dot height. Also, instead of pushing building objects onto our active queue, we're now pushing&nbsp;these fixed size structs onto the active queue. Making this change took the total test&nbsp;time about 5 milliseconds down both in the total test time and time&nbsp;spent in the getSkyline function. Okay, remember the comment that I made at&nbsp;the beginning where I said that using a&nbsp;vector events here was a mistake? Watch what&nbsp;happens just by switching to fixed size arrays. Making no other changes, our times are now&nbsp;down to 6 milliseconds and 1 millisecond. We went from 40 and 15 down to about 6 and 1 doing&nbsp;nothing but changing to fixed size arrays. And this I think is one of the biggest problems with&nbsp;leetcode. This was supposed to be a competition for how fast you can make this algorithm go. But&nbsp;by telling you that a building and a point are supposed to be vectors of ints, they've already&nbsp;slowed your program down by a factor of 5. This just goes to show that designing a good&nbsp;interface and choosing your problem statement&nbsp;as carefully and as correctly as&nbsp;possible can really make a difference. If you do something, like, choose an inappropriate&nbsp;type for your function or return type, you can end up really slowing down the execution&nbsp;of your function. and then you also end up slowing down other things that now have to pass&nbsp;data around, reformat data into vectors in order to call the function. Anyway, I hope you&nbsp;enjoyed this solution. If you did, don't forget to subscribe. As always, thank you to my patrons&nbsp;and donors. I really appreciate your support. If you especially like the video, please consider&nbsp;becoming a patron. Thanks and see you next time.
The Skyline Problem
the-skyline-problem
A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_. The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`: * `lefti` is the x coordinate of the left edge of the `ith` building. * `righti` is the x coordinate of the right edge of the `ith` building. * `heighti` is the height of the `ith` building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`. The **skyline** should be represented as a list of "key points " **sorted by their x-coordinate** in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. **Note:** There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]` **Example 1:** **Input:** buildings = \[\[2,9,10\],\[3,7,15\],\[5,12,12\],\[15,20,10\],\[19,24,8\]\] **Output:** \[\[2,10\],\[3,15\],\[7,12\],\[12,0\],\[15,10\],\[20,8\],\[24,0\]\] **Explanation:** Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. **Example 2:** **Input:** buildings = \[\[0,2,3\],\[2,5,3\]\] **Output:** \[\[0,3\],\[5,0\]\] **Constraints:** * `1 <= buildings.length <= 104` * `0 <= lefti < righti <= 231 - 1` * `1 <= heighti <= 231 - 1` * `buildings` is sorted by `lefti` in non-decreasing order.
null
Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set
Hard
699
706
That they got a big ODI series according to Dibbs Half Birthday Bhi Challenge Photo Only Boys School Design Hai Swakshetri Designer Shuaib Stabilizers Deceased Person Just Different Functions Day The Just Want To Give A New Meaning To The Lord To Remove Subscribe Now To Receive New Updates Reviews &amp; News Angry Bird Heroic Trio Two During Winters Hair White Good Declaring Vector Adams Calling Tax No Money Tractor Function Of Which Class My Map Will Have Two Good Candidates All Over The World And Another And 210 Maximum Co Approve One Plus One Sided Love You Two Minus One is the Giver - 121's is the Giver - 121's is the Giver - 121's decoration and returned to the country Valley of these wide hips and same giving character boys is a particular constructor function and can give the giver Subscribe and you can vote see now like so also these days turn Kansai middle of this year Designer Suite Functions on Financial Benefits You Can Simply Give Access of Kullu Valley Bigg Boss Key Share Will Work Will Be Valid Notes Will Give subscribe And subscribe The Amazing - One Who subscribe And subscribe The Amazing - One Who subscribe And subscribe The Amazing - One Who Does Not Love You All The Various - Love You Does Not Love You All The Various - Love You Does Not Love You All The Various - Love You - 108 Will Return Minus One In K Sidon Tuesday - 108 Will Return Minus One In K Sidon Tuesday - 108 Will Return Minus One In K Sidon Tuesday Statement Inside The Function Will Return - Made Yogurt Well Tips And Return - Made Yogurt Well Tips And Return - Made Yogurt Well Tips And Removing Functions Which Can Just Make Debut Against Minus One Is The Value Of World - One Major Removing And The Value Of World - One Major Removing And The Value Of World - One Major Removing And The Value Of Records Riders Minus One Needs Some Cases After Removing The King Is Address Working So Let's Minute Time Densi It's Working And Yet Working Porn Solution And Widening Deficiencies Tension
Design HashMap
design-hashmap
Design a HashMap without using any built-in hash table libraries. Implement the `MyHashMap` class: * `MyHashMap()` initializes the object with an empty map. * `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`. * `int get(int key)` returns the `value` to which the specified `key` is mapped, or `-1` if this map contains no mapping for the `key`. * `void remove(key)` removes the `key` and its corresponding `value` if the map contains the mapping for the `key`. **Example 1:** **Input** \[ "MyHashMap ", "put ", "put ", "get ", "get ", "put ", "get ", "remove ", "get "\] \[\[\], \[1, 1\], \[2, 2\], \[1\], \[3\], \[2, 1\], \[2\], \[2\], \[2\]\] **Output** \[null, null, null, 1, -1, null, 1, null, -1\] **Explanation** MyHashMap myHashMap = new MyHashMap(); myHashMap.put(1, 1); // The map is now \[\[1,1\]\] myHashMap.put(2, 2); // The map is now \[\[1,1\], \[2,2\]\] myHashMap.get(1); // return 1, The map is now \[\[1,1\], \[2,2\]\] myHashMap.get(3); // return -1 (i.e., not found), The map is now \[\[1,1\], \[2,2\]\] myHashMap.put(2, 1); // The map is now \[\[1,1\], \[2,1\]\] (i.e., update the existing value) myHashMap.get(2); // return 1, The map is now \[\[1,1\], \[2,1\]\] myHashMap.remove(2); // remove the mapping for 2, The map is now \[\[1,1\]\] myHashMap.get(2); // return -1 (i.e., not found), The map is now \[\[1,1\]\] **Constraints:** * `0 <= key, value <= 106` * At most `104` calls will be made to `put`, `get`, and `remove`.
null
null
Easy
null
68
today we're gonna be working on lead code question number 68 text justification so we have been given an array of strings words and a width max width format the text such that each line has exactly max with character and is fully justified left and right you should back your words in a greedy approach that is pack as many words as you can in one each line pad extra spaces where necessary so that each line has exactly max with characters the 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 slot on the left will be assigned more spaces than the slots on the right okay for the last line of text it should be left justified and no extra square so we don't have to justify from with the left and right on the last line so no extra space is inserted between the words a word is defined as a character sequence consisting of non-space characters only each word's non-space characters only each word's non-space characters only each word's length is guaranteed to be greater than zero and there are other requirements so let's see the example here the words are this is an example of text justification maximum width 16. so we as you can see that the spaces are aligned and then it is just justified on the first two lines and not on the third line and in this example we have a lot of word what must be acknowledged man shall be and again we are basically in these examples justifying all the lines except the last one which is left justified only so the way we're gonna be doing it is basically we're gonna be keeping record of the spaces and uh the spacing between them and the extra space we have because we are also given the maximum width so n is the number of words and the result which we're going to be returning is an empty array at the beginning both our i and j are zeros we initialize them as zeros the first thing we wanna do is to iterate the i uh starting from zero to the number of words we have and we wanna make sure that every single time i becomes equal to j because j is going to be is may cover different number of words every time so we don't want to undo it again so what whatever words are being covered by j uh we want to make i equal to that length is at the beginning is going to be -1 and the j is going to iterate from be -1 and the j is going to iterate from be -1 and the j is going to iterate from i and j is going to be equal to less than n we're going to do it until j is less than n the total number of words uh because j is kind of pointing at the number of words and the length plus 1 plus the words of the length is less than equal to the maximum bit so basically we are deciding that we still have enough space to put a new word in here so whichever word we are at and the j is indicating we want to make sure that word length and wherever you are right now in the length that is less than equal to the maximum width then we're going to change the length to we're going to increment the length to the number of words and the length of the word j is pointing to at the beginning the spaces is going to be equal to 1 and the extra is going to be equal to zero yep so first thing we wanna say is if the j is not equal to i plus 1 and the other thing we want to make sure is that the j is not equal to the n the total number of words if that is the case what we are going to do is we are going to say that the spaces is the total allowed limit in that line which is the max width minus the length where we are right now like how many in that line how many have been covered uh once we have the subtraction of that we're gonna be dividing it with j minus one minus uh minus i plus one and the extra is going to be very similar uh because uh this is divided by under the extra is the modulus like basically how many spaces do we have and it's basically a greedy approach and how many extras is left because external is basically saying okay uh how much extra space it's going to be if i put this word in there the row is going to be equal to that words of i so whichever word i is pointing to uh that's gonna be our row so uh what we're gonna be doing here is like we're gonna be iterating k uh to i plus one and the k is less than j and then we're gonna be incrementing k and extras are gonna be get decremented and we're gonna be putting in the row we're gonna be adding the word so we already have the word right now whichever we wanna put in we're gonna uh we're gonna append that with a with an empty space and we're gonna repeat uh whatever calculated spaces and extras we had uh we're gonna repeat that empty space that many times plus the word uh plus the word represented by the k s k is getting incremented so every single time we are putting a space repeating it spaces plus extra if it is either one or zero depending on the value of the extra and we're gonna keep appending it to the row then we're gonna be once we are out of that uh we're gonna be appending this uh one single time whatever extra uh whatever uh extra spaces we have left with and we're gonna be incrementing that and then we're gonna pushing that whole row into the result so we're gonna keep looping through it for the whole i and j and then in the end we're gonna be returning the result looks good let it runner run it yeah and let's check it for all the test cases yep
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
287
hello everyone in this video we will solve the question uh 287 in the lead code that is find the duplicate number so in this it is a medium level question so here we are given an array numbers containing n plus one integers where each integer is between 1 to n inclusive that means we are given spaces of 1 to n plus 1 and we have numbers only from 1 to n so we will be left with the extra space so we will have to repeat the number from 1 to n to fill that place so we have to prove that at least one duplicate number must exist assume that there is only one duplicate number find the duplicate number so we are to assume only that only there is one duplicate number because only we have one extra space so in this area that is one three four two we have two as a duplicate number all other are only occurring single time so in this also three is repeating so you uh we must not modify the array and we must also only use the uh space that is o often and our run time complexity should be less than of n square and there is only one duplicate number an array but it could be repeated more than once so one may be repeated more than once that is if two is occurring two times it may be repeated one day more that is three times so we will see this question step by step i will show you the uh approaches that we will uh if we are asked in the interview this question if we ask then how we need to approach to it so first of all we will start with the brute force approach that is if we are given this array so uh the brute force approach that comes to our mind is using two for loops so that is uh really group that you can understand yourself and uh like tell the answer to the interviewer so he will tell you to optimize this approach so you may see him that in this array if we sort this array this is array so basically we are given one three four two five six seven 2 so 2 is repeating so our output should be 2 so we will sort that first of all then we will iterate over it and check if one element is same to the element at next index so we will check if 2 is equal to the i plus 1 index elemented i index is equal to i plus 1 index and it is a repeating element so as we have sorted the array all the repeating elements will be coming together or uh continuous so as we have sorted there all the duplicate numbers will come together so it will take analog and time to sort the array and of one space or off and space accordingly if you use merge shot or quick sort so that was it for this question so interview will tell to tell you to optimize the time complexity so we uh so for optimizing the time complexity we can use a visited array so basically we have to initialize a visited array of same length so uh plus one so because we are not getting element from zero uh element zero so we are getting elements from only one to n so uh zero index will stay as it is we won't uh like touch this index or uses so we have to initialize a listed array all with all zeros then we will traverse our original array without sorting anything so we will traverse over it and we will check if one so it will go to index one and we will check if at index one the value is zero so it has not been wasted so means we will uh set it to one similarly at uh three we get element three then we will reach to the third index and we will check if it is one no it is not one to zero so we will set it to one and similarly all these will get uh one when we visit them accordingly and then when we have uh like got all the elements so basically they are continuous so nothing is missing between them but only one element is repeating so we have got all now when we visit two so we go to second index so it is one before only so means it is a repeating element it has been listed before only so we can say this is the repeating element so basically here we can we have improved over time complexity but our space complexity has uh decreased like increased so we have we are taking off and space for creating this visited array so the most optimized approach or a really good approach that i would say is using a slow and fast pointer concept that we would have studied in the linked list so basically as you know we have studied this slow and fast monitor in the liquidation to detect a cycle so basically we will form a cycle using this array so i've written the original array here this is array one three four two five six seven two and these are their indices that is zero one two three four and five and six seven so we will this i have created for only for the intuition so we will build this uh like linkless like structure actually so i will show you the approach then so basically i have made this using first we will use visited array then first element is one so we will write one and now to find out which element will be next to one we will go to the first index that is this one so next limit is three so we will write three so one will point to three and similarly third index uh contains value two so third uh three will point to two and second index contains value four so two will point to four and then we will go to fourth index so fourth index contains value five so we will go to fifth index so now we will go to fifth index it contains value six so five point two six now we will go to six index it contains value seven so six will point to seven and seventh index contains value two so which has been visited so it will consider it will make a or like it will end into a cycle so seven points to two so this you can see we have formed a cycle so basically we will use now linked list approach that is using flow and file fast pointer slow pointer as the name suggests it will move only one uh it will only jump once and fast point will jump twice in a single iteration so we will initialize the slow and fast pointer at the first position now i will first of all uh like i will first of all iterate the slow point then the fast motor i will jump first slow then fast so slow will come here and uh fast will uh come from one two three then three to two first will come here now our slow is here so slow will come one position ahead three to two and fast winter was here so it will jump from two to four then four to five first pointer will come at five now our slope winter will come from two to four that is at this point now fast pointer will jump from five to six and six to seven at it jumps up two steps so now our slow pointer will come here that is five now our first point jumps two steps so it will come from two seven to two then two to four it will come here now our slow matter will come to this point that is six so it has came here now fast water will jump from four to five then five to six so basically at this point the both pointers uh collide so basically six is a collision point as pass pointer is moving two times the speed of the slow pointer so it has also covered the twice the distance of slow point so they are bound to like meet in this uh loop so basically if slow pointer is moving one time uh in this the first month will move two times in this so for understanding this uh so first of all i will show you the approach then uh when we have uh found a collision point then we will again initialize so one while loop has ended when they have collided so now we will set the fast pointer to the first index that is one so it has come here now where the both pointers flow pointer is at the collision point only and fast pointer is at the first index so at the starting point now they will move one step one by one so slow pointer will come to the next index that is seven and fast pointer will come from one two three it occurs in same iteration because they are moving one by one uh at same time so now fast matter will come to the next point that is two and the slope and will also jump from seven to two as it forms a loop so ah at this point both again collides now they have traveled equal distance you can see from six to two there was one node in between the slope pointer and the uh starting of the linked list uh starting off the loop so the fast motor also traveled uh one to two and there was only one node so this is equal when we have found this so you can understand this using uh you can refer to the youtube uh for this basically it is called a floyd's algorithm so you can check it how to how it works how it is proof that it will surely work so you can check there are many videos for the explanation i will keep it simple because we are not understanding the linked list approach so actually when these points combine so we will return the slow motor value that is 2 so we have actually found the repeated element so i will show you how we can implement this without using a linked list implementation or converting the array into a linked list so we will basically use this approach that is and we will set the fast is equal first of all fast and slow and both will point to the first index so slow will move by one index that is a of slow array of slope and fast will move to area of fast and fast again so it will jump two times and slow will jump one time you can understand this by like writing on a paper so i will show you the try run of this uh this on this uh array specifically so we have initialized two and fast pointer to the first index that is area of zero and array of zero both are at one and one when you have their value is one and one so now we will move both by uh both in the while loop now when slow will move so array of one now we will use the element as index so array of one is three so it will come out to be three now for the fast it will become array of one and again array of one so area of one is three so it will come out to be 3 and it will go to the third index that has value 2 so ultimately the value will be 2 now again they are not equal so we will keep them running while they are not equal so now slow pointer will again we will use it as an index for the another element that is array of three so it is two now slow point will move so to this index that is array of two it is four so is equal to four they have still not equal so while loop will keep running now we will use this as an index so it is two so array off actually i did something wrong here maybe uh actually when i ran this just a second so it was array of two then we have to run it again so area of two it jumps two samples so array of two is four so it will go to the fourth index that is value it is having value of two so uh fourth index actually and it is having value two so they both have collided so we have found a collision point so you can rewind the video and check how i did that and i did a silly mistake so i uh show you how i showed you how it works and now when we have found a collision point it is actually repeating but uh it won't be in every case that we found this elements as equal so actually we have we will get sometimes a different value so now we will have to do one thing that is we will initialize the fast again to the first point that is fast will be initialized to this uh starting index so it will start running by one sec now fast will uh for this it will run only one step now in second uh loop actually just a second it is here now what's happening we have printed now fast will only run one step and so will also uh run for the one sec so now we will check when they get equal so here slow of uh we will use 2 as an index so its value is array of 2 is 4 so it is equal to 4 and it is value 0 1 and then area of 1 is array 1 is 3 so value is 3 they have one for one they have run for one iteration well it is so you can keep the count of the iterations actually so now we have done this now uh it will again run a of four that is the area fourth index contains value two so it is equal to 2 and array of 3 that is this will be used as index rf 3 also and is value 2. so now they have again collided and this is our point of loop that is this is where our loop occurs or starts this is a repeating element so we will return our value that is will return the slow pointer value or area of slope so basically we have you can see how we have found the repeating element by using linked list method that is using fast and slow pointer you algorithm or method so this was how i showed you the dry run and this was the loop so actually you for the intuition or for the how proof of this algorithm how it works you can refer to youtube video or if you want to me to make the video it will get actually bigger longer video so you can just comment down below now i will show you the code on the lead code platform so i've written the code in cpr space so this is a code actually so this is the code basically just a second what's happening so uh we are given an vector of numbers uh integers okay numbers so we will initialize slow to the number of zero that is first index of first element and fast also through the first element now i have used a two by loop so while it will run till while slow is not equal to fast it will keep running so slow will move by one index one jump or you can say number of slow and fast will move by two jumps that is number of fast so i have to show you the dry run so you can define the video and check out how it works if you have not understood so then we will when we have found a collision point this is where we find the collision point i will recommend that in this loop we will find the collision point and so we will find the clear point in this loop so it is basically now when we have found this so we will uh set the first to initialize first again or faster pointer again to the first index so we have initialized it fast will be initialized the starting point so now four pointers will move by one step each slow will be at the collision point and fast will be to the starting point now slow will move till the fast they are not equal so slow and is equal to numbers of so and fast will also move one uh or it will jump only once that is number of fast so when they will be equal then we have found the uh the repeating element that is we will return slow or we can return fast whatever now i will show you the run running this code so yes it works so let's submit the solution let's see so yeah you can see it has a faster than 97.67 percent of solutions a faster than 97.67 percent of solutions a faster than 97.67 percent of solutions at intakes also less memory again we can try submitting it maybe it increases the time complexity and okay you can see display a space complexity increases improves that is it is using less memory than 71.14 71.14 71.14 of solution and uh this was the code for it and i will provide you the code in the description so if you like this video because i made this uh i invested a lot of time making this video and like studying for it this was a really uh intuitive method i also liked it most if you tell this matter the method in the interview then he will be also impressed because you are using a linkedlist concept into array and you are implementing it without using linked list so that is really a nice solution so i explained you all the three approaches that you can post there may be more approaches but i will only uh try to keep this video concise and accurate for the interview purpose so thank you for watching guys do like this video and subscribe this channel for more videos thank you for watching guys thank you
Find the Duplicate Number
find-the-duplicate-number
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. There is only **one repeated number** in `nums`, return _this repeated number_. You must solve the problem **without** modifying the array `nums` and uses only constant extra space. **Example 1:** **Input:** nums = \[1,3,4,2,2\] **Output:** 2 **Example 2:** **Input:** nums = \[3,1,3,4,2\] **Output:** 3 **Constraints:** * `1 <= n <= 105` * `nums.length == n + 1` * `1 <= nums[i] <= n` * All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times. **Follow up:** * How can we prove that at least one duplicate number must exist in `nums`? * Can you solve the problem in linear runtime complexity?
null
Array,Two Pointers,Binary Search,Bit Manipulation
Medium
41,136,142,268,645
474
hello everyone welcome to my channel code with sunny and today i am going to discuss the problem once and 0's index number is 474 and the problem is of medium type of lead code okay so let's discuss the problem now we have been given an array of binary strings and the two integers m and n and we have to return the size of the largest subset of the array of strings from the array of the strings such that there will be at most m zeros and n ones in the subset okay and here is the subset definition is given okay now frankly speaking when i first read this question it has been like i'm confused at a time why the very frequent question because you can easily see there are at most m zeros and at most and once in the subset uh basically it is talking about the as the total count of ones in the strings that is from all of the strings in my current chosen subset that is the overall count and it is not the count of the only a particular string it is the count of the all of the strings of the entire or in my current subset okay so this is the basic confusing part okay we have to return the size of the largest subset of this string so that this condition holds okay let's now move further to example these are the two examples given i'm going to discuss that also how the answer is coming and what should be the best approach and efficient solution relating related to this problem okay let's look over the constraints now because the very important part of this problem lies over that when we look over the constraints we can have an idea of what type of solution this problem wants from us okay so you can easily see the strings area of strings lengths can vary up to 600 and it is very small amount and m and n goes up to 100 okay so we can have a solution like this length into this m and into this end because the total number of iterations will still uh less than equal to 10 power seven and it is good enough for having the solution to be passed in this problem okay so we can have a solution like o of length into m into n okay we can think like that okay for now let's move further to understand this problem and analyze with the help of the example how we can proceed further in this problem okay so let's move further so here you can see i have taken uh example where a number maximum number of zeros can go up to five and maximum number of ones can go up to three okay so first let's figure out what is happening here so let's uh we have to choose some of the string such that this condition holds let's try to choose this string and let's try to choose this string so if we try to choose three strings then what would be the total number of ones count in the chooser instincts you can see here it comes one and here it comes four and it will come out to be total number of one count is six and total number of zeros count is one and three and two and it's coming out to be six you can see this is not satisfying this condition so it is false we cannot choose this subset of strings and what about choosing the strings like okay choose this string use this string and this one if you are going to choose this string total number of ones count will come out to be three and total number of zeros count will come out to be one plus three four plus one five yes it is satisfying this condition total number one's count is three it is less than equal to 3 and 5 is also less than equal to 5 yes we can choose a 4 number of strings equal to 4 so our maximum number of chosen strings is 4 our answer is 4 in this case ok so can we think of a brute force approach no we cannot we this is going to be like you are going to think like brute force approach in this problem then it will be syn for you why because if you are going to choose one sub choose one string choose any of the two strings choose any of the three strings and the maximum length is going to above up to 600 then it will always obvious that we are having a tla verdict so okay so can we think of a greedy approach that is sort on the basis of number of ones and start picking from number minimum number of ones like that okay let's try to figure out let's try to think with the help of example okay i'm going to take this example okay so let us check it out if this is going to be fine or not okay i have this example and let's try to figure it out if greedy approach is going to work fine in this case or not okay if we are going to sort on the basis of number of zeros let's try to have the minimum number of zeros like this one and i'm going to choose this element let's choose this element then i after choosing this element we have number of ones as one number of zeros is zero yes this is satisfying this condition let's try to pick up the next chosen one that is this one then the number of ones becomes two and number of zeros will be like one can it satisfy this condition no it doesn't satisfy this condition so what is the maximum number of chosen elements this one only one but our answer is two we can choose these two elements so how we are going to identify that what should be the best approach to think for this problem i am sure that and greedy approach will fail here because you are not aware that which elements will choose because the here the parameters are lying like depending on two things number of ones and number of zeros and we are unaware that which strings we are going to choose will minimize the count such that it will be at most m number of zeros and n number of points okay let's try to generalize this case okay so let's think like of approach like dynamic programming so if you are start thinking like the approach of dynamic programming then it will be much easier to understand this problem interpret what is happening here in this problem okay so let's uh find it out what should be the prerequisite to solve this problem efficiently with the help of dynamic programming okay you can see uh we have to here we have we are going to think for the two parameters at most m zeros and at most n ones okay suppose so we have been given a array and we have been given for every let's say we have three elements one element a second element and third element and for every element we have two pairs we have a pair like first element of the pair is going to denote the value and second element of the pair is going to denote the weight basically i am trying to explain the knapsack problem okay of the dynamic programming and second element will be again v2 value comma weight and third problem is again value comma weight so if we have been asked to find out what should be the maximum value we can get by putting these knapsack weights and having at most w weight so it is the standard problem knapsack problem then what we are going to do is just maintaining a dp array we can do a 2d dp array where we can have a maximum of like number of elements that is n plus 1 and maximum number of weight we can get w and w plus 1 okay and we are trying to figure it out what will be the maximum weight so what we are going to do just think like a dynamic programming approach that is for every i from 1 to n we would think like that we are start proceeding j from 1 to w and we will like uh let's try to choose this element that is if you are going to choose this element uh then we will be like if this weight is going to be less than equal to j then only we can choose this element okay if we this weight is going to be less than equal to j then we are going to choose this element then what is the maximum value that we can maximum value of this one dp of i that is choosing this element and with the weight value equal to j would be maximum of this current value plus maximum of if this is not chosen i minus 1 and j minus current weight it should be like that and what about if this j is going to be less than my current weight it would be like just don't choose this element so dp of ij will be like maximum of dp of would be like simply just fill up the my current answer as dp of i minus 1 and it will be like j if j is going to be less than strictly less than my current weight w2 okay just simply like that but here we have not only a single parameter like the knapsack problem in the knapsack problem you can find the only single parameter is capital w we want at most w weights okay but in my actual problem in this problem of the lead code you can find we want x actual m number of zeros and n number of ones here we are going here we are we have to think like dynamic programming with two conditions and what are the conditions we have at most m zeroes and n ones and uh for this we have to uh in spite of maintaining a 2d dpi we must have to maintain a 3d dpi to solve out the problem efficiently okay so let's try to figure it out how we are going to do this okay so for now let us let me erase this stuff over there and let's try to write some pseudo code for this dp relation okay so you can see i will have like just maintain a 3d dp i know to dp of size would be like array of string size that is n plus 1 for convenience i am going to maintain an extra size and for having m plus 1 because indexes are going to be start with 0 i would be like at most maintaining at most m 0 so would like maintain m plus 1 size and n plus 1 once i do like 3d dp and for every i am going to check i from 1 to n we are going to just check if i am going to choose this element or that is we are going to check two conditions if i am going to choose this element or if i am not going to choose this element ok when i'm going to choose this element so okay let me write for in simple case i start from j from 1 to m and from k from 1 to n that is for every i am going to check if this j is going to satisfy the condition or if this gain is going to satisfy condition so i have basically nested loops three nested loops and i am going to check for current value of i j and k if i'm going to check first firstly i'm going to count the number of ones and number of zeros in my current ith string okay so if i have already counted it would be like what should be my current answer that is current answer of like dp of i j and k it would basically signify what is the maximum number of items maximum number of length of subset we can choose by having the ayat by not using this if string and with j as the number of maximum number of zeros and k as the maximum number of one it would if i am not going to choose this one how i might this would be my this dpf i j k would be assigned as dp of i minus 1 and j and k simply okay and what if i am going to choose this element let us choose this current string okay so if i am going to choose this current string it basically signifies if after choosing this string it would satisfy that is m should be greater than or equal to 0 and should be greater than equal to 0 okay so it means that my current j should be like greater than okay should be like greater than or equal to the number of it is simply if i am going to write it for m number of zeros my j should be greater than equal to number of zeros and what should be my k and note that i need to maintain the and condition and k should be greater than equal to number of ones then only i can choose this string okay otherwise we cannot choose this if i'm going to able to do this then my answer would be like dp of i j and k would be maximum of this value and dp of if i am going to choose this string my answer would be like dp of i minus 1 and j minus zeros and again k minus ones because i have already chosen these stuffs that is choosing these amount of ones and chosen these amount of zeros okay so k minus number of ones so this is my basic dp and what should be our answer finally should be maximum value of entire 3d dp which anyone anything can be our answer so i need to take the maximum also okay so let's head over to the code and find out how we can implement this in a better way okay so basically this problem is the variation of knapsack problem standard knapsack problem of the dynamic programming okay so let's head over to the code okay so you can see i have okay so let us code it out as fast as possible so let me write our length as uh okay so i need to write len as okay so i am not convenient with length let me take as ested should be a hdrs dot size and let me maintain a dp array would be like a dp 3d dp would be like s j plus one and again i need to have like m plus one i need to have like n plus one okay and let's fill with uh default value meme set and it would be like uh okay so okay in spite of doing that let us iterate and fill it up i can use the meme set also but i don't i'm not convenient with this okay so j is less than okay it's j less than equal to m and j plus and also k 0 and k less than equal to n and k plus this dp of i and dp of j and dp of k is going to be zero okay you can have also use the mean set size of dp terms like but the time but it would also take this execution time okay so let's try to fill up the dp 3d dp okay so i need to i treat from int i equals one i less than equal to s j and i plus i need to comment it down here fill up the 3d dp table okay so how we are going to do that so it is simple just to let's count the number of ones and zeros first number of ones will be count of str s of i minus 1 dot begin and stress of i minus 1 dot end and it will be like 1 and what should be the number of zeros it would like it would be like htrs of i minus 1 dot length minus number of ones present in it okay let's try to fill up for every i for every j less than equal to m and for every k less than equal to n okay and i need to have like nested loop over here okay so k should we start from 1 because n and m are greater than equal to 1 and i need to increment k every time okay what if i doesn't choose and doesn't choose the current string so if i'm doesn't choosing the current string would my answer would be like dp of i j and k would be like dp of i minus 1 and j and k and what if okay so check if we can choose the current string or not so i am going to just check it out if my current string can be chosen or not so if j should be greater than equal to once and okay so j should be greater than equal to zeros i think this should because j is for m and uh k should be greater than equal to once then dp of i need to take the maximum basically i j and k should be like maximum of dp of i j and k and just to remove considering this element should be like a dp of i minus 1 and j minus number of ones and also k minus number of zeros i think i have already done a mistake over here i should have to write j minus number of zeros okay so yes this is fine but i need to take the maximum always answer equals max of answer and dp of i j and k and i need to return the answer finally so let's return the answer but still i haven't defined my answer by default so i need to write answer as zero okay yes it is good run time is 124 ms faster than it solutions okay so if you have any doubts do not forget to mention in the comment section of the video and i will ask the viewers to like this video share this video and do subscribe to our youtube channel for latest updates thank you for watching this video
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
6
hello all welcome to another video solution by code runner in this video we will be looking at the zigzag conversion problem on lead code and this video will provide you with the c plus solution of this problem i have also made a video for the python solution of this problem and if you are more comfortable with python then you can go ahead and find that video linked in the description box also i request you to please subscribe to my channel to get the latest updates about exciting problems and their solution so without wasting any time let's proceed to this problem in this problem we are given a string s which can consist of just uppercased and lowercase letters comma and full stops we are supposed to represent this string in a zigzag format in a matrix and then print that matrix row wise with the input string s we are also have an input of the number of rows this matrix should have for example consider the string paypal is hiring let the number of rows are equal to three we start with the first letter of the string s which is p and store it in the first row and first column of the matrix then we shift to the second row and store the second character of the input string which is a after this we shift to the next and the final row and store the letter y in the first column of the third row as the number of rows are three now we start moving upwards shift one column right and store the next letter which is p in the second row we continue the same steps over and over again until the entire string has been accommodated in the matrix this if you look closely leads us to a zigzag pattern as an output of the function we are supposed to do the following once the matrix has been made we have to start iterating over it from the top row and print the values in the list of list or matrix row y's that is the first four letters in the output would be p a n and h now we move to the next row and store the letters in the second row finally we move to the last and the final row and print the values in this row i hope by now the problem is clear to you even if it is not clear just hang in there i'll be explaining that in the code part with an example too now let's head over to the c plus solution and see how we are going to solve this problem throughout the code explanation part i'll be considering the input sample paypal is hiring first we just checked the base conditions if the number of rows were 1 that is the input string s was supposed to be projected into one row as shown in the comment we can directly return the original string itself similarly we can do the same if the number of rows were greater than or equal to the number of letters in the input string this is also shown in the comment here and i hope this is clear to you now we will move ahead and start storing the characters in the input string in a matrix form we define a variable delta which will keep track of the direction we are moving in row wise that is either we move down or we'll move up we denote plus one as moving down in the matrix and minus one is moving up then we declare a row variable which will store the row number we are currently at and where the current character is to append it finally we declare a vector which has the number of row equal to num rows after all the variable declaration we start with our iteration over the characters in the input string s initially the value of row is zero so we append the first character which is p in the first row of the matrix as shown in the diagram now we apply a check over the row number we are currently at this is done to change the direction we are moving row wise if we are currently at the bottom most row we have to switch the direction and start moving upwards if we are at the uppermost row we have to switch the direction again and now start moving downwards this is what this check of the if statement will do for us if the row number was zero or the last row we switch the direction here understand that the value in the variable delta can either be minus one or plus one if the value is plus one that is we were moving down we increment the real numbers by one in the other case that is if the value of delta was minus 1 we decrease the row number by 1 and move upwards once we are out of the for loop and done with our scan over the input string we will get the vectors or list of lists as shown in this figure now we simply iterate over this vector and collect the characters one by one to get the final output that is it great job and we are done with the solution let's try to run it and see if it works or not and there you go the solution has been accepted i hope you liked the solution if you did then please hit the like button and press the bell icon to stay updated about the latest problems and their solution on lead code bye for now happy coding and i'll see you next time with another exciting problem and it's solution
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
54
another day another problem so let's Solve IT hello guys I hope you are all doing well in this video we're gonna solve the spiral Matrix problem before we get started hit that subscribe button if you haven't already and without further adoles so let's get started imagine that you have a matrix a grid of numbers and they ask us to visit all the numbers inside the Matrix in a special order the order should be right down left up so to solve this problem we're going to use a technique called spiral order traversal and the spiral traversol is a method of following all the elements in The Matrix and a clockwise Pearl starting from the top left corner so first we're gonna visit the top row from left to right then visit the right Mouse column from the top to the bottom and visit the bottom row from right to left then finally visit the leftmost column from the bottom to the top and so on and it's all you have visited all the numbers inside the Matrix so here is how we're gonna travel The Matrix first we calculate how many rows and columns we have inside the Matrix and we're gonna have a are left and right the left and right variable marks the leftmost and right most column and we're gonna initialize another two variables the top and the bottoms the top and bottoms marks the topmost and bottom most rows and we initialize an empty array that's going to be the output and where we're gonna store the numbers then we start at the waiting to draw all the numbers inside the Matrix so the first iteration Gonna Be by visiting all the numbers in the first row means the top starting from the leftmost corner to the last number inside the first row so we're gonna start at one visit two three and four then we're gonna move the top to the second row because we are done with the first row and now we start another iteration from the top last column to the bottom means we're gonna visit a 12 and 16. and we're gonna eliminate the last columns mean we're gonna move the right to the previous columns then we check if the top and bottom have not yet crossed if not push it to the array all the numbers in the last bottoms means the last row starting from the right to the left after all the numbers being pushed to the result array will eliminate the last row by moving the bottom to the previous row then we check if the left and right have not meet each other we visit the left most column from bottom to the top and we move the left to be pointing to the second column and we start another iteration checking if the left knot passing the right and the top not passing the bottom so we visit the second row from left to right mean we visit six and seven and push them to the array result then move to the top to the next row then we visit the right Mouse column from top to bottom which have only one number 11 and we push it to the array result and we move the right to the previous column then we check if the top pass the bottom if not we visit the last number inside the Matrix which is 10. and finally we move the left to the next column to pass the right so we can return the result and stop the iteration that's it guys I hope you have understand how to solve this problem so let's jump with code in the solution so the first thing we're going to do is to calculate how many and arrows and columns we have inside the Matrix then we initialize four variables to keep track of the elements inside the Matrix so the left is going to be zero and the right gonna be the last columns inside the Matrix then the top gonna be zero and the bottom gonna be the last row inside the Matrix then we set a loop that continues until all the elements inside the Matrix have been visited the loop is controlled by two conditions if the left is less or equal to the right and top is less or equal to the bottom which ensure we will visit all the elements inside the Matrix and stop once we finish and return the result so the first two for Loops gonna push at each iteration of the outer loop all the numbers that are from left to right and all the numbers from the current right most column from the top to bottom and the two other conditions gonna push all the numbers that are at the current at the bottom from the right to left and all the numbers that are at leftmost columns from bottom to the top and we'll finally return the result array which contain all the elements in The Matrix visited in the special order so the time complexity of this problem is often where n is the number of elements inside the Matrix because we've visited each element in the Matrix exactly once and the space complexity is also off and because we store all the elements in The Matrix an unless before returning it thanks for watching see you in the next video
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
139
welcome to this video in this video we will solve this coding interview problem word break in this problem you are given word of dictionary and a string you have to check whether you can construct the string from the word of dictionary we can use one word multiple times to construct the string in this string we see we have two word lead and code lit and code exist in the dictionary so we see that we can construct this string from the dictionary so for this given input you have to written true for example if you are given dictionary equals to pin and apple and a string apple pin apple we see that we can construct this string from these dictionaries we have apple pen apple we will use the word apple twice we are allowed to use one word multiple times and we have this word pen so we can construct the string from this dictionaries so for this input we have to written true now how to solve this problem in order to solve this volume we're going to use dynamic programming let's see how to solve this problem using dynamic programming first let's create a dynamic programming table the length of the dynamic programming table is the length of the given string plus one this is our dynamic programming table in this string we have total eight letter so the length of the dynamic programming table is eight plus one that is nine at the first position we will insert true what does this mean it means that a certain word ended here we may assume the empty word has ended at this position if we have here true and false fault it means that at this position a word has ended with valid ordering okay we have empty strings in this word lit so we can have another word right after this position so we don't have to worry about whatever we have on the left when we find out here true let's see how it works so at the first position we have true it means a word ended here just remember it a word ended here so we can have a new word from the next position now we're going to construct a set data structure to accept the dictionaries now we're going to construct a set data structure to access the dictionary words in constant time let's create a set data structure let's assume this is your city data structure here you have two word lit and code now we're going to iterate over this string from the first letter all the way to the end first we have l now we're going to generate all possible words that end with l that is this word l we see this word does not exist in our set if the word does not exist we'll insert false let's move to the next now let's generate all possible words that end with e l e and e we see none of them is exist in the set so let's insert here false let's move forward let's generate all the word that end with e that is l e and e you see none of them exist in the set so let's insert here false let's move forward we see our first word is l e t this word exists in our set now what i'm going to do we're going to find out the previous word the ending position of previous word we see this word can start from this position and right before this position we see this index 0. here we have true it means that a word has ended here so it's a valid ordering of this word lit so this word can start at this position one so this word we can pledge right here now we find out this word exist in the set if the word exists in the set we will check the ending position of previous word that is true so exist and here you two so true entries two will insert your true since we find out this word exists and this word in a valid order so we'll skip we'll move to the next iteration including c let's generate all possible word lead c e t c and c we see none of them exist in that set so let's move to the next and here let's insert false since none of them exist now oh including o now if we generate all the words that end with o we'll see none of them exist in the set so we'll insert your faults sim goes for this now for this we will have this word lead code this one does not exist in the set this word does not exist this word exists in the set since this word exists we will find out the ending position of a previous word that is this position here we have true and this word exists so we'll insert it true we are done we have the answer at the very last cell in our dynamic programming table that is true it means that we can construct this string from the given dictionary words this is called dynamic programming this is how we can solve this problem the solution will takes big of n square time complexity since we are generating all possible words and it will takes bigger than space complexity for this dynamic programming table now let's take another example for better understanding let's assume we're given this input first let's construct a set data structure let's assume this is our set data structure in this state data structure we'll have two words pin in apple so pen and apple now let's create a dynamic programming table the length of the dynamic programming table the link in the stream plus one the length of string is one two three four five six seven eight nine ten eleven twelve thirteen so let's create a dynamic programming table right here at the first position we inserted two it means that a word has ended here we may assume that an empty word ended here now let's generate all possible words that end with a that is a it does not exist in our set so let's insert here false then p let's generate all possible words that end with p ap and p none of them exist in the set so let's insert your faults then this p so a p and p none of them exist in the set so let's insert here false then l let's generate all possible words appl ppl pll you see none of them exist in the set so let's insert here false let's move here now we see we have the word apple we see apple exist in our set so let's find out the ending position of previous word that is this position here we have two it means that on the left we have valid ordering we don't have to care whatever value we have on the left since we find out here 2 this is the ending position of the previous word since here we have 2 we don't care whatever we have here we may have on the left a lot of words we don't care so here we have 2 and it adjust in our set so we'll insert it true and we'll skip we'll move to the next iteration so here so if we generate all the words that end with p we will see none of them exist in the set this one does not exist this word does not exist in this word does not exist this word and this word you see none of them exist in our set so we'll insert your faults now for e a p l e p e if we generate all possible word that into it e will see none of them exist in the set so we'll insert here false now for this word we see this what does not exist this word does not exist in the set this word does not exist now we see this what does exist in the set since this word exists in the set we'll find out the ending position of its previous word is this position here we see that we have two it means that we have valid ordering on the left we don't care how many words or which one here we have on the left we just hit this position since this is the ending position and from here we can start inserting a new word that is pin so it's true and this exists so two and two is true we'll insert your true now let's move to the next if we generate all possible words that end with a we will see none of the image exist in the set so we'll insert your faults same goes for this now for this if we generate the word apple pineapple apple pen apple you see this word does not exist in our set this word does not exist when you move to this word we see this word exist in our set since this word exists we'll find out the ending position of previous order that is true so we will insert true we are done since we find out at the last position true so we can construct this string from the given words so we'll written true this is the solution for this problem we've understood how to solve this problem now let's code up this problem let's create a function word break this function takes two parameter dictionary and a string s now first we're going to find out the length of the given string so n equals to is dot length now we're gonna construct a set data structure to store the dictionary words to access in constant time so set new hash set now we're going to run it follow for word in dictionary dict will add all the word to the set so set dot add the word now here i'm going to create a dynamic programming table difficult to new bull the type is boolean in plus one we're using one extra spot to denote the ending position of empty string so let's insert at first index true now let's run a follow for i from one two in now we have to understand substring method here for this string lead code if we say sub str zero one then what it reader it will return just l why it will just return l because it will start at the start index and it will end up at the ending index minus one that is zero so zero and zero start at zero into 0 so it's written l if we say sub str 0 3 you know what it will return from 0 to 3 minus 1 that is 2 so 0 1 2 it will written lit we've understood sub str method now let's run in a loop for j from 0 to i minus 1 now we're going to find out the substring sub equals to h dot sub str from i to from j to i here it will generate all possible substring including the height letter as the last letter or as the ending letter now here we're going to check if the previous word of this substring has ended at a valid position and we can access that using dvg and if the substring contains in the set dot contains the substring so sub if it's true then we'll set if it's two then we'll set dp i to true and we'll just break since you find it true so we'll break now at the end we will return the answer from the last position this is the algorithm this algorithm will takes big o of n square time complexity and big of in space complexity hope you've understood this problem word break thanks for watching this video
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
232
Hello everyone welcome to my channel Okay let's see first let's see further asked the company why to implement Microsoft Amazon Google okay why to implement using stack okay let's see as if I take it if pushed then I take it Why is the behavior like this, if you push the van, then the van comes here, then if you push, you will come after the van, there is a kind of queue, like how there is a queue at the ticket counter, why is that? A kind of peak is done, which means which banda came first, its value is van, neither is the value of the pick, look, I have put van, I have popped it, so the one who came first will be a sin, so it is gone, okay, so look pop. If the van is not there then it is false, we have sent the proof, okay then what will be the answer, see who is on top right now, you are here, the van is there, if you are there now, then the answer should have come, in that case, it is okay. It is simple and I have to make K, what do I do, I always solve such questions like this, see, I first check whether I have to make, I write on the side that whatever input is given, no pop, it is ok, don't think this. In the operation, we will design the strike accordingly, so let's take the main why is it ours, okay, then it's okay, if you push, then here 1 A is going to pick him up, so pop it, so do n't you think A is falling because There is still an element in K, okay, I write this in the original behavior side, I always try to implement it later, how to make it from a stack, okay, so now let's see how to do it using a stack and by the way, from a stack. It won't happen, right? It can behave like a stack, so we will take two stacks, okay, let's see from which track, how can we replicate this behavior from the start, okay, so what should I have said, okay? So let's put the input, okay, here the input will be reduced like input, whatever input is being pushed, we will keep putting it in it and whatever I will do as output, anyone will have to give me output, how will you think. See, the simplest way is what will come in your mind that what you are pushing is okay, after that the peak means which is the first element, then remember that the limit of KP should be WAN, otherwise we will need WAN from here, so let's know WAN. You will have to go down to the bottom for this, otherwise what will you do for that, if you pick it up here and give it to the team, then you will come here, then this van is left, if you bring the van here, then it will be mine, then it will be empty, ok, after that, you can send the POM and output. The one at the top of the stock will be my peak, okay, so I have removed P = 1, till now it is okay, so I have removed P = 1, till now it is okay, so I have removed P = 1, till now it is clear, okay, after that we will have to put it back, right, this is also clear, okay, that's it. What's next, I removed it from here and copied it, okay now look, let's do one less, like I take it now in the future, again he asked me to pop it, okay, so let's leave it in the output, right now. We will pop it from the direct output only, why again when we did the pop operation, when we had just popped the van, we will not put you in it again, we will not put it again, we will take it again, we will let it pop, so we will pop it again. Again, we will pop it from here only and let it remain in the output, okay, so whenever we were asked to pop it, what did we do? Sir, we picked it up from the input and put it all in the output, okay and then popped it from the output, okay, output. Let's leave the elements in the same place, okay, so now you will say that I take the next push, A is okay, I take the man, what will happen is the flower here, after you, five A is gone, okay, push is being done, that means the input is A. So the input has come, so what did I say? Always put the first one in the strike. Okay, what did we do in Pushp? Didn't push 5? Okay, and now I asked, peak kiss, what is its grain, you should have come, then see when. Whenever we have to give some output, first of all we will check the output. Every time, if the output is not empty, then send the answer from there. Okay, so see, when you asked me this, it was according to your answer. You should have come and we are going to have sex, so what did I say? First we will check the output, is the output empty or not? If the output is empty, then we will send the top of the output, right? And we will send put dot top, that will be my answer. Look, its answer is true. Isn't that correct, okay, it is clear till now let's assume that I have said something in it, okay, by the way, I have asked, if the input is A, then the input will always be added in it, okay, sorry, I asked here, I gave a comment here. Okay, here comment, I gave a comment here. Okay, here also only teams are given, okay, it is doing the right thing in both of them, okay, now you agree with me, okay, first of all, check if the output one is empty, if it is not empty, then what can I say quietly, which is the pick? The output is dot top, that is, you will be okay, you will be popped, okay, no, the output is not empty, friends, quietly top the output one, that is, you will pop more, so what, you will be popped, see here. Right, this has been popped, we are going absolutely correct till now, okay, now I take that many, told me to pop, now told me to pop, okay, so now see what should be the pop according to you, it should be five pops but here But look at our five, the output is empty. If the output is empty, okay, if the output is empty, then what I said is that first we will group the stack input into the output, then 7 A will go here, Van A will go here and five A will go here, right by removing it from here. Okay, after that, if we top the top one in the output, then what will we do output dot com, what sin will happen, five will pop, you see, we are going absolutely right, what I told you is that I am not going to remove the output. Right, I will not put the output back into the input. Okay, this is clear. After this, look here, pay attention to the man. After that, I asked for a pick. Okay, so pick means according to you, a pick should be made. If you want to make a pick, then see here also our output is not empty, so we will get the answer from the output itself. The output is my pick, my output is dot top, neither is the peak, what has happened to me, it has become van. You see, it is going absolutely correct, I am fine. If it means that if you look at it, then just pay attention that your input is strike. Okay, whenever any input comes, keep putting it in the input. Okay, and whenever you have to get something out, like pop man low or peak. If it has to be done, then what should you do in that case, you take it out from the output. Okay, if the output is empty, then if the output is consumed, then you cannot do anything. Input will have to be put in the output. So every time we will check that if the output is empty, then the input. Make the output and then find out the answer. Okay, now you are paying attention to one thing. Now, I can do all the operations with direct output and I will do them in the oven. Remember when the output was empty. At that time, I was not able to put the input into the output, then I was feeling off, but now look, my output is full, right, we will directly get the answer from here, we are of the pop of P, what will it look like then? If the van is working fine then you are seeing that sometimes it seems to be off but most of the time it seems to be off. When we have filled the output then you know this is called amortized most of the time the oven is sometimes off. This is fine for the interview, so do not take this question lightly, it is a very important thing. You see, sometimes it is like oven, but most of the time it is like oven, as if you have just forgotten the pick, so I will tell you directly in oven. I will give you the top right now, I will tell you in direct open, I just told you pop, I will do it in direct open, it was so simple, it became simple but it was more important to you than that, it was very important for you to know how the oven is, it is okay. This is what is asked in the interview, okay, one more thing, now one good thing, tell me what can you do, remember, here if I take the input, it would be something like this It is from me, so look at this, I take this pick, then the output is asked. So is it empty or is the output empty, this is the input, I have given you group here, I have given 1 group here, after that I told directly, then it was off N in the first time, after that again asked ok, now I will tell you in off van, tell me again. I will give it okay, so it is okay, but look at one more thing, no friend, the first element that will come in the input is fine, the first element that will come in the input is okay, I am okay, I will keep it in the group, so see what will happen in it. I tell him what will happen in the case, see, this was my input, this is a very good option, I do n't know, he has not told this thing, okay then come on, okay, you have done it, wait, it is empty right now, the van is pushing, okay so. Look, the input is empty, if the input is eaten then it means that it is sure that this band is the first element. So if it is the first element then it is the element of PK. I write this and store it in the van. Even if the input is clear, then right now we are not there, meaning. If you are not the first element, then I will not update the P element. If I will not update it, then you gave it to me, then if three comes, then three will also be seen. Well, this input stack is also not empty, which means the peak element must have already been created. Isn't this the peak element, we will not update three A, then four will also appear the same, I am the first element otherwise I cannot be pikarment, now if anyone asks you about the peak element, will you tell me directly, you need to do van also. You will not need to do what you remember, you have to put it once, here and there will be no need to do that, nor at the time of pickup, when you have to go out in the pickup, now what will you say directly that if good, if my output is my output every time. I have to check, brother, whatever happens, if output.in is at the top, my pig will be correct, meaning the output is not empty, then I have to close my eyes and get the answer from the output because obviously I will get the answer from there in the oven, but If the output is empty and someone asks me the peak element, okay then what will I do, I will send the return peak element. Okay, this thing is cleared, what has saved me from this, so I will not have to move it even once. I will store it off. Every time, before doing any operation, I will first check the output stack that if it is empty then only I have to do something, ok, the output is correct, then I can exit all the answers in the off van, all the answers are clear till here. And you will also know that both will be empty, then that means we do not have any elements. Okay, then none of ours is empty, neither is the stack empty and we will only have elements. Then okay, so the solution to empty is very simple. Is the function done, is it empty, then you can check it like this, okay guys, second, what did I say about how to pop every time, what will you check first, brother, it is okay to check the output stack, if the elements are there, they are simply in the over van. If it is not going to go then brother, it is necessary to move the element from input to output. Oh pen will be used, okay, later on, overfin van will be installed, then later, okay, this is your pop, okay, it is very simple, the input is A. So brother, put two groups in the input and this is off van, this is my simple thing and yes, if there is any first element which will be the first element pushed, then I will store it in a variable named PK element. I will do it, Pushkar, now we have seen it, so if it is shown, we asked and saw, then you saw it, did not see it, and now let's check the pick, right? What did I tell you about the pick, that if the output is empty every time, then first check if the output is empty. If not then brother, what will be the answer output dot top, first of all I must have kept the group, okay, if it doesn't come to my mind, then I do the same thing again, put outer from input, then it will be off and then take it out from there, okay, so that is from a van. I have saved you, are you okay, so we have done all the emptying, so see what story is there right now, I will just convert the story in the court, now when I go and code it is okay and I have told you the most important thing. Rakhi told the question, it was already ready, let's do coding like this, just nothing, the story comes, it is a very simple question, okay, now let's do one less, what did I say, I will take dostack, one for input, one for output. Stack of these will be an input type right and one which I will take, now mines van team is giving it, later the variable that will come will be given, the value will come. Okay, Mike is doing the initialization, let's leave it, we have to fill the empty. So the peak was very simple that if in put dot m t is ok and end output.in is given to If there is an element of K, then I will update the element of P, here this will be my less and you have to push the bar outside in the input, this has to be done every time, okay, till now it is clear, now let's come to pop, okay see. Pay attention to what I said, every time I will check the output, if the person gives me that answer, then it is a very good thing. Okay, so what I said, if the output is out, if the output is empty, then brother input. Output will have to be put. Put the input in the output. Then what will it look like? It will look like off and on and keep on sinning the input. We are going to remove the input from the input and put it in the output. Till this point it will be filled in. After that what I said is the output is correct. My answer will come out, right? What do I write, what will happen is that my answer will be dot top the output and return bell that I have popped it, okay and let's take man, if my output is not blank, okay then I will come out from direct output. I am looking at the value here, then what will happen in this case, it will be off van, then the maximum time will be off van because once you fill the output, this call will not happen, then there is a maximum time, that is why I wrote. I am saying again and again that it is important for the interview, so what did I say in the peak, brother, if F output.in, make it simple, what did I say, for the peak, I removed the brain that sends from input to output. I thought of it and put it in a variable that if the output is empty then there will be no need to put it from the input to the output. I will take it out from the peak element itself. I am updating it in the speaker but it is okay if the output is empty. If it doesn't happen then it's ok output. If my sorry is not empty, if it is not empty then I am sending the top of the output. Simple ok, let's run it and see. I hope if it gets run then we have made some mistake. Let's say great by submitting it. Let's see Great C Have Salt This Question and You Be One This is an easy question but it is very important and according to me it is not easy, okay this is a lot to learn, I call the question easy from which one can learn a lot. No, okay, I call that useful, okay, easy, medium, hard, go to hell, we mean to learn the maximum, okay, so we saw a new thing here, the story of the ammotize people is okay, thank you.
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes element x to the back of the queue. * `int pop()` Removes the element from the front of the queue and returns it. * `int peek()` Returns the element at the front of the queue. * `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. **Example 1:** **Input** \[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 1, 1, false\] **Explanation** MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: \[1\] myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is \[2\] myQueue.empty(); // return false **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. * All the calls to `pop` and `peek` are valid. **Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
null
Stack,Design,Queue
Easy
225
48
hi everyone today we are going to sort of three to go to the question rotate image so you are given a m by m2d matrix and representing image rotate the image by 90 degrees clockwise so you have to rotate the image in place which means you have to modify the input 2D Matrix directly do not allocate another 2D Matrix and do the rotation let's see the example so you are given one two three four five six seven eight nine and we have to rotate this image like a clockwise like this and like this so in the end output should be like a seven four one eight five two nine six three in this case yeah um very simple question and uh looks like everyone tried to solve this question so we should do the solve discussion and uh I think there are many ways to solve this question and uh yeah I actually I came up with a few Solutions but I'll show you like a um again I think I believe the easiest way um to solve this question okay so let me explain with this example one two three four five six seven eight nine and uh we try to rotate this image and 90 degrees clockwise so first of all imagine um you have line here and then swap the number in the same column so that means uh one and seven and the two and eight and three and nine we swap the numbers so in that case um the image like seven eight nine and therefore 5 6 and the one two three right after that um okay uh the Rhoda so imagine the diagonal line like this from like a top uh top left to like a bottom right like this diagonal line and then swap eight and four and the one and the nine and the two and six so after adapt image should be like a seven four and one and then this 8 should go to this so 8 5 and then these six we go to this position so and then 2 will go to this position so two and nine is here and then six and the three and actually this is a answer the time value um so let's check so initial image is this one and the rotate it 90 degrees clockwise is like this so if we rotate the 1 to 90 degree clockwise um yeah uh this one should go to here right and the one and uh two should we go to here and a two and a three so you go to here and three and uh four should go to here and therefore and the five doesn't move right and there's six should go to here and the six and there's seven should go to here and seven and eight should go to here yeah eight and then nine goes to this position and here yeah um looks good so yeah um okay I think there is a like a pattern moving pattern so you can I think you can manage uh like a one by one but I think uh this um lines make Pro make question easier I think yeah um that is our basic idea to solve this question so with that being said let's get into the code okay so let's go first of all um Edge length equal ranks of Matrix and the first of all SWAP the number um like between top numbers and the bottom number um so top equals zero and the bottom equal H length oops Rings minus one and uh start ripping while top is less than bottom so in the case for column in lens H length so first of all uh draw a center line and then sub the numbers so first of all um keep the top by a Top Line a top row value to a temporable so many tricks and top and the column after that um update this position to um same Quran but bottom right and then after that update this position and to always temporary variable right so I think we successfully swap the numbers after that um update top plus equal one and the bottom minus equal one so after that um draw a line like a diagonally and then swap the numbers and uh yeah it's how to uh put a name for variables so let's say I equals zero and uh um why I is less than H length oops and uh 4J in lens and start from I plus 1 to X ranks oops so y plus 1 so um suppose so position e should be zero and zero one zero two and uh this is one zero one two and uh two right and then now we draw a line like a zero one two right and swap the number uh zero one and the one zero two zero and the one two one right so that's why uh we have to uh iterate through like a zero one only zero one zero two one two right um so if when I is zero um I mean I should be actually low position here and this is a i position and uh column version so when I is 0 so we iterate this row and we don't have to check zero so we so that's why we start from zero one so that's why we need plus one another one zero two and then when I is a one in that case we don't have to check one zero one how we start we can start from like a one two in this case so that's why this portion is one two and when I is 1 we start from negative 2 for J so one plus one is two right and then um when we when I is 2 so J should start from like a here but this is out of one so maybe uh this Loop not executed so then finish looping so that's why we need to like a plus one um yeah if you don't understand my extra explanation so please let me know in the comments below so in that case uh actually we do the same thing like a temp equal Matrix and uh pi and J and then update this position to um actually uh we uh sub I and J I right let's say 0 1 and stop the index number like a one zero and uh for Delta uh we have to solve this number so zero two to zero so that's why we swap that like i j h j i yeah and uh up to date j i to Temporary variable yeah I think that we can stop uh this number with these three lines and then after that um other plus one to I plus equal one yeah um after that just return Matrix yeah uh let me submit it yeah looks good and very efficient algorithm so time complexity of this solution should be a full um like a swapping like a top and the bottom um numbers algorithm so that should be like an order of column multiply low d by 2 half length of row and a plus and for like a swapping the number like a diagonally so that should be like an order of a low multiply column d by 2. uh roughly I think that this time complexity so yeah a little bit complicated but I think a roughly uh this time complexity for this algorithm and the space complexity is um actually we don't use extra data structure just update the input Matrix so if we don't count this Matrix I think one space complexity yeah so let me summarize step-by-step yeah so let me summarize step-by-step yeah so let me summarize step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm of rotate image step one imagine you have a horizontal line at the center of the image solve the numbers between top and the bottom step two imagine you have a diagonal line from top left to bottom right sub the numbers between the diagonal numbers yeah that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Rotate 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
856
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have not liked the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever i post a new video so without any further ado let's get started problem is score of parentheses let's see what the problem is we are given a balanced parenthesis string we need to return the score of that string the score of a balanced parenthesis string is based on the following rule this has a score one meaning one opening bracket and one closing bracket has score one a b has score a plus b where a and b are balanced parentheses strings for example here let's say we have something like this and this so this is also balanced single bracket has score one so this one will have score one this will have score one so this is a and this is b so a b has score what a plus b where a and b are balanced parentheses strings so this a is also balanced b is also balanced so score for a b will be a plus b that is a score was 1 and b score was 1 so 2 will be score of this and this thing like this has score 2 multiplied by a where a is the balanced parenthesis string for example let's say we have something like this so this is balanced this will be your a so something like this is there right this is a balanced parenthesis string a and outer brackets are there so for this single a this is single opening closing so score will be one so 1 so this will be 2 into a score so 2 into a is what 1 so 2 will be score of this fine so these are the conditions which are given ah so see for this will be one for this we discussed it will be two and for this test case we discussed it will be again two so i hope you understood the problem uh let's see how we can approach this problem so see basically what we need to do is see whenever we are getting opening bracketed it means that uh we are going into we are have we when we are open we have a opening bracket right there could be two cases either there could be again opening bracket here something like this could be there or if we have opening bracket there could be a closing bracket something like this so there could be two cases so when we are getting an opening bracket we will have to do something and when we are getting a closing bracket then we will have to do something for example lets take this part so let's do one thing first let's discuss what will be the output for this string so for this what will be the output here first of all this single bracket is one and this inner one is also one now because of this outer it is something like this right one so it will be 2 into 1 2 that means meaning this whole from here till from here let me change the color that is from here till here this part will have score 2 so now this 1 and 2 these are like this right a and b so it will be 1 plus 2 3 so this in the inner part has what score three and then these are their outer brackets these so this is again something like a is balanced so this is a balance string right inside 1 so what will be the score of this 2 into a that is 2 into a is what 3 so the output for this will be 6 fine now let's discuss how we can get 6. some idea you might be getting that what we can do is so this is a string right so see basically what we have to do see opening just means that there is there could be different cases that either there could be nested brackets like something like this there could be nested brackets or there could be a closing bracket just after the opening bracket these two cases could be there when there is closing bracket then we need to calculate the score depending on what was inside here so let's say here it was something like this so when we are closing this will depend what was inside here so we need to store somehow this core which was inside this here between these outer brackets what was the score in of the internal brackets if there are any if see if it is like this so then there is 0 here no internal bracket score then for this only one will be there score but if there is something like this and we are calculating for this bracket then there will be some internal score of this that is one plus one two so it will be something like this so when we are at here at closing bracket we need to take into account this score so it will be 2 multiplied by 2 4. fine so let's do one thing let's dry run using the code and side by side you will better understand uh we will try and so that you better understand the approach uh let me just erase this so just uh follow the dryer and try to understand what basically we are doing in this problem after this we will be discussing uh another approach which is optimized then this approach so see what we are doing is we are taking a stack you will understand why we are taking a stack the reason for using a stack is because let's say we are calculating for this outer bracket so stack will be storing the result of the inner brackets that is the score of inner brackets that for that we have to have a stack to show the previous values fine so let's discuss uh this approach so we have what we are doing is we are starting we have taken a variable score initially as zero so let me take a variable score and i have taken initially it as 0 then we are iterating in this string if the string element is an opening bracket so here initially we'll start from here so we get an opening bracket what we will do we will push the score in the stack so score zero will be pushed in the stack this zero indicates that there is right now no uh internal you can say internal brackets right now no internal brackets for example here there is this internal bracket now between these outer brackets for as of now there is no internal bracket and then else so first again we will go here again this is an opening bracket so stack score will be pushed score will become zero here fine now we'll go here now it is a closing bracket so it will go in else so score will get updated what will score become score will be equal to see now here this is a closing bracket and there is no internal brackets here no internal brackets between this and this so what we will do we will this 0 represents the score of the internal brackets here so since there are no internal brackets your score is 0 we will take the score 0 plus max of so see guys if there is internal any score let's say here there was score 2 so this outer this whole thing score will be what 2 multiplied by this internal score a so max 2 into score or it could be if there is no internal brackets like here there were no internal brackets this was only there so for this what will be the score so for an opening closing this is one so one either it could be two multiplied by score comma max so whatever maximum value between these two that we will take here score is zero so this will be zero plus max of two into zero will be zero comma 1 so this will be 0 plus 1 that is this bracket score is just 1 which is correct and opening closing bracket score is 1 so as of now we are doing correctly fine now let's move forward and we will pop from the stack so now this is not the internal bracket score this we will pop now let's move forward so here now we will go here now there is opening bracket and score is updated right score is updated to one because score here is one now um so let me raise this fine now this is opening bracket right opening bracket so we will push the score to stack so one will be pushed fine one will be pushed which is the score of this and score will we will make it 0 because the new bracket has started so score we will make a 0 now we'll go ahead opening again so when again is opening we will push this score in the stack and we will update score to be zero so now score is zero fine now we'll go here closing bracket so 0 plus max 2 into score is what 0 comma 1 same thing so 1 will be there one is the score of this thing fine so we will pop this zero from the stack and now we'll go here so now here closing bracket is there fine so uh what we will do again stack top that is one plus two um multiplied by here max sorry max will be there 2 multiplied by score is what 1 comma 1 so here why we have taken 1 here stack top is 1 max of 2 comma 1 so this will be max of 2 comma 1 will 2 plus 1 3 so this here it will come out to be 3 what is this 3 this thing oh sorry not this thing fine so this is coming out to be 3 which is this thing 2 for this one for this two plus one three now again we are at the last closing bracket so what will be the score will be stack top find stack talk so that is stacked up stack top is uh this will be popped in this step so stack pop top will be 0 plus max of 2 comma 2 multiplied by score is what 4 is uh here 3 comma 1 so here it will come out to be 6 fine so what we are doing basically is whenever we get a opening bracket we push the current score in the stack and we initialize the score again and else when we are getting closing bracket we find out the this will be the if there is any inner bracket and this will be for that current bracket so the current bracket whatever it is i hope you understood this approach time complexity for this approach is o of n uh and space is also of n because we are using a stack fine uh this is the same code which we have discussed here so i hope you understood this approach now the second approach is constant space and it is to be honest like i thought that approach to be more intuitive than this approach so uh let's discuss that approach also let me run this approach first so if we submit this is getting accepted and let me let's discuss the second approach uh what it could be so see the test case which we are taking is this one fine so here guys see what could be there uh over here like when we are at this inner bracket when we are here at this inner bracket whatever will be the depth outs what will be the depth inside till here from the outer bracket from like from here to the innermost see innermost bracket let me take another example so let's say we have something like this one two three four five so see this is the innermost bracket so for this one will be there score and how many times 2 will be multiplied 2 is multiplied by the inner score right a so this will be a so let's say if this a um is how many times basically we will multiply this 2 so for this c for this 2 into 1 then for this 2 into 1 but this it will be 2 into this thing 2 into 1 fine and for the end one it will be 2 into this thing 2 into 1 fine that means how many times this 2 will be multiplied it will be multiplied 2 raised to the power 4 times 1 2 3 4 and what is 4 here 4 is the depth of the innermost bracket see 1 two three and four depth is there that means what is depth here what i am saying is depth meaning number of opening brackets one two three four this we will not include this one we will not include because this is one the rest which are outside this one two three four that is the depth so 2 raised to the power 4 will be the score of this whole thing so my uh motive of explaining this is because what we will be doing is we will be calculating the depth and based on that we will be calculating the score so i hope you understood this um this thing let's discuss let's dry run so that you can better understand because see guys the basically we can understand these problems only if we dry it fine if we are not dry running and we are just thinking in mind then that way it can be clear but according to me you should dry run so just a second let me what is the code so see what is here we are doing what we are doing is we are having initially depth we have taken a variable depth as zero and dress is the score which we will return at the end fine previous we are taking because see this innermost bracket if we are at the closing bracket how we will know this is the innermost bracket just think how we will know that this is the innermost bracket because we will know it when if we are at closing the previous bracket is opening then this will be the innermost bracket for example if this we have to check here we are at the closing but previous was another closing so this means that this is not the innermost bracket this is the innermost bracket fine so uh what we will do where s is equal to 0 previous we are taking so that we can check if this is the innermost bracket or not for innermost bracket uh this when we are at the closing bracket the previous one will be the opening bracket then that will be the innermost then bracket are going to each uh here just let me raise this we are going to each uh element in the string so this is zero first of all we are here so here this is opening so we are we have got one opening we will increase the depth because we are going one bracket inside right we are going one bracket inside so we are increasing the depth then again we get opening bracket depth increase fine now we are getting a closing bracket so this is a closing bracket so we are getting a l we will go in else here we will do depth minus because if we if you remember here when there was the earlier case which we saw in that all the opening brackets were 5 depth was four right depth was four because we were not taking the innermost brackets opening bracket that we were not considering so that's why if opening because this depth depends on the opening bracket now so if opening is five depth will be four so that's why we're decreasing depth one uh and if you did not under understood this part just go to that part and watch again so depth we are decreasing by one and if previous is opening bracket so here previous is opening bracket every time we will update the previous right here previous is the opening bracket meaning this was the innermost bracket so just calculate the 2 raised to part of the depth so rest will be 0 plus 2 raised to power depth will increase agreement here by 1 so depth will become 1 2 raise to 4 1 this is 2 so it will be 2 then we'll go ahead we get opening bracket depth will increase by one then again we get a opening bracket depth will increase by one then we get a closing bracket first decrease the depth minus and then find the check previous if previous was equal to opening or not here see whenever we go to this brackets now we will be updating previous i forgot to update it but when we will go to the next one so we are storing the previous the character in the previous right so here when we are at the closing previous is opening right this one so meaning this is the innermost bracket so calculate the rest so this will be 2 plus 2 was the previous value plus 2 raised to per the depth which is 2 so this will be 2 plus 4 6 fine now we'll go here closing bracket depth will decrease by 1 but here previous will now be closing bracket this correct this one fine so here uh we got a closing bracket that could be decreased by one but here previous was not opening so we will not do this thing we'll go ahead and closing we will update now this is also closing depth we will decrease zero but previous it was not opening its closing only this is closing only so we will not update res and we will come out of the loop and rest will be six so this is approach but you might be having some confusion then that how this is giving us the correct answer see this depth thing too i think you might have understood uh the doubt where you might be getting that how we are adding these this result and this result right so see whatever will be inside this will get multiplied right so whatever this is let me draw here i hope this you are clear how we are getting this part using this thing let's say this is b and this is a so and this here we have to multiply by whatever this is we have to multiply that with 2 right so 2 into whatever the c but what is this c is a plus b so we can write it as 2 multiplied by a plus 2 multiplied by b that what we are doing here that is what we are doing here so just dryer and once uh you will understand basically here what we did first for this and this two multiplied by this one to multiply this two multiplied by a was what a is what this one two multiplied by one plus here what we did 2 multiplied by what was b what was this was 2 only b is what 2 so this is what we are doing actually here we are expanding this because it's the same thing right if we calculate this first or we separate it like 2 into a 2 into v i hope this video was helpful time complexity for this is o of n and space complexity is over 1 video is quite bit lengthy but i hope you understood the concept and if you found the video helpful please like it subscribe to my channel and i'll see in the next video
Score of Parentheses
consecutive-numbers-sum
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced parentheses string. **Example 1:** **Input:** s = "() " **Output:** 1 **Example 2:** **Input:** s = "(()) " **Output:** 2 **Example 3:** **Input:** s = "()() " **Output:** 2 **Constraints:** * `2 <= s.length <= 50` * `s` consists of only `'('` and `')'`. * `s` is a balanced parentheses string.
null
Math,Enumeration
Hard
null
1,845
hey there welcome to pomodora Joe for Monday November 6th 2023 today we're looking at lead code problem 1845 seat reservation manager this is a medium problem design a system that manages the reservation state of N seats that are numbered from 1 to n implement the seat manager class and it has three different functions or methods we have seat manager which takes an integer n this will initialize the seat manager okay then there's int Reserve so this returns an integer and it fetches the smallest numbered unreserved seat it reserves it and then returns its number so we find the smallest numbered unreserved seat and return it all right and then void meaning it doesn't return anything unreserved int seat number so this function or method takes a seat number it doesn't return anything but it just UNR reserves the seat okay so this is actually pretty straightforward let's put 25 minutes on the palor timer and we'll get started so let's see in our init this is where we need to allocate some storage to store all of our seat numbers that are going to be reserved and unreserved now this tells us that we need to return the smallest unreserved seat anytime somebody reserves a seat so we could store everything in a list and then just search through our list looking for the smallest number that's not yet reserved and then return that but the fact that we're always returning the smallest numbered seat every time it makes me think of a different data structure it makes me think of a heap now a heap is a data structure that does just that it will return the minimum value that's stored within the Heap anytime you pop a value out of the Heap so it's very similar to a list but it has certain properties in fact in Python it actually uses a list as its storage so with a heap you basically have two functions you have a push and a pop similar to a stack now you push a value Val into the Heap and it stores that value internally you don't really need to care about how it stores it but it stores it internally and the other method is pop and you can pop a number out of the Heap now there are different types of heaps there are Min heaps and Max heaps and python by default it's going to be a Min Heap which means that when you pop a value out of the Heap out of the heap's storage it's always going to return the minimum value that's stored in the Heap so that's perfect for this problem we want to store a bunch of values the seat numbers and anytime we reserve a seat we want to get the lowest valued number so we'll pop something out of our Heap we'll pop that lowest value seat out of our Heap and return that now there's a bunch of things about this problem that aren't really covered like well what if there are no more seats that we can reserve or what if they're trying to unreserve a seat that wasn't actually reserved so there's all these edge cases that aren't really being covered here but since it's not being covered in the problem statement we can ignore those for now if you get this problem in an interview those are the exact kind of questions you'll want to ask you'll want to say well what happens if they try to reserve a seat that's already reserved or what happens if somebody unreserved a seat that's not reserved yet what happens if they try to reserve a seat but we don't have any seats left these are all questions that we don't have answers to all right so let's go on with the problem here so internally we have to have some storage for our Heap so I'm just going to have a heap and we'll make it a list now in Python this is a list now in other languages they'll probably have other libraries for heaps so you'll have to look up your specific language to find out more about heaps and since this Heap will be a property of our instance of this manager this seat manager we'll have to say self. Heap all right so self. Heap is going to be an empty list now actually I think I'm going to pre-populate our Heap with all of the pre-populate our Heap with all of the pre-populate our Heap with all of the different seats so this will be a list of all of our available seats all right so this will be a range and this will go from one to n but we have to do n + one from one to n but we have to do n + one from one to n but we have to do n + one because range is non-inclusive it does because range is non-inclusive it does because range is non-inclusive it does not include this last value so range from 1 to n plus one so now our Heap is already pre-populated with all of our already pre-populated with all of our already pre-populated with all of our numbers now in order for this to work as a heap we actually need to call a function heapify so right now this list is just going to be all the numbers in order from 1 up through n + 1 in order from 1 up through n + 1 in order from 1 up through n + 1 in ascending order now in a heap it's not actually going to store that in ascending order because it needs to be able to find these things very quickly so it's actually going to rearrange these to be more like a binary tree a binary search tree now I don't actually have to worry about how it does it I just need to know that I have to heapify this before I can use it as a heap so let's do this we'll say Heap Q so that's the Heap library in Python so Heap Q we will heapify our Heap so self. Heap Okay so we've pre-populated our Heap Okay so we've pre-populated our Heap Okay so we've pre-populated our Heap with all of the available seats that's all the seats from one to n and then we've heapify our Heap so it's ready to be used now when we reserve something all we have to do is pop our value out of the Heap so we could just return Heap Q dot Heap pop and then we have to pass in the Heap that we're popping from so we're going to pass in self. Heap all right so we're going to use the Heap Q Library we're going to do Heap pop on our Heap that's going to return the smallest value in our Heap and we'll return that's exactly what we need to do for our Reserve all right let's see I'm going to give a little space here now unreserve well if we're unreserved seat all we have to do is put it back in our pool of unreserved seats and that's our Heap so in that case we have to do a heap push so Heap q. Heap push and then we pass in the Heap and the value so self. Heap and the value will be the seat number all right and I think we're done so we have our three methods here we have the init where we initialize our heat with all of our available seats we have our Reserve where we pop out the smallest valued seat number and then we have our unreserved where we push that value back into that Heap all right let's run this see how we do range is not valid uh let's see oh right so this is actually storing the range itself in my list which is not what I want I actually need to go through all the values in the range so I have to make a list so that's this square bracket let me just redo this whole thing all right so I actually need to get all the values out of this range and put them in my list so I have the square bracket creating a list I can't just store this range directly because that's actually storing the range as the value in my array so I need to take all the elements out of this so I have to say for every X in this range so I want X for X in range all right so what this is going to do is for every X in the range from 1 to n plus one so that's for every number in that range it's going to put that number X inside this list all right let's give that a shot all right seems to work let's see if we can pass all the tests and we pass Let's see we do not great 27% for runtime 67% for memory so great 27% for runtime 67% for memory so great 27% for runtime 67% for memory so it's not great it's not terrible but it's not great let's see if we can fix this up a little bit well one thing we're doing is we're pre-populating this we're doing is we're pre-populating this we're doing is we're pre-populating this Heap with all of our unreserved seats and we're heapify it maybe we don't need to do that just yet maybe we can keep track of what's the next value for our lowest numbered seat and then we can just return our next lowest valued seat if we don't have any seats available in our Heap so that means that we'll start out with nothing in our Heap we'll just know what the lowest value seat number is which will be one if we're reserving a seat we'll Reserve seat number one if we reserve another seat we'll Reserve seat number two and then when we unreserve a seat then we'll put that into our Heap now that we have a heap so previously we had no numbers in our Heap now that we do have a heap well that's going to be the lowest number so we'll actually be going through and reserving our seats and only when we have unreserved seats or seats that were reserved and become unreserved will we have a heap and then in that case if we have some numbers in our Heap they're guaranteed to be lower than our next available seat that we're keeping track of outside of our Heap so let's do this so we still have our Heap but in this case I don't need to put anything in it's just an empty list and I don't need to heapify an empty Heap so I don't need this but I do need to keep track of my next available seat so I'll have self. next seat and we'll set this equal to one because that's our first available seat now when we reserve it's a little bit different we can't just pop something out of the heat we'll have to check first do we have anything in the heat so if self. Heap well then we can pop something out of the Heap otherwise if we don't actually have a heap yet then our next available seat will be self. next seat now I kind of want to return this so I could do like return but I actually need to advance my next seat I have to go to next seat plus one so if I return this then I've lost that ability so I kind of want to do something like next seat plus equals 1 so we advance to the next seat and then return self. next seat but if I do this that means we're going to start at seat number two so I actually have to go back up here and change this to zero okay now this seems to work we've got our empty Heap to start with we have our next seat initialized to zero if we reserve a seat there's nothing in the Heap yet so we advance to the next seat which is going to be 0 + 1 so this is which is going to be 0 + 1 so this is which is going to be 0 + 1 so this is seat number one and we return seat number one that's exactly what we want if we go to the next seat we'll return seat number two number three until we unreserve a seat if we unreserve let's say seat number one it'll be in our Heap then when we come back up here and we call this Reserve well now we actually have something in the Heap so we'll just grab that value out of the Heap and we'll keep returning values out of the Heap until it's empty and then we can go back to returning our next seat values all right let's try this okay it works let's see if it's any faster significantly faster now we're at a 96% for runtime and a 98% for memory a 96% for runtime and a 98% for memory a 96% for runtime and a 98% for memory so that is awesome all right I'm very happy with this solution so with that I think I'll leave it here okay so this has been a fun one this has been the seat manager problem leap code 1845 seat reservation manager I like these kinds of problems okay well I hope you enjoyed this hope you had fun hope you learned something hope you can go out and write better code
Seat Reservation Manager
largest-submatrix-with-rearrangements
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. Implement the `SeatManager` class: * `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. * `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number. * `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`. **Example 1:** **Input** \[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\] \[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\] **Output** \[null, 1, 2, null, 2, 3, 4, 5, null\] **Explanation** SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats. seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1. seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2. seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\]. seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2. seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3. seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4. seatManager.reserve(); // The only available seat is seat 5, so return 5. seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\]. **Constraints:** * `1 <= n <= 105` * `1 <= seatNumber <= n` * For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat. * For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved. * At most `105` calls **in total** will be made to `reserve` and `unreserve`.
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
Array,Greedy,Sorting,Matrix
Medium
695
232
okay leeco 232 implement a queue using stacks so in this problem all we're going to be doing is we're going to be using two stacks in order to implement a first and first out data structure that's known as a q right so basically how a cue looks if you're not familiar with it is you have some data so let's say we have like one two three four and basically if we have a front and then we have a back right so the front is going to represent the thing they got put in first and the back is going to represent the thing they got put in last and basically whenever we peek or we pop or do whatever we're going to be performing it on the front of the queue this is opposite to what a stack is because if you remember a stack essentially takes things in let's say our order is one two three well since one went in first it's going to come out last because we can only pop or peak at the top so if let's say we want to get the order of this now remember it came in as one two three but it's going to come out as three two and one right and this is basically understanding this is basically how you implement this solution it's basically just understanding that okay well if this goes in this order we know that one went in first but this reversed it how do we reverse it back well the answer is just add another q to the mix right so this is s1 let's say we say that we want to take all of this we want to put it in s2 so we keep popping so we pop in the top three two one so now with the ones at the top as it should be for a q and now whenever we peak we can peek at this stack and see what one's the front that's true cool and if we want to pop we just pop from this right and that's all we really have to do now obviously we don't want to do this for every single operation of a queue because remember the queue has four different operations in this question we can push we can pop we can peak and we can just check if it's empty so we don't want to be doing this movement of data between two stacks for every single operation in reality the only times we want to be doing this is when we either pop or we peak because that's really when the ordering of our elements matters a lot but during those intermediary steps like we were pushing or we're just checking if something's empty we really don't care what order our elements are in right because like if i'm pushing i'm not using the data for anything at the current moment right i'm just pushing and saying hey i might need this later but when i do call pop or peak that's when i should be moving to the second stack so let's like run through an example for example let's say i want to like push one i want to push two i want to push three right and we'll call this s1 and then i'm done pushing i just don't now want to say how about i wanna how about i peak like i wanna know what's at the front of my queue so now i do care about the ordering so what i do is i have s2 all right and now i start popping so i do this three two one cool right but now let's say i want to push again i push let's say a four so i push it here it's the only element in s1 but now that i pushed i don't really care about copying it over to here yet right that's not really what i care about because remember i pushed 4 but a q only cares about what's at the front really right it cares about that type of ordering so regardless since i push the 4 right the force here but the front right our pop and peak are only ever going to really care about the front element but the front element still remains a 1 right regardless of what's here because we've already created this so that's pretty much all there is to it right popping works the same like if we push here this is going to be in the back of the queue regardless so one being in front still matters but let's say we do pop the one so let's say we throw one out of here right so this is gonna be up there so two is going to be let's say we pop the two gets thrown away let's say you pop the three so the three gets popped now though s2 is empty right so that's going to be a very critical thing checking if stack 2 is empty or not is going to be very important for us so basically now that s2 is empty though now we might have to do this again for a wee peak right if we want to peak i should copy over this over to here now and say okay cool well now four is at the front so this is how the logic works it's kind of tricky it's confusing um it's kind of hard to draw out because you're dancing between these two stacks but let's just type out the code so i'm going to add a little private field here private and let's have like two stacks of integers we'll call it s1 stack of integers s2 and s1 is going to be our stack that just holds things temporarily and s2 is going to be the stack from which we peak and pop from right so we don't really have to do anything here um pushing okay like we said earlier we're only pushing on to s1 if i kept the drawing we're only ever pushing here so if in this case if i wanted to push a five i'll just push it here i wouldn't immediately push it there's no need so we'll just say s1 dot push all right and i'll just push x so we'll do that cool let's do our other one let's do the peak first right so let's say we just want a peak so how does that work well the first thing that we mentioned is we want to check that s2 is empty right because if it's empty we're going to have to do this movement of elements over so we're going to say if um s2 dot empty if i can spell today uh empty so if s2 is empty we're going to do that movement of elements we're going to say if s2 is empty so while s1 isn't empty we're going to take everything from s1 and put it into s2 so we'll do s2 dot push s1 dot top and then of course we should be popping from s1 as we go i believe there we go cool but what if s2 isn't empty right if s2 isn't empty that means the thing that we care about being in the front is still maintaining that property right so we can just return basically we just say that let's say into result is going to be equal to s2 dot top right and then we'll just return the result immediately and then notice that we're peaking so we're not we don't have to pop we're just looking at the top let's do the pop code as well so it's very similar right we check again if s2 is empty right that means we're going to be copying everything from s1 over to get that ordering that we want the first stand for style ordering so we do it while s1 is not empty we're going to basically push everything from s1 so that's one dot top cool then we do s1 dot pop awesome that's what we want now for this okay so what we want is we're going to do it's result is going to be equal to s2 dot top sorry so just like our previous problem so we do this so we store the result of the top but then since this is a pop operation we should pop from that stack as well so we do s2 dot pop cool and then we return the results so that's done right pretty easy so far this is really the trickiest part actually the pop and peak um are the trickiest but that's all that we really need and then let's check if it's empty right the empty check is really easy right because if um s dot empty so if s is empty uh or do we call it we call that s1 sorry so if s1 is empty all right all we're going to do is we're going to say okay well there's nothing that we've recently pushed so let's return s2 dot mt so let's just check if s2 is empty right because s1 could be empty but s2 could not be empty right because we could have something that we have in this picture let's say we didn't have this 5 let's say this 5 didn't exist here right this is technically empty right there's nothing in here but there's a 4 in s2 so we need to return that check like if that's the thing right because it could be that they're both empty right but in some cases that's not true otherwise just in case we'll return false right because if s1 isn't empty then s2 definitely shouldn't be empty because eventually at some point in time we're going to be popping things out of s1 and putting them into s2 um that's pretty much it i don't think there's anything else to really say i think the only kind of optimization we can do is we can actually do this since peak returns an integer we can actually delete some of this code maybe and just say the result is going to be equal to whatever we peak right so we peak i'm going to return this and then we're going to pop and return the results see if that works let's run the code awesome that runs let's run the code submit cool there we go 100 faster of course just fluctuates um but yeah um runtime's really weird for this so i think it's the challenge for this one that they want you to do is yeah amortize oh one time complexity so it basically means that like as you perform more and more operations over time the time complexity as time goes on is going to kind of like you can think of it as averaging out to being constant time complexity right and the reason for that is like remember we had this whole example with these things getting popped right and pushed onto here remember we're not doing this every single time right we're only doing we're only copying all the data from here to here if s2 itself is empty right but let's say like we run through this a couple times and let's say we're like okay well let's say we pushed three two and one here right so these are things on q on s2 i don't know why this s4 so s2 so this is here i can keep pushing like four five six seven right i can keep doing this as much as i want right and if i'm just peaking if i'm not popping these things right if i'm only peaking i'm only ever doing it as own one time because i don't need to copy these yet like there's no point right we don't have to do that we only care about the front we only care about what's in the on the top of this s2 stack so this is why kind of over time becomes an of one thing now obviously eventually and at some points in time we might have a condition where obviously we pop everything out of s2 that we can and we then we finally have to push things in here right so it becomes seven six five four but the idea is over time it averages out to like an of one type deal so uh yeah that's pretty much it i hope that this helped it's a little bit of a tricky problem but uh yeah thank you
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes element x to the back of the queue. * `int pop()` Removes the element from the front of the queue and returns it. * `int peek()` Returns the element at the front of the queue. * `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. **Example 1:** **Input** \[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 1, 1, false\] **Explanation** MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: \[1\] myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is \[2\] myQueue.empty(); // return false **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. * All the calls to `pop` and `peek` are valid. **Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
null
Stack,Design,Queue
Easy
225
342
um lead God question uh question lead code 342 power of four we just did the power of three so it's pretty much the same thing um literally so let's get into it uh given an integer n return true if it is a power of four otherwise return false an integer N is a power of 4 if they are X if there exists an integer X such that n equals to x to the power of X so literally you're just returning true if the number given it's a power of um it's a power of four okay and it's the same thing that we did previously let's remove this um so basically we're gonna check if it's not if it's zero or if it's equal to negative one then we're going to return first and then uh the mistake that you are more compelling to do is to return this one here at the beginning uh so that will not get evaluated here at the beginning let's say maybe if it gets to this point when you're getting out of the loop it might be equals to one and then you don't have anything to check that so it's going to fail right it's going to give you the wrong answer so you have to evaluate uh n equals to 1 right here at the return statement or at the end after the while loop it's up to you but um while n uh modulus 4 equals to zero so basically if it's divisible by four uh we're gonna keep dividing it until it's no longer and then at that point we're gonna get out of the loop and then we're gonna check this statement and then if it's true we're gonna return true and then if it's first we're gonna return first and pretty much that's it I will see you guys in the next video please don't forget to subscribe bye
Power of Four
power-of-four
Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_. An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`. **Example 1:** **Input:** n = 16 **Output:** true **Example 2:** **Input:** n = 5 **Output:** false **Example 3:** **Input:** n = 1 **Output:** true **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
231,326
269
happened to Ajay that yesterday in the cricket channel today's video, it's so let's signal on the printer of the one who looted the gender dictionary, Ghaghra has a string of some words, first a string of if string, are you not trading for some alien language when that language According to this Software Development Withdrawal in English, we want to write Software Difficult, we will write something like ABC, some ADC will come after ABC, why do teams match, BMD mismatch is ok and duty is great but this will come later, site can bring it without saying anything, why first. If we go after the mixture then what kind of English comes to our mind, if we use simple English, then this chapter comes out of its cotton and it has been given in a different language, by keeping it in a different language, we indulge in the language, who knows what? It is said that if it started Amazing that in that given alien language, tell me the lexicographical road from the letters to them, like today cake, if I have written this to you, then this is the English Alphabet Recording Mr. Asif Products and Characteristics of its Letters and You will see the medicines that as many as they are used, that is the same meaning, if this used oil is not used, then who knows what is there in it, that is, when the government comes to you and runs something, then as many as are given to them, AB serial is given here. The answer is wrong that for English, here 1 lakh Scorpio brother, how can this be done in short term, tell a lexicographical order of all the letters here, true sexual, if we make all these words the latest, then it will also be seen that it is sorted. And on the back side, dictionary border is basically like this and Sukh soap is not very common but first let me tell you something about dictionary and Muslim that you must know, there is a lot of confusion if we talk about Kunwar dictionary English dictionary. So if you look at the English dictionary, it is like I have written hello, it is for A Ajay and after that I am writing I am for four times, hey, I have written like this guy below is the one who comes later in the lexicographical order, why share? Such something place value when please arrangement happens in some English world but something is printed but you will see that the character is available at the greater place value. Now if it is a mismatch then the dictionary defines it as snatched and in the very beginning. A great place where the back came superhit because greater ne chak so this word comes later iron and time, you write anything after this basically doesn't matter dictionary order viagra of two worlds if you want to be different then how will you define it The first mismatch letter divides the ones after that, you don't even know how to see them. There is a width in it, which will come later than lifetime and hello will come first, that the reliability of seeing these four and the dictionary and up cannot even define between these four. Yes, if I just say hello to you and if it's your time, you can remove the relation of only one channel, remove the rest, then why not go ahead and decide who will come to SP first. Do you have any information about China? No baby, so if you have two words, life is two but collective graphical order is only there, then from it you can extract the relation of only two characters, those two characters will meet, like for example of this match character, I complete it with lip. Baby and Four Times Actor and here it is AC and Four Times again, the guy below will not come later, why is this match happening, then these two will decide, if these two come out of this mismatch, then these two are better than the depositors even with a good plan. It does not matter due to which this AC double would have been the head because the mixture is there, both of them will give points. Now if the seat in the voting list comes later in both of these, then such double is going to come later, so from this friends world also you can only get Banarasi Geography. Can you tell the cord, can you do something big during this tour, what ca n't you do, friend, that if the Shudra caste is a giver to you, the day is only theirs, only their first match is the tractor's prince, you know, if there is nothing else other than that, then his Ca n't say anything about the latter, may be one and a half before, may be later, but if the lips were laughing and very sir and yes, this is till Vivo, still there may be some request, ok, only between the world, only Prithvi Shaw of mismatch character has a mother who may not know anything but now if we look here then here we are using this software already given a Brahmic characters to extract the shot after shot, first I will write all the practice but that Brother, with which characters, why sir, I spent a day here thinking about all the characters given here, who knows, somewhere in that alien language, show wi-fi somewhere in that alien language, show wi-fi somewhere in that alien language, show wi-fi 20f, I said clearly, the heat is intense, oh yes, then you are this. WTA City Good Constipated Chapter It WIT You Placed First So It Comes First On WRS In Dictionary Word And In Traffic Border For Serial Language W Comes Before RTI Filed 337 RSW Will Keep Coming First So Are We All These Tilak Ambedkar will go and compare from Word, Mrs. Headache and Teacher Company in WRS, if you Pimple or Pimple TRS match then because W has given before coming RTMnu, then it will go before Tip K, entry will be made for it, time will then work wi- Even if you try to do fi, time will then work wi- Even if you try to do fi, time will then work wi- Even if you try to do fi, then hello viewers, mismatch will come only after Tubelight, okay, we will compare wi-fi with C daughter, okay, we will compare wi-fi with C daughter, okay, we will compare wi-fi with C daughter, freedom to IT with IIT, then daddy will be literature, can this domineering woman be with everyone with need? There is no need to be afraid of those who shift by sharing, there is no need to check MS Word basically onion, all the things in it like how DM is done, then if a person has kept his wi-fi in W and if a person has kept his wi-fi in W and if a person has kept his wi-fi in W and before that, then you will see its form like this. Have you removed your WRS code before the test, then it has been removed automatically, if your bedroom RTO code is set to W before the alarm, if your bedroom RTO code is set to MW before the alarm, then the WRS code is set to W before sharing and so on. Before tear and done automatically do a little anything if you these two feet recording lexicographical and of your baby latest I used w and before tr own youtube simple that in w and team dictionary is coming before by Android Before the root of it comes before the interview with the doctor, that current has become side 100, you do not need to check all these trees, to make the latest, there is a lot of dengue in it, basically friends only affair, just check and on that basis. Decide the order of conference letters, only then what will I do in black sea, I will test my Wi-Fi WRS of the black sea, I will test my Wi-Fi WRS of the black sea, I will test my Wi-Fi WRS of the computer, so what will I do before I start making a graph in which Raghu is appointed first to the team if android porn Wi-fi in India porn Wi-fi in India porn Wi-fi in India will come before W in Tubelight 10, why West can only tell about this match in India, ask about it later in July, let's see, if W came before this, then W did it before its own day Pizza last wta this people and first one strip years ago if you went it here before which i double t&amp;t is ttn which i double t&amp;t is ttn which i double t&amp;t is ttn and frustrated then what reduces w or tv show's t r t claimed it's an angry now its plz Plz plz click on subscribe words, I have converted it to tap, user, if you don't know, subscribe, by subscribing to this, something can happen that I have some words of my own, this also happens with laddus etc., this is the own, this also happens with laddus etc., this is the own, this also happens with laddus etc., this is the difference for you. You will find out that this person has made your Wi-Fi tip difference for you. You will find out that this person has made your Wi-Fi tip difference for you. You will find out that this person has made your Wi-Fi tip submit, then if he is not trying to seduce the prince of any world, then you will keep rough dad anywhere among such women, he needs an answer, if an age effect W850 is taken out. Or if you keep it, then you don't know the operations about the set for a decade. You can't even know about the coding root of the words given, why are you afraid, this order is being decided by clearance here, this order is being decided by W &amp; D. As for Dainik Bhaskar, W &amp; D. As for Dainik Bhaskar, W &amp; D. As for Dainik Bhaskar, I don't do anything. You did n't know anything about anyone else. If you don't do anything then you will definitely subscribe. If you keep it right then you will be able to fit in everywhere. This episode contains letters and these [ __ ] keep it up. If you letters and these [ __ ] keep it up. If you letters and these [ __ ] keep it up. If you are the dictionary of the world and not any person, if you will understand this prince of my plates, if you will understand all this, then you will not order it because it is 102 Jhal Hua Tha A Suite, this movie, this is now we do not do anything, looking at it, its I will tell you once it is done, then open the app, first of all you will know the solution of Electric Shadow Totke very well, only then you will be able to understand the advice, if you are not using Tubelight then you will not be able to understand it by sitting at a console, I will try. First watch this video, the result of taking the tip of Kansal Pratham Big Achievement 225 logically is that the heads are going to fall that the engine is made in Agra and the one is India type and the tractor with indri grease will not work, this is this. All map option is a specific time of the character of the registered tractor, so if the internet people will use it in its network without any pet, then I just keep the character, so it is important to remember to save duplication. Okay, so don't edit that in front. Keep that you are not option don't laugh that assumed that I need for denser continuity ca n't make patience why character hate not indicator of the park are subscription we were a joint versus India was indicate bluetooth new indri as many boards as a certificate Give zero that then put this soap oil strainer state from word then take out character from it then from source can reach from start to learn and to that is Ajay which Sonmati means then 10:00 Kalia which Sonmati means then 10:00 Kalia which Sonmati means then 10:00 Kalia took all the character from some string their That in removing the solid and fitting the accused indexes zero, give lectures in degree less when the customer will be made at this time, so indiae.in that indiae.in that indiae.in that indicates, its company servi is now done, so now turn on me and subscribe, then in the subscribe, all the universities in the united states. Unlike births skin should celebrate start and precise group who is modern world dot length - once in more equal to zero start length - equal to zero start length - equal to zero start length - subscribe to that personal whatsapp on play school function internet committee mixed clinton then put in And its leaves make snacks tractors so hence send next allotment to next allotment to next allotment to its length of both needs to go till Himalayan because from that point match 2020 will do if you do to-do list a silent mix simple now this secret descendant notification system That is, if both the characters mismatch fear then we got to know something, we got to know the prince whose ch1's corresponding ch because so first of all sirvi what are you going to do then I need two things, increase the number of doctors why while doing the indicate account If consal salary works, then I will decree ch2, I will do it. End scene, put the ponting brightness near Swarna, then this has to be done in the shop, so that this is visible to Akshay, beautiful mehendi and cordial staff in teacher that Akshay is pintu. I am giving this name and notification character from 128, I am making equal to new obscene 200, now it has to come, just removed it, now if I am already present, you can add your platform in the start content key and graph, okay, chrome in this To use through the app, if I want to become the seat of the content, if the content is servi, if the content is creative and guru, if it is ugly, what do we have to do, if I look at the graph of tractor-trolleys, till I look at the graph of tractor-trolleys, till I look at the graph of tractor-trolleys, till now I am just trying to fix it. Single set up the call recording and compare cr which is the first mismatch character's corresponding stand cricket match mila to kya hai ch1 already map me presenter अध्वरविज की भीली अपने में to kya hai ch1 already map me presenter अध्वरविज की भीली अपने में to kya hai ch1 already map me presenter अध्वरविज की भीली अपने में अपने हैं है अपने हैं है अपने हैं है If there is a president in the already map then the state will be nothing but A, on one comment, I will add update in servi and space, mute surrey dot sh, already in the test, many have taken it out on the bus and added ch2 or just set Abhishek to section 2F only. Where do you slam add, if not then I will add us after the age, ride is August, but if it is not doing hours in the nose, from now on, we will remove half of it, if in our space, in the cent content, president of ch2, subscribe the channel, Indian Will do so in delhi that you get up incident who has water seats delimitation not end agreed not look at ch2 system that any imaginary what semen's that any imaginary what semen's that any imaginary what semen's loan cannot near or end 21 tree otherwise if from school If they fail then they will be set city, then if you pad the first one in this then dots will be increasing 2ch from it, learn a lesson and your husband's military product minute is the right admit, he needs to put it here in this brother call 100. Then put it by Yuvak, there is no need to make 2 years, so that PM, we have done it, now friends, now you will get the answer from here, after getting the off mismatch, you have to spread the chapter, after getting the mismatch, you have to spread it from off and look like if you get a mismatch. From here, pour a cup on Ko that brother, now go to the next one, you two wards, drink less, now there is no need to do anything else in this, whereas miss na Sheela Om, I have wronged you on the front in between. Only a few of the latter tell us that they can be used, so now we move ahead, make this 500 yards of land, don't show me my game, so now what do we have to do, simply decide, work to the minimum, then make it at the time of sleeping. Have taken it has been done again and again in one work one what we have to do and if we need cough then we make friends in meeting in which we have to make it from the end them stringbuilder tomorrow cricket now in school as much gun that these degree before 0.3 hrs So forget these degree before 0.3 hrs So forget these degree before 0.3 hrs So forget cost say speech from increase dot jai hind shat ki sir aap niklo aur August agar in degree dot guest teach ki equal 2014 ki if in quality 2013 and not SC code equal to zero then and one will remain then why in Add Shoaib and under the corpse Tubelight So someone has given life to CS in such a way that now after getting out of here, what do you have to do, after getting out of love, you will get the most of these till now the company does not happen till then Lok Sabha's simply to boiled why dot size that is not equal to zero 110 017 remove the ministry of workers and character is equal to you don't remove first your subscribe are trying that tractor mix will become history that Surya will make his friend Gave it to your friend and do the cutting of its name, first of all do the cutting, do it from accounting because you have to know also, all the temples have also been printed. Chapter issue of Lord of President inaugrates cycle which is Diora of this team. Contacted a similar group of 200. Now all the forces of the customer's bhajan, the people of the circle are usually the first to go to his residence. In the middle of the graph, all of us brothers, whose bus did not add. If you write carefully here, then those whose name is not there, they are never added, that in you, the cake soham, those who see it, that brother, if you are removing the turn of the graft content, if this is you, then spread it on top of this, if If his residence is presented then what will we remove in the one who will do it below him solve collector dependent equal to solve collector dependent equal to solve collector dependent equal to that Geeta Singh Rajput Ramesh Mehta Ludhia change and pe mistake appointed that is is is I this little free all On ne you will rice tabs nibbles your bus check so what how its in decrees what drink in degree misfits me what suits me on ne it plus on made in india giri dot net own old anjali set Do equal receives wi-fi old anjali set Do equal receives wi-fi old anjali set Do equal receives wi-fi setting then it - stop setting then it - stop setting then it - stop your correspondent if you central now if these degree if your in decrease and increase and cigarette not increase by 20 also dependent if equal 2220 then it has become independent why so If you can add in, then why should I add and return blast, we will update it in it instead of talking to lemon, now you have done it, here you will just go out of the files, so all you need to do is that brother, is the account quality controlled? Is it as many cafes as all? All the guys have been added to Stringbuilder, you can wrap it on the side of meeting like contact is not special, just okay, if you do it, then in the amazing print, that is quiet, return it from here, speed and something. Everyone inside became friends, it was true that palazzo is run by someone else, if he is not wearing the printed solution of buying it, then someone is not his own professor and someone can also make a praise, even the testers ca n't update the apps. Peace Party Well, if you take a bath in it first then show it Shayari Education which you need to think that I will tell you there is a war in which if he tells you then first let's heat it and see that this is some truth to me in the world so in this fennel is the one who is firm on the decision It is of the same type Tractors Limited, which has put the phone number in twenty, can not be sent, Atal good gas switch on and tell me, 200 gms, some in 1627, I had not put the size, how was yours decided, spot and do it or MP Chauhan. Nehru acted to Sanam, he will have to print the dot from 500 trains, International Journal 2018a, that Surya Prakash Reddy has been appointed Jasmine spokesperson of the committees, one is not handling that one is a picture, you are one, we are hunting one, I have kept something under the influence of one. There is something more obscene than leaves is that brother, if you have lips as ABCL and ABCD and have kept it in type travels, you have called on the phone and seen, then now you can develop both of these, if you put together a loop, then 3 You will go till the minute because you get down in this matter, this match will go wife messenger, how tight is the match, then if it has been three matches, if no mismatch is found, then it is written in the statement that the one who knows the lance will come first. In this match, the friend does not get the length of the locality, he will go first but you in the life order and told me that in this match, towards the final, the length of the first one is more, so how is it not possible that brother, in such a case, your answer cannot come like this. The one who cannot give his answer that he is a Dalit but Zohra Lotan needs qualification, if both of them are in that match, then this matter had to be maintained, he has given wrong input, for this he has asked to do the scientist American in the matter of money, then so. If I can't handle it and move the mountain back and forth, then it will become a part of the gratification. How to handle the loot center? I will trend the loot center so that you can see that this is do something in all, brother, if we will do an explanation of all the parties doing what, take the courier. Exactly keep it in perform or now I will make it as big as I will break, I will slide, I will select, if ever I get a mismatch, I replied by tweeting that I have found the next fennel, now this note has been found, so now we are in this match. If we have got the black color, now we have come out of the For Lips and when we have come out of the slippers of the Lok Sabha zodiac sign, if on the platform, then it means I am not sewing in this match. If by flight call, it means now that you have just I am. I was making a comeback among the plus one, there was no special found in it, no match was found anywhere, day, its length will be smaller, then someone lifts, if you do, the length will smile next, there is no problem, but if current's longing, if current's length is history, this If the length of the current becomes greater than this then keep this input separate from the penis of the next one which we had taken that after submitting to Bigg Boss, we will do it in the morning, after this we have done this first, let us write how many kilometers in the mix video today. Ajay is in trouble
Alien Dictionary
alien-dictionary
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you. You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language. Return _a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules._ If there is no solution, return `" "`_._ If there are multiple solutions, return _**any of them**_. **Example 1:** **Input:** words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\] **Output:** "wertf " **Example 2:** **Input:** words = \[ "z ", "x "\] **Output:** "zx " **Example 3:** **Input:** words = \[ "z ", "x ", "z "\] **Output:** " " **Explanation:** The order is invalid, so return ` " "`. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of only lowercase English letters.
null
Array,String,Depth-First Search,Breadth-First Search,Graph,Topological Sort
Hard
210
1,663
all right welcome to january's lead code challenge today's problem is smallest string with a given numeric value a numeric value of a lowercase character is defined as its position in the alphabet so a is one b is two so on and so forth a numeric value of a string consists of lowercase characters defined as the sum of its characters numeric values so a b e is going to be equal to one plus two plus five equals eight now you're given two integers n which is the length of the string and k which is the sum of the character numeric values we want to return the lexigraphically smallest string with length equal to n and numeric value equal to k note that a string x is lexigraphically smaller than y if x comes before y in dictionary order so in other words we want the smallest string in lex graphically sorted order with the sum of the k given to us and a length of n okay so a couple insights here we have a length right so at the very least we have to have a value that's going to be equal to the length of the string so if we consist all of these as a's that's going to sum of total of three and that's going to be the minimum number that we could actually return now to go into its number k so if you think about carefully uh we want to basically increase the last character to its max value and continue on until we fulfill our k so with this example here we can start with like aaa see whatever is left update the last character to the max number that we can which is z that's going to be 26 and if there's anything left after that we'll move on to the next index and continue this algorithm until we have a total sum of k so i hope that makes sense um let's think about our approach the first thing i want to do is create some sort of lookup dictionary with the numeric value as the key and the character as its index that way i don't need to worry too much about having to convert it constantly and what we'll do is have a list comprehension we are going to go from the index to the character in enumerate what i'll do is say range of i'm going to use the ord function and say a to the ord of z and i need to add one here as well so i'm going to create this dictionary with a value of i and i want to re convert this into a character so chr of character so let's make sure this looks right and looks like it works uh notice how i made the zero a and one a b and the reason i did it this way is we're gonna start off with everything being a one right so the difference isn't actually going to be the character that we want it's going to be like if we have 25 left over then we want to update it to a z right so we want we don't want this exactly as 26 we want it to be the difference from one uh that way it's going to make it a little bit easier when we do our calculations okay so the first thing i want to do is create a temp list and i'm going to have just all values of zero at first for let's say whatever in the range of the n given to us so now we have this temp string it's all zeros and that to us means it's all a's right so i want to start by initializing like the index character from the very end and this will just be the length of temp minus one and we want to keep track of whatever is left over so whatever's left over is going to be k minus the length of temp right okay so while we have something left over so left is greater than zero and just to make sure let's say all right n is also greater or equal to zero because we don't want to fall out of the index uh what are we going to check well we're at the very end here with aaa let's say and we're going to first see if whatever's left over is greater than 25 because if it's greater than 25 then it has to be a z right so if left is greater than 25 what do we want to do we're going to take our temps list and make that equal to well 25 after that i suppose we can just set left to zero and just end the algorithm otherwise if it's greater or if it's not greater then that means whatever this character is should be the temp here with whatever is left right and i apologize this shouldn't be left equal zero this should be left uh subtracted by 25 because if it's a z then we want to carry over whatever's left to the next character or the previous character and just keep continuing on here if we find that it's less than 25 and that's the last amount so this character is going to be something between a to z and uh just to continue our algorithm make sure to decrease our end by one and that would be it so after this we just need to return the string version of it right because right now it's a list of numbers so what we'll do is say four let's see i in temp or i in temp i suppose we're going to look up the character that's going to return to us a string and we all do a string join to make it into one single string here all right so that looks like it's working let's go ahead and check and that is accepted time complexity it's o of n right because we are only going to do as many as the length allows and we have to have this look up so that's actually going to be a space complexity of o of n as well now can we do better like this is fine this works um but is there a way that we can actually even do better than this if you think about it carefully um we know the minimum string is going to be all a's and the maximum string is going to be all z's right there's nothing less or greater than that if you think about characters carefully this algorithm basically what this means is it's going to consist of some number of a's in the beginning some number of z's at the end and one character of something else in the middle it could be all a's could be lz's but if there is something other than done in a or z it's only gonna be one of them it's gonna be in between these a's and z's so that's a big insight and this algorithm kind of shows you why that would be the case could we figure out a way to calculate that number and then just generate our string with the number of a's and z's at the end as well as the character that we want to look at okay so that's um that's possible if we did that we don't need any of this what we can do is say okay first take our k and we will subtract the number of n's and this is going to be basically what's up whatever is left over right now let's calculate the number of z's what's going to be the number of z's well that's going to be basically the number that we have left over divided by 25 right because if we have some number great or like 100 the number of z's that we can take care of that with is going to be divided by 25 there and we'll have something left over and that's if we have something left over that's going to be the weird character so to get the number of a's here we just take our number of z's uh subtract that from the uh n and i think we'll actually subtract one just in case we have a number in the middle so what we're going to do is take our number of a's add that to well before we get to that let's get to the number of z's as well oops and here in the middle we want to take um why i guess we can use the character get the ord of a and we'll add the modular from k modular 25 here this will give us the ord and we will add however many numbers that we need to add in the middle and we'll reconvert that back to a character so let's see if this works nope not nx it's nz oh and look at that it looks like that's working as well now one thing to note there is one edge case uh we might have all z's right that's possible and if we did that this kind of ruins it because of this middle operation here so what we'll do is say well look if um n times 26 it equals k then just return you know all z's and that should take care of that edge case and there we go that's much faster right and the logic is actually the same it's just that we're using some sort of math to kind of calculate it i think it's fine to start with that very beginning and if you can get to this solution that's great too um time complexity wise i guess this is constant right because it wouldn't require us to do any of ends it's just all these three equations here so that's it thanks for watching my channel and remember do not trust me i know nothing
Smallest String With A Given Numeric Value
detect-cycles-in-2d-grid
The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on. The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe "` is equal to `1 + 2 + 5 = 8`. You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._ Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. **Example 1:** **Input:** n = 3, k = 27 **Output:** "aay " **Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. **Example 2:** **Input:** n = 5, k = 73 **Output:** "aaszz " **Constraints:** * `1 <= n <= 105` * `n <= k <= 26 * n`
Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
229
majority so given an integer array of size n find all the inputs that I pay more than n by three times so the given an array of size m I am here to return all the elements that are that is appearing more than n by three times so n is the size of the array in this case the size of the array is 7. so 7 by 3 will be so the elements that are appearing more than two times we have to return this so if we see over here one is appearing Thrice so one will be written then again two also appearing Thrice so 2 will so return so this is what we need to return so at first it's uh the approach point we can do is we can just sort the array and then keep the pointer until the next number comes in you count it so if it is greater than 3 then add it then from here new count will be started again if it is greater than 3 add it here new control if the count will be one here and you stop it so there is a normal approach what do you do but the other thing instead of this what other thing we can do is you can create a hash map so this is key and value so key will be the array element and the value will be the number of times it's occurring so for one will not be present so married I will have point of one so while it will be one for two again in the added and the point will be one value will be one so one is already present so it is the value will be 3 is not present so the value will be one two the value will be committed two then again one is counter so value incremented three and two is also control you have this hash member one two three and three to one the values keys and values respectively now I took to the hash map as a set as a key set map key set we have so once you either the count these values are greater than n by three okay it is then just um the written type is list so create a list and add that particular number of the keys to the list and return the list that is how you solve the problem so at first we will create the list so in equal to num start length bracket now we will create the list of type integer so let's name it as list only Solar TV list so we'll create hash map also the type will be off into the comma integer let's name it as math new hashma so now we have added to the elements in the array so we have to add mapped on put off either you have to get the default one what you have to put one is the number and value depends whether the number is already present just increment the value by one otherwise by default and it does one so ma'am dot get off or either you get it or you make a default value half now comma zero plus one so what it will do if the number is already present it will increment by one if number is not present it will assign 0 and that y will also get incremented by 1 so the count will be 1. so after this now to add it to the foreign the value of particular number is greater than n by 3 then you have to add that to the list so let's dot add off that particular number so yeah at last you return the we will run this foreign please like the video and subscribe to the channel uh there is some other algorithm to solve the problem as well we'll be explaining in the next video so until then keep running thank you
Majority Element II
majority-element-ii
Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** \[3\] **Example 2:** **Input:** nums = \[1\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1,2\] **Output:** \[1,2\] **Constraints:** * `1 <= nums.length <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow up:** Could you solve the problem in linear time and in `O(1)` space?
How many majority elements could it possibly have? Do you have a better hint? Suggest it!
Array,Hash Table,Sorting,Counting
Medium
169,1102
1,260
welcome to tim's leco challenge this question is called shift 2d grid given a 2d grid of size m times n and an integer k you need to shift the grid k times now what does that mean shift means we're going to take the element at grid i j and move it to grid i j plus 1. now if the element is at the very edge or at the very right side of one row then we want to move it to the very beginning of the next row and if it's at the very end of the last row and last column that's gonna move all the way up to the beginning here so if we had a 2d grid like this one two three four five six seven eight nine and shift it one time nine is going to move up all the way up to here and it's gonna now look like one two three four five six seven eight so uh i don't think i really need to explain it more than that if we shift it four times you can see how it shifts four times here and we're gonna return that but that's kind of a trick there we definitely don't want to shift it multiple times we just want to shift it one time four times right so certainly um the easiest way to conceptualize this is to flatten this 2d array into a 1d array not actually do it but just imagine it that way because if we could do that then all we need to do is kind of write an algorithm as if this was a single 1d array and shift everything k times make sure everything wraps around to the proper point at which it needs to be long right if we want to calculate the proper row and column all we need to do is get the index number uh starting at the beginning and we'll assume like each one of these is one two like zero one two three four five all the way down and we can divide it by the number of columns to get the row and then do a modular number of columns to find which column it belongs in that row and if we do that then everything else should come pretty easily so let's initialize a couple variables here we'll do the m and n which is going to be the length of the grid as well as the length of the grid zero so this is rows and columns right now i'm going to also do a capital n here and this is going to be the actual number of cells and that's just going to be m times n so the easiest way to do this is just to initialize another m times n grid i'm just going to make these all zeros at first and say okay zero times the number of columns that's going to be n and say four blank in range of m right so all that remains then say okay 4i this is the index number as if this was a flat 1d array in range of capital n let's calculate what should be the new index number and that would be what j would equal i plus k right and we're going to make sure to wrap around and we'll do modular and in case we need to wrap around now all that remains then is let's put in our new output here what should this be um let me make sure i got this right this should be i suppose this should be j divided by n and the column would be j modular make sure that we get lowercase in there and this would be what get the original grid and we'll calculate i n and i modular and finally we can just return our output and this would be it this should be it let's make sure this works looks like that's working and there we go so this is the optimal solution unless you want to do this in place because this is a m times n time complexity but it also takes an m times n space right because we're creating this uh 2d array here uh so if you do it in place it's a little bit more complicated um well like let's just imagine if we had some flat array here and we want to shift it i don't know two times right we'll say five six one two three four like how do we do that well it's kind of hard right there's not really a two-pointer approach like uh really a two-pointer approach like uh really a two-pointer approach like uh the way we would have to kind of do it is to store that information somewhere temporarily so what we'd have to do is probably take start the very beginning we'll empty it out and store that somewhere in some temporary variable we'll say one now we'll move to where it belongs we'll say here store this somewhere temporarily say take that three and replace it with our current now we move two ahead again now we take our three here and we oh remember number five and now we move all the way up to all here this will be five but unfortunately we haven't done everything right so to take care of that you have to shift it once and make sure that we're gonna take care of every single element here so we shifted one right here now we'll take two so we'll be blank two here and move here this will be two we'll first store four take that two now we'll uh store six replace that with four and finally right here it's gonna be two oh sorry six yeah so if this is a one d array that's how we would do it but we can just assume that's a one d array because we can calculate it right here pretty easily okay so how do you do this uh well let's create a counter okay we're gonna get rid of this output here because we're gonna do this in place right so let's get a count okay and we'll also get the i initializing at zero here instead of doing a four i we're gonna do let's say while count is less than n okay uh count will go up whenever we do a shift here so let's see let's store the current value somewhere and we'll also store the new index number j that's going to be let's see grid this will be i divided by n i modular n and the j would be i plus k wrap around capital n right so while true uh we're going to try to go all the way around up until um if i let's see i equals j i say j equals i then we're gonna break there okay uh also make sure each time we're gonna increase our count by one and we're going to be doing this you know shift thing so we'll take our current and we'll take our uh grid and speed calculate the um the j and j modular m like this and we're going to do a swap right we'll take our shift something like that so we're going to be swapping that each time and we got to increase our j as well but make sure we i guess we do it after we break here so j uh plus equals what i that's not right yeah it's going to go j plus k wrap around to n right finally if we break out of here and we find that the count is still less than n then we're going to increase our i and we'll go by one so we can shift it and then we'll calculate the next elements right i'm going to just turn our grid here like this okay so let's make sure this works okay great i think that's working so there you go that's also going to be m times n time complexity but it uses constant space but you can see it's a little bit more complicated but it's really not that bad it just looks a little ugly and hard to understand but once you understand like the first approach i think this approach is actually not that hard okay thanks for watching my channel remember do not trust me i know nothing
Shift 2D Grid
day-of-the-year
Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times. In one shift operation: * Element at `grid[i][j]` moves to `grid[i][j + 1]`. * Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`. * Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`. Return the _2D grid_ after applying shift operation `k` times. **Example 1:** **Input:** `grid` = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 1 **Output:** \[\[9,1,2\],\[3,4,5\],\[6,7,8\]\] **Example 2:** **Input:** `grid` = \[\[3,8,1,9\],\[19,7,2,5\],\[4,6,11,10\],\[12,0,21,13\]\], k = 4 **Output:** \[\[12,0,21,13\],\[3,8,1,9\],\[19,7,2,5\],\[4,6,11,10\]\] **Example 3:** **Input:** `grid` = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 9 **Output:** \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m <= 50` * `1 <= n <= 50` * `-1000 <= grid[i][j] <= 1000` * `0 <= k <= 100`
Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).
Math,String
Easy
null
406
hey guys welcome to the core mat uh if you are new to the channel please do subscribe we solve a lot of competitive problems today's problem is q reconstruction by height what problem says is suppose you have a random list of people standing in a queue each person is described by a pair of integer h and k where h is the height of that person and k is the number of people in front of this person who have height greater than or equal to h write an algorithm to reconstruct the queue so we have now uh number of person given in the input two-dimensional area with h and k input two-dimensional area with h and k input two-dimensional area with h and k currently it's in it is not in order which we are expecting like uh every person should have k number of persons 10 k number of persons should standing in front of that person having a height is greater or equal to the what current person has the height okay that is what the rearrangement we would like to do okay so now let's understand with the example here the given as this two-dimensional here the given as this two-dimensional here the given as this two-dimensional area where for first person height is seven and we are expecting only 0 or 0 number of persons to be in front of this person so that way all the data is given in the two-dimensional area two-dimensional area two-dimensional area and expected output is uh this is what the correct arrangement for that so for this first pair in the result uh expected is to zero person which has a higher height as compared to the current height five and the same way goes to seven uh there also we the expected is to only zero person uh which are uh ahead of that person same it goes for five and two so here if you calculate there are two already two persons uh one is this pair and other is the person itself which are two persons are standing uh ahead of that person the same way it goes for here so for this one we already have a two so it's already satisfying the condition for 4 we want 4 person which should have a height is greater than the 4 so we already have 4 pace and same goes for the seven one because this pair is already satisfying that result also the same pair is also satisfying so we have already two persons standing uh ahead of that person which is having a height uh greater than the 7 now let's understand the solution approach for this so in the solution let's first understand with this example where we have each person having the same height let's say okay and our k is a different so the first pair we have a height is equal to seven we want zero percent to be uh standing uh ahead of that person same goes for seven two and seven one so in this case it is pretty simple for us like as height is same so we can directly arrange based on their whatever the requirement in the k okay so output for this one is going to be like let's say if we write output for this because we have only a height group as a seven only we do not have any different height so output is going to be first pair is going to be seven zero uh second pair is going to be seven one and third pair is going to be 7 2 because we do not have a different height over here okay all heights are same so we do not need to worry about it now let's see the second example okay in the second example i already put it the previous three elements or the previous three person and then i have added three more pairs from uh weight is all three pairs having the same weight six okay so let's say if it is going to be only this three okay then we know the result what is going to be okay so let's say if it is seven zero then we will have a seven one okay and then seven two okay now here we also have a second group of a person which is having a same weight so this is what the second group now if we consider this one also as a separate area now let's say if it is a given input error is having only this three person is a six then result we know that it is going to be first person is going to be six zero ah then you have a six one and then six two okay but we also have other person which is having a higher weight so it is always a good to add the this person's in the in between here if you take this way six zero will always satisfy the condition which we want because the higher weight or higher height person is already ahead of that person okay same way we can add six one over here and six and 2 over here okay so our result is going to be 7 0 okay then 6 0 then 7 1 6 1 7 2 and 6 2. okay so this is what the result is going to be now let's understand the same logic with the what whatever the in example given in the main question all right so this is what the input error given to us now let's first make a group of way uh persons based on their weight so highest weight is seven and we have two persons from that category okay uh first page okay and the third page so this two person having the same weight uh the next is we have a weight is equal to six then we have six and one okay for five we have two piece five zero and five two okay and for four we have one pair only okay four all right so now let's put this uh pairs in a uh q so first we will pick uh highest weight person and we will put both the pairs at index 0 and 1 first based on what we have discussed previously so first we will put this 7 0 and then 7 1 okay now we will pick 6 next element is a 6 our next person is having a height is equal to six so in that case uh that says that one person needs to have a higher height as compared to uh one so we already have a seven zero and one more so if we will put this pair as index one so this whatever the current pair we have seven one that is going to be moved to one more uh index uh right hand side okay so this is going to be 7 0 then we have here as 6 1 and then we have 7 1 okay now same way if we take a 5 okay it says 5 0 and 5 2 okay so our five zero will come at a zeroth index so same way this all three will shift one location to the right side we'll add five zero first and then rest of this okay let's say seven zero six one and seven one so this way this all four fours four uh pairs are currently satisfying the condition which we want okay now the second pair that from the five is we have five two so we will edit it uh index five two so that is going to come at this position okay so we will add phi 2 over there okay and same goes for the 4 so that will come at this position okay all right so what we did here is first we have shorted them based on their height okay and then if the height is same so in this case let's say if their height is same then in that case we would like to do a shorting uh based on their um the k value okay so this height short is going to be our descending order that highest height is going to be come first and within the same we would like to do ascending order of sorting based on indexes once we receive this data and then we will add this data to the list okay to perform this operations at each k we will try to add that pair and if there is a already pair present in this case here when we are adding a 6 1 7 1 was already there but for this less higher uh height we would like to add it under index one this one will get the first precedence as compared to this one so in that case we will add this whatever the currently generated sorted data to the list and then again we will return that list we will convert that to the array and then we will return it so that's it in the uh explanation now let's go back to the code and write a code for that all right now let's first short our array arrays or short okay we'll give a custom comparator x y so if both person having the same weight is equal to y of 0 so in that case we would like to short based on their rk value sorry 1 minus y of 1 okay else we would like to show it based on their height so it is 0 minus x of 0 y of 0 x of 0 yes ok so the our sorting logic is ready our error got sorted based on the what the logic we have discussed previously now let's define a queue or list array which is finally going to be our cube which is a type pair okay is sorry okay now list is ready now let's run look is equal to zero i less than people dot length plus okay now let's add it so every entry we will add it at the k position so we'll take that and one will add that entry over there so that way our final uh queue is going to be in expected order okay so our queue is ready now let's return that queue return list dot 2 array okay now we'll provide constructor integer as and this is the length of that okay now let's run it okay it got finished looks to be good now let's submit it okay it got submitted so that's it in this video hope you like it please add comments if you have a different approach or you are looking for solution for different problem thank you guys
Queue Reconstruction by Height
queue-reconstruction-by-height
You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each `people[i] = [hi, ki]` represents the `ith` person of height `hi` with **exactly** `ki` other people in front who have a height greater than or equal to `hi`. Reconstruct and return _the queue that is represented by the input array_ `people`. The returned queue should be formatted as an array `queue`, where `queue[j] = [hj, kj]` is the attributes of the `jth` person in the queue (`queue[0]` is the person at the front of the queue). **Example 1:** **Input:** people = \[\[7,0\],\[4,4\],\[7,1\],\[5,0\],\[6,1\],\[5,2\]\] **Output:** \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] **Explanation:** Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] is the reconstructed queue. **Example 2:** **Input:** people = \[\[6,0\],\[5,0\],\[4,0\],\[3,2\],\[2,2\],\[1,4\]\] **Output:** \[\[4,0\],\[5,0\],\[2,2\],\[3,2\],\[1,4\],\[6,0\]\] **Constraints:** * `1 <= people.length <= 2000` * `0 <= hi <= 106` * `0 <= ki < people.length` * It is guaranteed that the queue can be reconstructed.
What can you say about the position of the shortest person? If the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person?
Array,Greedy,Binary Indexed Tree,Segment Tree,Sorting
Medium
315
319
hey guys it's iran and today we're going to solve a question that i came across and couldn't solve to save my life it's called bobswitcher i have mixed feelings about this question on one hand i think it's a terrible interview question i mean just awful look at how many dislikes it has it's not for nothing but on the other hand i think it's a really cool math trick and it felt really satisfying to finally get it so that's why i wanted to make this video so hopefully you can have your own little light bulb moment so let's get straight into it there are n bulbs that are initially off you first turn on all the bulbs then you turn off every second bulb on the third round you toggle every third bulb which means turning it on if it's off or turning it off if it's on for the ith round you toggle every ith bulb return the number of bulbs that are on after n rounds so our goal here is to find how many bulbs are going to be switched on after n rounds right so uh let's do an example if n is four we have four bulbs and four rounds initially all the bulbs are off on the first round we toggle all the bulbs so all of them are on in the second round we toggle every second bulb in the third round we toggle every third ball and in round four we toggle every fourth bulb so after four rounds we have two bulbs that are switched on so the output for this example should be two now i think the first thing that we can all easily agree on is that a bulb ends up switched on after end round if we toggled it an odd number of times right because we start with all of them being off and then the first time we flip the switch we turn it on the second time turns it off next toggle turns it on then off then on and so on right so after an odd number of toggles the bulb will always be on so in order to find how many bulbs are going to be on after end rounds what we really need to find is how many bulbs are going to be toggled an odd number of times so let's try to think how many times will each ball be toggled and remember the rules of this game in round eye we toggle every is bulb naturally this means that in round i we toggle only the bulbs that divide evenly by i because those are the only bulbs that can be reached with a step of size i right let's do an example and make this point a bit clearer we'll do an example where n is equal to nine so we have nine bulbs and nine rounds in round one the step size is one so every bulb is toggled obviously all the bulb divides evenly by one in round two the step size is two so of course every bulb that divides evenly by two will be toggled in round three we tangle every third bulb that's bulbs three six and nine which is of course every bulb that divides evenly by three or in other words has a three as a divisor in round four we toggle every fourth bulb that's bulb four and bob eight which is every bulb that has four is a divisor and the rest of the table can be filled in the same way so as you can see in round eye we toggle every bulb that divides evenly by eye or in other words has i as a divisor that means that each ball be struggled once per each one of its divisors for example the divisors of six are one two three and six so those are exactly the rounds in which bob six is toggled rounds one two three and six the divisors of nine are one three and nine so those are the rounds in which both nine is toggled rounds one three and nine so if we go back to what we're trying to find which is how many bobs are toggled an odd number of times the fact that the number of times a ball be struggled is equal to the number of its divisors means that what we really need to find is how many bulbs have an odd number of divisors right and more generally put how many integers in the range one to n have an odd number of divisors let's look at the number six it's the bases are 1 2 3 and 6 because 6 can be written as 1 multiplied by 6 and it can also be written as 2 multiplied by 3. so naturally the divisors come in pairs right when two numbers multiply to equal a number x then two divisors are added for that number the only time a single divisor is added for x another pair is when a number multiplied by itself is equal to x for example let's look at the number nine its divisors are 1 3 and 9 because 9 can be written as 1 multiplied by 9 that is one pair of divisors and 9 can also be written as 3 multiplied by itself and that adds a single divisor another pair which makes the total number of divisors odd so the only numbers that have an odd number of divisors are the ones that can be written as the square of an integer those kinds of numbers are called perfect squares for example 4 is a perfect square because it can be written as 2 multiplied by 2 and 9 is a perfect square because it can be written as 3 multiplied by 3 and so on so now our question becomes how many integers in the range 1 to n are perfect squares so let's start by thinking how many integers in the range 1 to 16 are perfect squares are produced when we multiply an integer by itself so why not just produce them one by one starting from the first positive integer one the square of one is one so the first perfect square in the range one to sixteen is one the square of two is four which makes for the second perfect square in this range the square of three is nine is still within the range so we have three perfect squares the square of four is 16 still within the range so uh 16 is the fourth perfect square that we need to count and actually we can stop right here right we don't need to go any further because the square of 5 or of any other number that is larger than 4 will for sure be larger than 16 so it will not be in the range that we want it's even clearer if we look at the graph of x squared the range that we want is 1 to 16. 1 squared is within the range 2 squared is within the range 3 squared is still within the range and 4 squared is also within the range and anything larger than 4 will be somewhere here which is way outside the range that we want so that means that we have four perfect squares in the range one to sixteen now what about minus one or minus two or minus four they all produce perfect squares in that range as well but notice that they produce the exact same perfect squares they don't add anything new because it's completely symmetric minus 2 multiplied by itself is of course exactly the same as 2 multiplied by itself so we find just looking at the positive side now of course we don't want to actually compute all the perfect squares one by one and count them every time the trick is to go backwards we want y to be in the range 1 to 16. so we take the inverse of that we take the square root of the edges the square root of 1 is 1 so that's going to be the bottom limit the square root of 16 is 4 so that's going to be the top limit this means that every integer between 1 and 4 every integer in this range will for sure produce a perfect square in this range right and there are four integers in this range so the output should be 4. in the exact same way the number of perfect squares in the range 1 to n is equal to the number of integers in this range which is equal to the top limit minus the bottom limit plus 1 and that equals to the square root of n and that's the whole thing that's the trick the number of perfect squares in the range 1 to n is the square root of n which makes the number of bulbs that are going to be switched on after n rounds the square root of n that's the whole algorithm so let's see if we can manage to implement this crazy algorithm and we are done let's try to submit this okay so that is uh great and we are done with this one i hope you enjoyed this video uh don't forget to subscribe for more content like this thank you for watching and i will see you next time
Bulb Switcher
bulb-switcher
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Return _the number of bulbs that are on after `n` rounds_. **Example 1:** **Input:** n = 3 **Output:** 1 **Explanation:** At first, the three bulbs are \[off, off, off\]. After the first round, the three bulbs are \[on, on, on\]. After the second round, the three bulbs are \[on, off, on\]. After the third round, the three bulbs are \[on, off, off\]. So you should return 1 because there is only one bulb is on. **Example 2:** **Input:** n = 0 **Output:** 0 **Example 3:** **Input:** n = 1 **Output:** 1 **Constraints:** * `0 <= n <= 109`
null
Math,Brainteaser
Medium
672,1037,1491
827
in this video we're going to take a look at a legal problem called uh making a large island so we're basically given a n times n binary matrix squared you're given a you're allowed to change at most one zero right to be one return the size of the largest island in the grid after applying this operation so we are only allowed to change one zero to a one in our entire grid to find the largest either in our grid right and then the island is four directionally connected group of ones right so you can see here we cannot go diagonally we are only allowed to connect a island right islands connected four directionally basically up down left and right okay so in this case you can see here we have an example of our grid right so we have a one uh one zero and then we also have a zero and one right and then we wanna find the largest island after we flip what's one zero to a one so in this case if i change this zero right here to a one the max is three right if i change this zero to one the max island is also three so therefore the largest island is three right and then if we have something like this okay so in this case we have a we have uh a 2d array right and then in this case if i change this to zero right here sorry in this case this zero is right here so if i change the zero to a one the max area is four right so therefore uh there's only one zero so in this case we the max area is four right and if there's no zero at all that in this case the max area is basically four right or basically it's the size of the matrix so in this case um you can see here in our constraints is that n is basically grid.length which is basically grid.length which is basically grid.length which is basically the width of our grid and then n is between 1 to 500 and then for each and every single cell in our grid is basically either zero or one so how can we solve this problem so to solve this problem uh one way we can do this is we can use a brute force approach right and our brute force approach basically what we're going to do is that we're going to say find each and every single circle or sorry find each and every single zero right so let's say we have a zero here and there's one zero here so if i find a zero right and then what i can do is that i can basically do a dfs right i can do it just like how we did it in number of islands how we traverse using either breakfast search or deferred search to traverse the island and then find the area of our current island right so if i flip this to a zero to a one and i have a max variable right so once i done the dfs right in this case for the entire uh island where i try to traverse the entire island i know that the current island size is three so now what we have what we do is that we it basically updates our max to the largest island right in this case the largest island is a three and i change it back then i go find another zero which is right here so i change this to a one and i find the max area in this case it's basically a three so therefore we update our max in this case max is still three right so therefore at the end we just return our max or in this case the max island right so that's basically one way uh we can solve it but the time complexity as you can see here if n is basically the width of the uh of the grid right so basically the grid is basically n square right because we have n times n grid so if we were to do this approach we basically you know for each and every single zero we're basically visiting the entire grid so you can see here the time complexity is basically big o of n squared right times n squared uh and the reason why we do this because this n square is basically the size of our grid and then this n square is because in this case for each and every single zero we have to traverse we have to visit our kind of like our entire grid right or kind of like entire uh duplicate cells right so because we have to visit the entire island right we could have just visiting each and every single value multiple times so you can see here that the time complexity for this uh for this approach will be this right so how can we able to optimize this uh time complexity here right how can people to optimize to just you know the size of our grid right to n square so in this case to optimize the time complexity this to the size of our grid right the size of the grid what we can do is that we can be able to figure out how we can be able to cache this right if i'm at here if i'm at zero um in this case how can we be able to find the uh the islands or the size of our islands around them so that i don't have to traverse the entire island again right so maybe for example if i say these are the these islands has a size of three right has a size of three and then we somehow we know that the size of this island is a three so in this case for this zero once i visited zero you know i can basically do a dfs right or not dfs but basically you know visiting is nearby island in this case this is an island we know that it has a size of three and then we just say that hey the largest island for flipping this zero to a one is basically three plus a one right because we're changing this to a one so it's going to be three plus one which is basically a four right so we need to figure out how can how we can be able to cache this right how we can be able to reduce that uh computation right we don't have to do our dfs again and again right so how can people to say let's compute the area or not the area but the size of the island right to a variable that we can save it so that then what we can do is that we can basically just uh you know go to the nearby island and then maybe have some kind of way to retrieve the size of the island right so what we can do is that maybe we can use a table right to keep track of that and first what we have to do is we have to you know let's say we have a bigger island for example let's say we have one here and let's say this is zero right and this is zero one and one okay so in this case we know that this eyelet has a size of four the silent has a size two so in this case maybe we can have a table right uh to keep track of that which in this case this island has a size of four this island has size two so what we can do is that we may maybe we can use an id or maybe we can use some kind of strain to represent that right so maybe we can have an id the first item that we traverse in this case we can have like a integer value right or a different character value or something to represents that but in this case let's just keep it as an integer value right so because uh we can start with a two right because you can see here one and zero is already taken over so maybe we can start at two because id have to be unique or what we can do is that we can have a negative value we could just keep decrementing the id right so let's say for negative one it's our first island that we visit you know in this case this island right here has an id of negative one right so this i this island right here has an id of negative one it has a size of four we do a dfs explore this island and the next island that we found is this island right here and it basically has an id of negative two right so and then we do a dfs to explore the item we found the size is two okay so once we have this information available what we're gonna do then is we're basically just going to um going to visit each and every single zero right so once we found a zero we're going to do is that we're going to you know go for four directional go all four directionally and trying to find you know all the uh the basically the size of the island right so for this island right here it has a size of four for this island right here because this island has the same id as the previous island right maybe we can use a set to keep track of that right so this island we know that this island maybe has maybe we can change this to all just negative one right so that we know that this island has all has an id of negative one so we're gonna do is that we can basically keep a set right so we have negative one in our set so this has an id of negative one this is a zero so we don't keep track of that this has an id or this cell has a island id of negative two so far we have those values those ids in there right so then what we're gonna do is that we're basically just gonna get the value so this has a this id has a value four this id has a value two so therefore this if we flip this to a one it's basically four plus two plus one for the current cell because we're flipping the current cell to a one right so therefore you can see that one two three four five six seven right so we have six four plus two plus one which is basically seven right and then what we do is we basically move on to the next cell right so in this case we have we change this to a one right or this cell right here what we're going to do is that we're going to look at the id above us in this case it's a one right has an id of negative one and then we look at the uh the cell on the left in this case is zero so we don't keep track of that the cell below us in this case is uh is a one and then or in this case has an id of negative two right so we put an id of negative two here and then what we're gonna do is that we're gonna check the cell on the right in this case out of bound so we have two of them so in this case this has id of four this has or this id has a value four this id has a value of two so four plus two is seven oh sorry four plus two six plus the current cell if we flip this uh zero to a one is basically seven right so you can see the max in this case is still seven right and then if we go to this cell right here right in this case the same thing if i change this to or in this case if i visit the above cell it has a id of negative one i add it onto our set if i uh you know visit the cell uh beside us in this case has an id of negative two and then if i visit below us or left is out of bounds so in this case we don't keep track of that so in this case we have two ids this has this id has a value 4 this id has a value of 2 4 plus 2 plus 1 if we flip this cell to a one is basically gonna be seven right so in this case the max island is still seven right and just to clarify the reason why we're using an id here because you can see here if i know that this island has a side three and i know that this island has a size three how do we know that this island is the same as this island right so that's the reason why we're using an id here to keep tracking of unique islands right so therefore this is basically how we're going to do it and the time complexity if we were to do this approach it's basically just going to drop from you know big o of n squared times big o of power of n square right we're going to go from this time complexity we're going to drop it down to just this right the time complexity for this approach is basically this right we're basically just using a table right to keep track of that right to keep track of the pre-computed to keep track of the pre-computed to keep track of the pre-computed value so that we can be able to bring the time complexity down to n squared so now let's take a look at the code so the code uh basically is pretty simple what i did here is i put these values in a global variable right so i have a table integer is basically the key right which is the id of the island and then the values uh the value is basically the size of the island right and then we have our m times n which is not the case because we basically have n right because in this case uh the grid is basically n times n so i put m there which doesn't really make any sense but anyways um and then you can see here we have our id starting at negative one right every single time when we visit an island we're going to decrease the id by one right so what we're going to do first is that we're going to iterate through the array right through the grid and then for each land that we found we're going to do a dfs trying to find try to explore the island trying to find the size of the island and then we're going to save it onto our table right and then we're going to decrement our id because we want to keep our id unique so that we decrease it by one so we consistently making the id as a negative value so it's not gonna contradict with you know our any sales value in our grid right um so as you can see here in our dfs right so in this case you can see here we do our dfs do our base case check make sure that this cell is not visited and it's not out of bound and then what we do going to do is that we're going to assign the current cell that we visit right if this is the island right we're going to change it to the id so that what we're going to do is that we know that this land this cell right here it has an id attached to it so once we want to find if this id is the same we want to find unique ids or we want to find unique islands we can basically look at that right or in this case if i want to know the size of it size of this island i can look at the id right and then we do our dfs for all four directions and then we're returning a size right so what we're going to do then is you can see here after we you know get the size of each island and then save it onto our table we're going to have a max island variable to keep track of the maximum island right so for each id that we have in our table we're going to update our max island right so initially the reason why we do this is because there could be a situation where we have like no zero at all right so in this case we want to make sure we keep our max island to be equal to the max island value once we do that is that if we cannot be able to find a zero we can still just return the max island in this case the max island is basically the size of our grid right because we initially we already get this thing right we already get the max island already so if there is a zero right we want to calculate the max island we pass in the road past in the column and then we're gonna you know updates our max island right so our current max island or the max island and assign it to max island and in this case the calculates uh max island function you can see we pass in the row and column we're having a set to keep track of the unique ids right we don't want to have duplicate ids and added onto our uh or add to our added onto our calculation so we iterate through all the directions right this directions here we have uh four directions right so one is up down left right so we're going to do is that for each direction we're going to get our current row and column if it's out of bound we continue otherwise we want to see if it's zero as a water basically we can just continue otherwise we're going to get our current cells id and then we're going to add it onto our set right once we've done that we're going to get we have a sum for each and every single set uh for each every single id that we have in our sets we're going to basically get the cell right we add it onto our sum and then the reason why we're returning sun plus one here is because we want to flip the current cell right from a zero to a one right so therefore the sum is basically the uh the size of our island for all the nearbys for all the nearby cells for our current cell plus the current cell right plus one because we're flipping the current cell to a one so you can see here uh after we get the current max island we're going to update our max island right and basically at the end we're just returning max island so this is basically how we solve the problem and like i said time complexity is basically in square and it's basically the size of our grid so in this case we're basically traversing each and every single cell in our grid once right so basically you can see that this is how we solve the problem and thank you for watching
Making A Large Island
expressive-words
You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`. Return _the size of the largest **island** in_ `grid` _after applying this operation_. An **island** is a 4-directionally connected group of `1`s. **Example 1:** **Input:** grid = \[\[1,0\],\[0,1\]\] **Output:** 3 **Explanation:** Change one 0 to 1 and connect two 1s, then we get an island with area = 3. **Example 2:** **Input:** grid = \[\[1,1\],\[1,0\]\] **Output:** 4 **Explanation:** Change the 0 to 1 and make the island bigger, only one island with area = 4. **Example 3:** **Input:** grid = \[\[1,1\],\[1,1\]\] **Output:** 4 **Explanation:** Can't change any 0 to 1, only one island with area = 4. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 500` * `grid[i][j]` is either `0` or `1`.
null
Array,Two Pointers,String
Medium
null
109
hello guys welcome back to my channel my name is I hope you all are doing fine let's solve today's problem for lead code the problem name is convert sorted list to a binary search tree okay it's a medium problem just give a like the problem is saying given the head of a singular linked list where element are sorted in ascending order so we will be given a linked list where the elements of the linked list is in sorted array in ascending order okay convert it into the height balanced binary surgery so what we have to do we have to convert a linked list which is sorted in ascending order we have to convert it to the binary search string okay so you understood the problem let's see what is binary search the height balance minus h let's assume we have uh like uh there's a three rule basically two rows so one rule is that the left side should be always less than the root value okay and the right side should be always wait the signal is strong okay the left side should be always less than the root value and the right side should be always more than the root value this is the mythically binary search tree so what do you mean by this let's take an example let's say we have example like say we have zero and at so in this condition it should not be more than the root value now what is this is the root value okay this is the root value is the left side should not be more than the root value so we can either take whatever the value comes less than 0 we can take which is -2 can take which is -2 can take which is -2 and then what at right side a right side should be more than the root value so any element which is more than the root value is considered we have to put it to the right side okay let's take a uh this one let's take two positive two so which is more than 2 and negative 2 Which is less than zero I hope I'm clear here so this is what is this is left side and what is this is right side so this can see this uh condition is satisfied let's deep go deeper so here uh what will be the left side and what will be the right side uh can you tell me in the comment okay the left side will be obviously less than two so what is less than 2 minus 3 is less than 2 or minus 1 is less than 2 obviously minus 3 is less than so if you go negative it will be opposite okay minus 3 and what will be the right side it we can put minus 1 same thing we will do for this side so this ah like we have uh left side what we have we should be less than the root value so only one thing is that which is one and the right side should be more than the root value we can put it here three okay I hope you understood what is binary height balance binary surgery I hope you understood here what is this it has same what whatever the left side is obviously that side also has so it is a height balance binary such thing okay I hope I'm clear here let's see what's this the example says so we are given in a link English and we have to convert it to the binary structuring okay so we are given here a binary tree we have given a linked list so we have to convert it to the binary search tree height balance binary search tree okay so like we can take a 0 and here at left side is this less than the root value yes it is less than the root value so we can say it is right and at right it is more than the root value yes it is more than a root value so it is also right and next we will check for this one this is left is less than the root value the left should be left always less so it is right and here it this is the root value the left should be always less so here we have minus 10 so this is it so we can say this is height balance binary surgery okay this is a solution satisfies that let's see how we can solve it before that what we will do we I don't want leak list I want to convert it to error list so what I will do first I will convert it to the high resist it will be easy for me so I don't want to like solve it with linkage so I'm just converting into the arraylist so let's create another list here so integer um and I will name it as array new array list okay so now what I will do I have to iterate to every element so let's say this is head now okay so this is head now I have to iterate everyone I have to keep on adding okay so for that which function which loop I should use y Loop while head is not equal to null what is null uh like we don't have any element this is considered null till then run this Loop okay till then run this Loop what I will do here I will just okay so what I have to do here I have to keep on adding the element what element I have to add head dot value so value is here it is value so we have to put value here okay after that what you what have to do I have to now emit this and the head should be here for that what I will use a function called Nest okay so now head will Point head Dot next okay what I did here the head was here now head will be here now again head will be here now here the next will be zero now it will stop okay I open here now what we did here we just created array list okay we just converted a linked list to the error list okay now we will create a function which will help us we'll call it helper so to make it to the binary search tree okay array and the starting point will be 0 and the ending point will be the size of the array okay so why I am doing this I will tell you so let's see so I hope you remember whenever we see a sorted array we have to solve it by binary education binary problem or we can say uh like uh we can say divide and Rule so there are many names so basically like dividend rule so we will keep we will take that so divide and Rule so what is the meaning of divide and row so let's say let's take this example only let's take this example and what I will do here I will remove this I don't want this I will create my own answer okay so what I will do here I will consider left has zero and the right has the maximum value okay now what I will do I will find mid value so what is the mid value here the mid value is here 0 so how can I find it so like L to find the mid value basically what we have to do we have to add the low value and the uh the last value and divide it by 2. so in this case what you have to do this is 0 this is 1 this is 2 this is 3 and this is 4 okay so here 0 so what is the last value which is 0 plus what is the value last four and divide it by 2 okay now the value will be equal to how much the value will be equal to 2 because 4 divided by 2 will be equal to 2. so what will be the root value so I will create here okay now the root value is here what is the root value here root value is 2 which is 0 so we will make 0 okay now again we will do here what we'll do here again we will find the mid value but what I told here the rules here the left side should be always less than the root value so what I will do here I will say you have to calculate from here we have to calculate only this element so what is this 0 plus 1 what is 0 plus 1 which is equal to 1 now divided by 2 which is also equal to 0 because we don't consider it decimal point so what is 0 here 0 is minus 10 and where it should be at the left side okay it should be at the left side let's create minus 10 same thing we will do for the right side so from here right side so we have to take from here till here so what is 3 plus 4 which will be equal to how much which will be equal to 7 divided by 2 will be equal to 3.5 7 to 7 divided by 2 will be equal to 3.5 7 to 7 divided by 2 will be equal to 3.5 and we can say it as 3. so what is 3 here the 3 is here 5. so what we'll do at the right side we will put it as 5 okay at the right side we'll go and put it as the 5 okay I'm clear here I hope till here you understood what I did I just divided both the element divide and do now here I have calculated here so I have to find only this length and we can say this is minus 3 so minus 3 is more than minus 10 or less than minus 10. obviously more than minus 10. so what we will do here at if it is more than the root value what we have to do here we have to put it at right side minus 3 I hope I am clear here let's search for this one and we have another value which is 9 and 9 is more than 5 or less than 5 obviously more than 5. so what we'll do we will put that here okay so this is the solution for this but here you can say it is quite different here it's quite different but the solutions are same but the solution will be approved because here they took uh like uh three first then like they went for minus 10 but here we took divided into a concept and we did it okay let's see if the uh if the solution accept this order or not let's create a public uh what we have to do we have to return the tree node okay why we have to return T node we have to written at the end of the T naught that's why we are creating T naught and what will be the function called a function we'll call helper and I'm quite lazy so I'll copy this and paste it here and the end will be the left side and end will be the right side okay so I will just take this length make it more elegant okay let's do it okay now what we have to do we have to first find int mid so how we can find it how we did it left last right divided by 2 okay we just divided it now what we have to do we have to go and add it to the array rooted for that what we'll do we'll scale it three node root equal to tree node root equal to what new tree node array dot get of meet so that's why I convert it to the rim so we can't get the middle element we have to use like slow mid for Linked list we have to use like uh you may have heard about like slow and fast so I don't want to reduce that so this is quite easy so I just commentary to array and this is the pure solution okay after that what you have to do I have to go to the left side and here what I did here I said the now the mid minus one which is this is what's mid so I create mid minus 1 will be your new right side and the left side will be same okay the left side will be the same root dot left will be so now we will recall the function here we will recall this helper function we recall the helper function and we will say we will add it will be the same and the left will be also will be same but that here what we modified the right value the right was here and now the right was here so what we will do here it is mid minus one I hope I am clear and same thing we will do for the right side same thing we will do it for the right side which is helper as a now here we modified the left value so what we will do here we will place mid plus one so what here first it was media so now we uh we take left as 3 so what we'll do here mid plus 1 comma the right side net class what we have to do we have to return the root well okay let's run and see is this solution acceptable or not let's run okay so here there was some mistake because it the roof will keep on running we don't we didn't created a stop value so what we'll do here if how we can create this how we can stop this if left is less than the right so what we can say so in this case the left was less than the right so what we'll do we just did return the null so what we'll do here if left is more than so what we can say if left is more than the right uh no we can say okay if left is more than the right then we'll do one thing just return no okay that don't do anything now I think so runtime error will not come if there is any error anything else so it will come yeah it's getting accepted so as you can see the output they wanted here so what my output was 0 minus 10 5 null minus 3 null and nine but they were accepting they wanted minus three nine minus 10 null and five but as you can see this is also a height balance uh binary search T So if this solution is also accepted I hope I am clear here like submit and see if there is any error so now you can see it is getting accepted so it is getting accepted I hope I'm clear here I hope this solution is quite easy for beginners and also you have learned some new things and if you like this video please do like and if you didn't understand any part of this uh questions please do comment I will surely help you and thank you for watching keep coding solo bye
Convert Sorted List to Binary Search Tree
convert-sorted-list-to-binary-search-tree
Given the `head` of a singly linked list where elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** head = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** One possible answer is \[0,-3,9,-10,null,5\], which represents the shown height balanced BST. **Example 2:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in `head` is in the range `[0, 2 * 104]`. * `-105 <= Node.val <= 105`
null
Linked List,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Medium
108,2306
36
hello everyone in this video we will be solving the problem valid sudoku the number of the problem is 36 on lead code if you have played sudoku before then the rules must be pretty familiar to you but for everyone else who haven't played sudoku i'll just go through the rules we have to determine if the 9x9 sudoku board is valid or not only the filled cells needs to be validated according to the rules so we do not have to fill out the remaining cells to see if the sudoku board is valid or not just look for the values that are already provided the first rule is each row must contain the digits 1 to 9 without repetition each column must contain the digits 1 to 9 without repetition each of the 9 3 by 3 sub boxes in the grid must contain the digits 1 to 9 without repetition another a couple of nodes that the problem statement has is a sudoku board if partially filled could be valid but it is not necessarily solvable only the filled cells needs to be validated according to the mentioned rules so again we do not have to work on all the blanks in this sudoku board we only have to look at the values that are already provided so if you look at the example number one it would take some time to go through all the cells and validate it but the gist of it is this board is valid because it has all the right numbers in the right spots but if you look at the bone number two this is invalid because this number 8 is repeated twice in column number 1. so this board becomes invalid let's go to the whiteboard and see how it can be implemented i will be using the example number one from the problem statement to understand how it can be solved i believe this problem doesn't need any kind of an algorithm as such it is more dependent on our problem solving skills as the problem is asking us to look at the rows columns and the boxes we will be defining a dictionary or some sort of a variable which will hold all the values that are provided in the input i will create three variables here and these three variables probably need to be a 2d demand 2 dimensional or something which has a key and a value the key will be the identifier like for row the key will be the row number column will be the column number and box we can say it's a box number the first nine boxes three by three will be box number one then the number two number three and etc we can define that rule rsf row and column is pretty straightforward so let's say we create a dictionary or a two dimensional ad for simplicity i'll do a two dimensional array but in each entry we will not be saving only one value but we will be saving a collection of values in all of the three variables the first entry would be the row number index number or box number and the second would be or the numbers that are present in that row are in that column or in the correspond on the box all the numbers are going to be present in all the three variables so for this phi if i were to enter it in these variables its index would be so for row it will become r will be so my index is going to be 0 and here i will add the number so on row number zero let's say i'm creating a new list here so i will add five and then wait for the remaining characters whenever i'm scrolling through so basically when i'm iterating through all the numbers in the given board i will keep on adding it to these boxes or to these variables and make sure that those numbers are unique i should not be getting the same value again if i get it i should throw an error saying that it's an invalid sudoku board so i start with 5 so after adding it for row let's add it for column as well so for column the column number is zero and i add five and for box my box is zero again and i'm adding five okay i'll keep the brackets bigger so i can add more numbers to it so i will continue looping through all the numbers in the board after doing it for five i am on this empty so if it is empty or dot in the input we have to ignore it ignore now i am on seven so for seven if i'm adding it to the row variable the index is going to be zero so i will add it the same variable and then here i'm adding 0 7 i made sure that 7 is unique in this so far which is true so i can add it without any errors after adding it to the row variable we need to add it to the column and boxes as well i'll continue looping through further empty now i am on six now for six my row was incremented by one so i need to use another row with index 1 instead of using the previous one with index 0 r of 1 and then add 6 also i need to add it to the row column variable the column is still zero so i can add it to this column variable that's already created it is unique so i can add it without any error so adding six and this is still the first box so i can add it to my box variable the one that i've already created so 5 comma 6. similarly you can keep on incrementing through all the numbers in the sudoku board and make sure that you are adding it and the right index and if at any given point of time you find a number being repeated in that index in that variable for that given index through an error for example let me put a random variable here which will make the board invalid so i'm putting a 6 just next to the number that we just covered and this is repeated in the box so after going through this variable if i increment my counter so i'm now pointing at this six which is in box number one so it should be added in this box if i were to add it first i need to validate if the six is unique or not which is not unique so i will not be able to add it and i can say that this board is invalid and i can abandon the whole process i hope you are able to understand the approach it is simple it doesn't seem to me that it's a medium level problem when you understand the concept the time complexity for this solution is this o of m into n where m is the number of rows and the n is number of columns so in this case if it is 9 by 9 so it's o of 81 because we are iterating through each and every number only once our space complexity is 3 into m into n because we are creating three different variables and each variable is going to hold the value so it's like try we are saving the value thrice in three different variables three is sort of negligible so it's the space complexity is o of m into n so for this white the approach that we just discussed let's look at the c sharp implementation like we discussed in our whiteboard session i have created three variables for rows columns and boxes it's a dictionary of integer and hash set integer means it will be holding the values of the index like the row number column number or the box number and the hash set of character it will hold the values that are available in that corresponding row column or box the property of high set is to keep is to have all the values unique so if i'm trying to add a duplicate value it will return me false and i can directly throw an error based on that the flow starts with iterating through all the rows i take get the row and then start with the column so i'm getting the value in this field variable and then verifying if the field value is not equals to a dot which means empty so at each layer i am checking if the row was already being hydrated if it was iterated then i will find this contains key will return true i try to add that field to the row is it throwing an error or not because it's an has set if my addition is successful it will return me true or else it will return me false so in case if it is returning me false i am setting my result variable as false and i am breaking the loop if i haven't iterated through that row before i am creating or adding a new entry to the rows dictionary with i as my index or key and creating a new hash set adding field to it just like the rows i have the same logic for the columns as well to get the box number is slightly different because the box numbers are determined the by i and j together so i have built a helper method that returns me the box number depending on i and j for example if my i is less than 3 and j is less than 3 it means i am looking at box number 1. if my i is less than 3 but j is greater than 2 and less than 6 it means it is box number 2 and so forth so using this helper method i am calculating the box number and then using that same logic that we discussed earlier for rows and columns i am calculating if the variable is already added to the box or not if it is added through an error if not then add it to the list and at the end after the whole flow completes i am checking if my result is true or not if the result is true i return true else i return false i hope you were able to understand the solution and the whiteboard session that we had if you have any questions or concerns please feel free to reach out to me i will be adding the link to this solution in the description below and i will see you in the next one thank you
Valid Sudoku
valid-sudoku
Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**: 1. Each row must contain the digits `1-9` without repetition. 2. Each column must contain the digits `1-9` without repetition. 3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition. **Note:** * A Sudoku board (partially filled) could be valid but is not necessarily solvable. * Only the filled cells need to be validated according to the mentioned rules. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** true **Example 2:** **Input:** board = \[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** false **Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid. **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit `1-9` or `'.'`.
null
Array,Hash Table,Matrix
Medium
37,2254
797
Hello everyone and welcome back to my channel Algorithm H Why Today I am going to write the code and also explain to you all the algorithm to solve this all paths from source to target problem which is there in lead code it is a medium level problem and Belong to the graph section, so let's start it by naming it She Creation. In this question, we have been given a directed acyclic graph in terms of 2d integer array in which the integer array given at each index is represented. Neighbor of that particular node is the index node and the values ​​on it which are in the integer array are their values ​​on it which are in the integer array are their values ​​on it which are in the integer array are their neighbors. Okay, so what we have to do is to find all the paths from 0 to node n - 1 and those We from 0 to node n - 1 and those We from 0 to node n - 1 and those We can return in any order, like for this particular example, the graph that we have is given, okay, so how do we get to three, go from zero to zero, go to one, then go from one to three. If there is one path, it will remain so it is listed here, okay, then after that one can go from zero to two and then from two to three, so it is listed here, so all the parts have to be returned to us and we can return in any order. Okay, so the first approach I have thought of for this is that we will do DFS and DFS is depth first traverse I mean search and then after that we will do DFS, when we reach three then we will maintain list one. In which we will have kept all the notes of the foot till now. Okay, we will traverse till we reach n -1 and as soon as we will traverse till we reach n -1 and as soon as we will traverse till we reach n -1 and as soon as we reach n -1, we will create a reach n -1, we will create a reach n -1, we will create a list and add it to the answer list which we will return. If we do it then let's do a dry run of it once and see how we are going to do it, this is our graph, so basically we will start from zero, okay from zero we will go to one, okay we will add it to the list, then from one we will go to three, now Because this is our target note which we had to reach, then we will store this list in an answer list, then zero comma one comma is fine and now simultaneously we will back track and remove all the elements which we had added. If we keep doing this then we have removed three, now there is some other neighbor from one, otherwise we cannot go anywhere else, so again we have removed one also, now from zero we will go to two, okay then after that we will also go from two. On three again we have found the target node, so we will store this path from zero to three in an answer list again. Okay, now again on three there is no other neighbor and anyway three is the target note. So, we will remove it and we will also remove two and we will also remove zero and the last answer we will get will be 013 and 023, its code will be quite simple, we will have to remove it again and again by just tracking back, okay? Let's code it, then quickly, it's okay, we will create a function private void find path, okay, then the node is the int node, which is the current node, ours is okay, whose neighbors we will see, okay, then this will be the graph, then list of integers. Just second or wrong time, I have written answer and then list of integer current. In this we will store what is the current thing and in answer we will store all the things that we have got, okay till that target, now like we can go to any node. When it comes, we will add it to the current. Okay, after that we will see if the note is what it is, graph dot length minus and height means we have found the target note. If the target note is found then we will create a new array list in which the current We will copy the element in the current, so we will back track the elements to be removed, okay and add it to the current, then we will remove the current from the current, which is our element, what we just added, which will be present at the last index, okay and Then after that we will return from here because we do not need to traverse further notes, then after that we will see all the neighbors of our current note. If our target node is not our current node, then we will see all the neighbors of our graph. We will again apply this recursive function in the neighbors of the current note. Ok, I am the neighbor who will become your red note. For the next call, the current list will remain the same. Ok, and the target was added initially, now you will have to remove it here. I had removed it because we were returning after that, so it could not be removed, otherwise it would not go down, otherwise the current dot size is fine, so basically we will do this, after that, let's make a list of integers. Answer: after that, let's make a list of integers. Answer: New Array List Then here will come Fine Path Zero Comma Graph Comma Answer Comma New Array List Okay, we are starting from zero, so the value of our node, we have given zero and then we will return answer, run it once and see. Let's take this function, it is not available because the find path is fine and somewhere else yes, it's fine, let's run it and see if these two test cases have been successful, let's see by submitting them, okay, it's been submitted too, but Before leaving please don't forget to like the video and subscribe to my channel and also tell me my improvement points in the comment section ts it for the video Radhe
All Paths From Source to Target
rabbits-in-forest
Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**. The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`). **Example 1:** **Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\] **Output:** \[\[0,1,3\],\[0,2,3\]\] **Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. **Example 2:** **Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\] **Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\] **Constraints:** * `n == graph.length` * `2 <= n <= 15` * `0 <= graph[i][j] < n` * `graph[i][j] != i` (i.e., there will be no self-loops). * All the elements of `graph[i]` are **unique**. * The input graph is **guaranteed** to be a **DAG**.
null
Array,Hash Table,Math,Greedy
Medium
null
513
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is find bottom left tree value so in this question we given the root of a binary tree and we have to return the leftmost value in the last row of the tree so this is a straightforward description you have to find the last row and inside that last row what is the leftmost value you have to return it so in this case one is the output and in this case seven is the output now let's take a look at these examples and see how we can solve this question so let's take the first example you're given the root of a binary tree 2 1 and 3 and your answer is 1 because that is the leftmost value in the binary tree so you need to find the leftmost value in the last row of the tree so this is the last row and this is the leftmost value so you know you have to reach the last row so you have to Traverse through all the nodes there are two techniques DFS and BFS to Traverse through the nodes inside the binary tree so DFS is depth wise you access the depth first and BFS is level order traverser you access all the nodes in one level and you go level by level so first you explore this and next you explore this level so in this video Let's solve this using BFS so in BFS first you are at the root and then you access all the nodes in the current level you go to the next level and while going to the next level you Traverse from the left to the right so you access all the nodes in that level from left to right but here we need the leftmost value inside the last row right so what happens if we Traverse from right to left of every l LEL so the last node you visit will be your answer so let's take this example so to implement BFS you need a q so you are at the root so add the root so one will be added all its node will be connected as a sub tree so I'm taking the topmost element in the root now we go to the next level so how do you go to the next level you start from the right and now we pop that element out of the queue so after popping we have one we check if one has a right sh yes one has a right sh so add that into the quebe and now you are at this level you access this and you're at one you checked Its Right child now you have to check its left child if it has a left child yes so add it into the queue from back now you access both the nodes of one so eliminate that now from the cube pop the first element it is three now for three check this right child first and then the left child check if three has a right child yes it has a right child so six will be added at the end of the CU now we added the right child add it left child check if it has a left child yes so add it into the Que Now you access both the left and right child for three so you eliminate that now take the top element from the Q it is two add Its Right sh it does not have a right sh so it won't be added add its left CH yes it has a left CH so add it into the Q in the end now we access both right and left for two so eliminate that now we are at this level now take the topmost element it six check if it has a right sh no it does not have a right sh check it has a left sh no it does not have now we access both left and right so remove it from the Que Now take the topmost element it is five check Its Right sh it does not have a right sh so it won't be added check it left sh it has a left sh so add it into the quebe now we access both left and right so remove it from the que or get the topmost element from the Q it is four get its right child there's no right child for four there's no left child for four we access both of them so remove it from the Q now the root is seven check Its Right sh there's no right shell we check its left shell there's no left sh so remove it from the Q once the Q is empty whatever is the last element we processed so this is the root right so root will be here so return root. Val root do Val is 7 so 7 is the output for this equation now let's take a look at the code to implement BFS coming to the function given to us this is the function name and we are given the root of the binary tree and the output is a integer representing the last Row's leftmost value so like I said we are going to implement this using BFS so to implement BFS we need a que so let me declare it this Q is going to store tree notes I'm going to name it q and it will be implemented as a link list now to start off we need to add this root into the que so initially root is here so it has its left and right connections so into the queue initially using the add method add the root now like we discussed we need to iterate until the Q is empty so using a while loop we keep on iterating and this while Loop's condition will be until the Q is empty until Q dot is empty so until the Q is empty this will happen and once the Q is empty it comes out of the file Loop and now if Q is not empty there is at least one element present inside the Q so using the pole method get the element and remove it from the que so I'm going to use the root itself and using the pole method on the que so the pole method will return the first value present at the beginning of the queue and it will also remove it and now we have the root so if root is here first we need to add Its Right child so before adding the right sh we have to check if right is present or not so if root. WR is not equal to null only then add it into the Q so q. add of root. right now again we have to do the same for the left child of the root so root. left if it is not null only then add that into the q. add of root. left so make sure that you're first adding the right child and only then adding the left side and this y Loop will happen for all the elements inside the root and finally once Q is empty you come out of the Y Loop and you have to return the last visited node will be here so root will be here right so return its value so return root. value now let's try to run the code the test case are being accepted let's submit the code and the solution is accepted so the time complexity of this approach is of n because we're iterating all the nodes inside the tree at least once and the space complexity is also off n because we're using a q to solve this question to implement BFS that's it guys thank you for watching and I'll see you in the next video lady
Find Bottom Left Tree Value
find-bottom-left-tree-value
Given the `root` of a binary tree, return the leftmost value in the last row of the tree. **Example 1:** **Input:** root = \[2,1,3\] **Output:** 1 **Example 2:** **Input:** root = \[1,2,3,4,null,5,6,null,null,7\] **Output:** 7 **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
201
hello and welcome to my channel so today let's look at the uh today's lead code challenge question 201 bit wise and of a numbers range the question is given two integers left and right that represents the range left to right return the bitwise end of all numbers in this range inclusively so when we saw this question the first uh thought that maybe you uh what you want to do is to better wise all the numbers between left and right but the problem is we need to check the range so left and right actually the right the numbers might be like more than two times uh turn uh 10 to the power of nine so either we'll definitely get a tle so that's why we cannot uh do it just in the like brutal force so the question actually is a can be solved by beta operation so firstly we want to um check like at the end what is the probability of end b the end so the and the probability one property is uh if you end multiple numbers like five numbers here but uh there is a one zero join the end will result in a zero but the only one there is a like no zeros in your end no matter how many numbers you are ending so you will get a one so but if you have one zero two zero three zero it doesn't matter um the result will always be zero so um so to solve this question let's uh look at the like example one the left is five uh right is seven so if we want if we represent this two number in beta operations uh the left will be this like in the binary so the line will be this so i don't know we add a zero because uh that like the integer actually are 32 bit so actually we can add a like padding zeros it doesn't hurt so actually we can see that as long as there are right larger than left um so the end will have will result zero in the last digit so because if a writer is larger than left then in the last digit it must be um alternatively alternating that uh even the right last dj is one then next larger than uh that number is it will be have a last digit than zero so it will actually it must have at least one zeros so that's uh how we get this conclusion so for this problem what we can do is uh we can look for the prefix common prefix of this two binary number so the common prefix for this uh two number is uh is zero one and then we actually will uh will padding all like zeros to the right side so in the end the result will be one zero which is uh which is four um so let's uh let's start maybe writing the code um so we want to record the shift the num the number of shifts so that we know like how many digits on to the right side of uh the first uh common like at the first uh location that the prefix is equal so in the end we need to uh shift the back so that we can get zero one zero so yeah so as long as the left is uh smaller than right um we will do a left now actually i wish there was a shift into the right side so uh shifted to the right side so uh 0 1 0 will become a 0 1 0 and uh 0 zero one will become a zero one so i mean shift to the right side for one to one digit so and uh we need to add a shift so that we know like how many shifts we did so and then we just need to shift the back the left and the i mean to uh to shift it to the left side for shifted times and then we can just return the left so yeah also let's check the example too so for the example do left that is zero right is zero so the shift number will be zero so the we do left shift the shift left uh shift to the left uh zero times that is still left uh it will be equal to left so the answer will be still left will be zero so it's correct uh so example three is uh left is a one by right is the integer max so what we will get is we will shift it to the left so in this example left is a one and the right is a like a um 32 ones so what do we uh so we actually shifted to the right then the first shifter once then this so one will be zero but the those are actually still like us so actually we will shift the like 32 times so by the left uh so actually the left is already zero so one will shift it back or 32 times it will be still zero so the left will be zero so all the case seems is fine in the testing cases yeah so it's cracked seems yeah and also uh the time complexity uh so this time this while loop maximum level x uh execute uh 32 times so um so actually the time complexity will be one although is 32 times the bias is still constant space time component is similarly one so let's let me try and uh this let's check if it's all crack okay so let me let us some myth okay cool yeah so um if you have questions please comment on the video if you liked it please subscribe and click like button yeah thank you for watching see you next time
Bitwise AND of Numbers Range
bitwise-and-of-numbers-range
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_. **Example 1:** **Input:** left = 5, right = 7 **Output:** 4 **Example 2:** **Input:** left = 0, right = 0 **Output:** 0 **Example 3:** **Input:** left = 1, right = 2147483647 **Output:** 0 **Constraints:** * `0 <= left <= right <= 231 - 1`
null
Bit Manipulation
Medium
null
495
the problem is demo attacking so the question is our hero Teemo is taking an enemy Ash with poison attacks when Timo attacks Ash gets poisoned for exactly duration seconds more formally an attack at second T will mean Ash is poison during the inclusion time interval t 2 t plus duration minus 1. if Timo attacks again before the poison ends the timer for it is resets and the poison effect will end duration seconds after the new index you are given a non-decreasing integer array time series non-decreasing integer array time series non-decreasing integer array time series where time series of 5 denotes that demo attacks Ash at second time series of 5. and an integer duration written the total number of seconds that H is poisoned so the question what the question says we have given a Time series an array of Time series it which is non-decreasing order series it which is non-decreasing order series it which is non-decreasing order means it is an increasing order it is an increasing or just we will we can have same values like 1 4 5 we it is a non-decreasing array so it is a Time non-decreasing array so it is a Time non-decreasing array so it is a Time series time series is time series of I represents Teemo attacks Ash at second at the second Timo attacks Ash at first second Timo attacks at timu attacks Ash at Fourth second so it is a it represents Teemo attacks Ash at seconds so it is a non-decreasing array time so it is a non-decreasing array time so it is a non-decreasing array time series which represents attack demos attacking second team was attacking on which second okay and duration is for how long do you move how long the team was attacking with poison so duration represents how long the effect of poison will stay there how long it affects Ash the poison effect to Ash so we have given a array 1 comma 4 and duration is two so we have to find the answer that we have to return total number of seconds that Ash is poisoned Okay so they have given you can they have given the array is one comma so array is 1 comma 4 so Timo will attack at first second so the duration is from t is this from T to t plus duration minus 1. and we have to include both of them so what's the long what's the duration is from 1 to 2. 1 2 so for we can include in our answer we can include first and second first second and second so we have answer is 2 at I equal to 0 we have answer is 2. we have answer is two now T-Mobile attack have answer is two now T-Mobile attack have answer is two now T-Mobile attack at four second at Fourth second the duration is from 4 to T2 t plus duration minus 1 we have to include both of them so it is from 4 to 5. so if we will include them we have given 4 plus 5 4 and 5 which is 2 so answer here also 2. so if we will add both of the answer the total answer will become 4. as they have given here Timo attacks on ash go as follows at second one demo attacks and Ashes poison for second one and two at second four chemotax and Ash is poison for seconds four and five so Ash is poison for second one two four and five which is 4 seconds in total so our answer is 4 but now if let's say the time series is 1 and 2 and duration is 2 then what is the answer let's say the time series is one and two and duration is true so for first I equal to 1 for first second what we'll do simply one from 1 to 1 plus 2 minus 1. from first to second first plus duration minus one as they have given this thing they have given T from T to t plus duration minus 1 so we have used this so the answer is from 1 to 2 so answer is 2 okay for I equals to 0 the answer is 2 for I equal to 1. if I is here then I equal to 1 to answer what is the answer is for t equal to 2 we'll say the answer is from t from 2 to 2 plus 2 minus 1. 2 3. okay but now we can see we have included second num we have included second all ready we have included the number two already so we can't include it again we have included it all already so we can't include it again so we can't say k no we can't say Timo is poisoned for second one for second two and for second three no it is not them we have to say the steam or the ash is poison for one second two and second three okay so for this answer for this we will include only three so answer is one and total answer is three so you have given an idea what's the problem if the last answer which last answer we have found last answer we have calculate if this answer is less than this number when array was 1 comma 4 so this answer last answer this last second is less than this second is less than from this number if this last second is less than from this number we can simply add we can simply find this duration and add at them okay if now but if this last second is not less than is equal to or it's greater than this second for in this case 1 comma 2 this last second is equal to this it is equal to or equal it is greater than this number so what we have to do we have to Simply find its answer we will simplify this answer we'll simply find its it's last second it is 3G which we will find this range we'll find from how the maximum second it is going the maximum second degree it is going till 3 so what we will do we will simply minus this last second from this second what we will do we'll say if it is going from 1 comma 2 in first second and it is going from 2 comma 3 in second so if this second is not less than it is this second is not less than this array number if this second is not less than this other number what we have to do we have to minus we have to reduce this effect we have to which numbers we have included one comma two okay so we have to reduce this now we can't take this range this whole range we can't take 2 comma three we can't take two and three both we have to reduce this two number we have to reduce which we have included we have to reduce this what we can do we can simply minus this number this last second from this second so which numbers this range have included this range I've included this range will we will subtract from this range okay this range which numbers this range I have included we will subtract this range from this number so in this case what we will do we'll simply find we will simply find 3 we'll simplify 3 from 2 plus 2 minus 1 and we will say we will take a variable previous multiple variable previous in previous we will store the last second so here last second is to now second is to and we will so simply we will say answer we'll say answer Plus equal to this 3 minus previous we will say answer is equal to 3 minus previous if it is less than if this number this last second is less than this array number if it is a less than then this array number then we will simply add this whole range we'll simply add this whole range you will not we will not subtract this previous okay so the solution is now what we have taken the answer initialized with 0 we have taken a previous previously it is in they have taken the minimum value will say it is less than from nums of I because for in first to second first is one to anything first in zeroth position there is any second we will take it because there is no previous anything so we have to take its whole range so we have simply take previous into Main so because we have given this condition now this if this previous is less than this array number then what we have to do we have to add them simply okay so in initially this initially we have to add this second we have to add so we will say this previous is always less than at initially this previous is always less than this number okay we'll say it is previous is always less than this number so simply what I have done I have taken a previous it is into Min and a temp variable so I have done a for Loop from I equal to 0 till the time series size so there are two conditions If the previous is less than this array nums of is less than this second time series of I if this previous is less than this arrays element then what we will do we will simply add this duration answer plus equal to D and we will store the last number of the duration we will store the last number in duration in previous what we are doing we are storing these two this last duration last number of the duration in previous okay we have stored two in this previous okay here from first example we have store two then we will again come at 4 we'll say for like uh for example we are doing this then we will come at 2 will again check if 2 is less than 2 that it is not less than so what we are doing we are finding a temp we are finding this range we are finding this three we are finding this 3. okay in temp we are finding this three so three is nums of I plus duration minus one nums of I or time series of I plus duration minus 1 okay this time series of I plus duration minus 1 and what we are doing we are simply reducing this previous we are simply subtracting this previous from temp we are simply subtracting this previous this we have found previously two is found previously so now what we are doing 3 minus 2 and we are adding this in an answer also we will update this previous now previous is this previous is what is previous is this three previous is last number of the duration so what we are doing we are updating the previous and adding the temp minus previous answer and if it is less than or time series of I then we are simply adding the answer and updating the previous then at last we are returning the answer so we can run the code foreign and its time complexity is order of n thank you
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
430
Hello everyone welcome to my channel today's date 19th July recording will play any problem his flat in a multi level doubly linked this problem you are giver ne Delhi link leaves bhi thing in addition to the next and previous pointers it should have a channel pointer In the middle and the main knot does not point to the self Delhi in this Sindhi style list has one or more children of the ground and shown to produce a multi level data structure as shown in the example Blue Planet in the place where the best all the notes appear in A single level Devlin please you are in the head of the first level of the list saw her decision example and behave with his first level Sudhir we and he noticed 2.12 and have not done after each Sudhir we and he noticed 2.12 and have not done after each Sudhir we and he noticed 2.12 and have not done after each rate notes on third is with child pointer in the River Valley From Child Point to This Ain't Have Another Child Point Up So What We Need to Do We Need to Club Decide List In to the Original Place Where the Child Is This What Is the Final Votes Will Go Here First Will Go To Check meanwhile founder channels on this will be continued here same will get no do n't know the Note 3 will get Note 3 and will sacrifice for the child will go inside the child level in the continued even when will go to right wing should tiger extinct 2011 98100 Have to Come Back 286 Point Note Software will come back to the point in the process of Vitamin B Welcome back to the next point Per Of Three Wishes For Death Will Continue Process 516 This Is What The Answer Share Like This One To Three to 0.5 Went to the To Three to 0.5 Went to the To Three to 0.5 Went to the Child Services 11-12-12 Come Back to the Child Services 11-12-12 Come Back to the Child Services 11-12-12 Come Back to the Center of the President of 90 Will Back to the Point of Subscribe Answer Will Solve This Example Behave Way 30 to Knee's Throat Stationk Software Laxative in the First Baby Don't Have any child point how will oo but beneficial check so will initial is current pointer current point drawn from behind and check your feet is hair style and notification note is side business simply just to the current to the next pure current Vikram hair the current next that And This Will Continue Till Our Current Is Like Cantilever Current Is Not Least To The Final Sworn In S Nominal Hai The Real Hour Me Office Collection President Sudhir 123 Late Channel Herself In The Child From December Month Not Six Exam 100MB Tower Current Affair Will Continue To Be Continued Ther Current Hai The Time Will Start From The Current Child That And Vigor Till Overtime Don't Station Also Find The State Of The Child Sudhir And Child Is Vansh Yudh Tell What Will Develop and tell in all like share the current water will update you don't next loop straight middle and current dot next that in this will change the next and previous pointer of the cone is the current ride point next point is this switch S2 hair current don't like share and child previous notice current and will continue to make this phase new current like this thank you friends welcome to our country with over 1.2 friends welcome to our country with over 1.2 friends welcome to our country with over 1.2 MP three lamp o friend Jeanette how to make has one child which lets f5 and six the five and six in the Dar day at seventy art show ki dekh six let's middle have another child point apna 100th test se zee awards winners name process fast will look for the day i soft will look for detail of the indigenous equal had in the middle level starting from a fall child 111 Disawar Child 211 So What Will U Will Continue Against Corrupt Will Come Here 786 Prints One Straight Lots Of Force Entertain Hair Sudesh List Vikram Warne * 1575 From Chronic 600 Welcome Back * 1575 From Chronic 600 Welcome Back * 1575 From Chronic 600 Welcome Back To Three Lines Floor And Subscribe 9 K Vriksha Will Have Another Child For Internet And Nobody Will Come Here So Friends Welcome Ball Subscribe Lage In Find The Child Idli Swift Of The Year Notes This Notification Finally Bigg Boss To 15 To 20 6680 To Back To Secretary And Back To MP3 To For This Is Our Flat In Delhi After Processing And More than half they can you subscribe button subscribe from chronic renal that and will check gift our dot child on this channel this note child in the assembly update daughter and electronics and continued a message but what is behave child for child will do The Software Will Get 9 Votes From R Current Dots York For Detail And Of The Wild That Tam Don't McGuire Ne Bigg Boss Bear Last Not A Single Soul Not Equal To Null Fennel Bus Update m1213nf Bus Now Dip Mode On Son Will Update The Next To Our current affair setting of the first level for to-do affair setting of the first level for to-do affair setting of the first level for to-do list in between current and daughter will check dot next nine the point of view of water system is 154 Sweden foreign 10 we need to update the current dot max to our current child and monitor That and need to change previous point of the current affairs quiz current.child current affairs quiz current.child current affairs quiz current.child previous point to point note and will update current.child to channel this vansh videos will go back to share and continue look for this soane hindi and will just another original 1999 Subscribe That Nitish Compiled And Were Getting Correct Translate Submit Dissolution That Antiseptic So What Is The Time Complexity Of Processing All The Notes In Each And Every Level Water Works Of Right Now Hindus For Example Which Have Three 500 600 Processing Problems Oye Give You Have and noded in the time complexity is form of an and what is the space complexity effective yr like using the reference point is not any data structure and nothing baby no differences over the space complexities co of one member very easy solution if you think Little but you can easily more or less solution fuel no basics of the year english like and international solid like my solution class hit the like button and subscribe the channel try destruction of evil share the code in a gift for installation in this is very easy dustbin tum Basically Let Me Explain Your Bit About Distraction Shift Solution What We Will Do Soul You In The Same Exam Palat Se One To Three Lines For Internal Exam Child Will Start From It's A Five To 1000 89 Suv Virvar Will Going Deeper And Came Back To Do not develop infection in daughter will come and the river and should take refuge in you will ever since the last of that witch state will interact with max in our least 100 hair in for example will set 3939 values ​​and move to the find any process values ​​and move to the find any process values ​​and move to the find any process 5606 यौवन 100 MB टो 1MB वाशिष्ठ 90 युवन 100 MB टो 1MB वाशिष्ठ 90 उसकी 5606 यौवन 100 MB टो 1MB वाशिष्ठ 90 युवन 100 MB टो 1MB वाशिष्ठ 90 उसकी 5606 यौवन 100 MB टो 1MB वाशिष्ठ 90 युवन 100 MB टो 1MB वाशिष्ठ 90 उसकी चैनल सुस्क्रिबे और इस नेट मप 07 2009 MP3 लंड विल नोट एन प्रोसेस इस फेडर स्कम 2009 MP3 लंड विल नोट एन प्रोसेस इस फेडर स्कम 2009 MP3 लंड विल नोट एन प्रोसेस इस फेडर स्कम विल गेट एक टो ट्री लव विशेष विल गेट एक टो ट्री लव विशेष विल गेट एक टो ट्री लव विशेष 20680 और SUBSCRIBE QUESTION प्रध कोड़ी I will share with you in QUESTION प्रध कोड़ी I will share with you in QUESTION प्रध कोड़ी I will share with you in the great WE REPO RATE IT YOURSELF FIRST AND THANKS FOR WATCHING
Flatten a Multilevel Doubly Linked List
flatten-a-multilevel-doubly-linked-list
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below. Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list. Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`. **Example 1:** **Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\] **Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\] **Explanation:** The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: **Example 2:** **Input:** head = \[1,2,null,3\] **Output:** \[1,3,2\] **Explanation:** The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: **Example 3:** **Input:** head = \[\] **Output:** \[\] **Explanation:** There could be empty list in the input. **Constraints:** * The number of Nodes will not exceed `1000`. * `1 <= Node.val <= 105` **How the multilevel linked list is represented in test cases:** We use the multilevel linked list from **Example 1** above: 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL The serialization of each level is as follows: \[1,2,3,4,5,6,null\] \[7,8,9,10,null\] \[11,12,null\] To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes: \[1, 2, 3, 4, 5, 6, null\] | \[null, null, 7, 8, 9, 10, null\] | \[ null, 11, 12, null\] Merging the serialization of each level and removing trailing nulls we obtain: \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
null
null
Medium
null
1,345
hi guys welcome to algorithms made easy today we will be seeing the question jump game part 4. given an array of integers arr you are initially positioned at the first index and in one step you can jump from the index i to either i plus 1 or i minus 1 or an index j where the value at the index i and j are equal but the indexes are not equal we need to return the minimum number of steps that would lead us to the last index of the array notice that you cannot jump outside of the array at any given time for the first example we can jump from 100 to this 100 then to 404 and to 404 so this gives up one two three that is three jumps so the answer is three for the second example we just have one element which is the start and the end so we do not need to even jump so the answer is zero similarly for the third example 7 is equal to the last element so in one jump we can reach the end index and so are the other examples the hint given here is we need to build a graph of n nodes where nodes are the indices of the array and edges for nodes i are the nodes i plus 1 i minus 1 and where area of i equal to array of j and the second hint states that start vfs from node 0 and keep the distance answer is the distance where you reach the node n minus 1. so now let's see how we can solve this question okay so the first example if we create a map with key as the number present and the value as the index in which it is present we would get this kind of a map so the key is 100 and value part which would give us the indexes where this value is found so that whenever we want to jump we can see that okay so at the fourth index also we have hundred so we can even jump to the fourth index two apart from going to i minus one and i plus one so now with that we'll take a queue wherein we will store the elements that we are going to process at each step since we are positioned at index 0 will add 0 in the queue and the steps would be 0 as we have not taken any of these steps till now from here we can go to different places so we need to process all the possible jumps from this node in the queue and then add the subsequent index in the queue and return the steps once we have encountered the jump to last index to state all the possible jumps at each step i'll be marking with this vertical line over here so starting is zero from here we can jump to some other steps so now in the first step where we can jump to index minus 1 index plus 1 or the values in map which gives us index minus 1 which is minus 1 index plus 1 which is 1 and the values in map 0 and 4 so 0 is the current index and fourth one is this 100. from these minus 1 and 0 are not reachable and we can just reach to one and four so we put these in the queue and now this marks the end of the positions we can reach in the first step now since we have already processed this hundred we will be removing the 100 from our maps so that we do not process this again because there will be cases where we can get a tle if we keep the processed index in map for example if all these are hundreds we'll keep on processing the i minus 1 i plus 1 and every other index multiple number of times and we'll get a tle so for that reason we are just removing this from our map now with this we know that in the first step we can reach to 1 and 4. now in the next step where we can reach so we will be popping an element out of the queue and calculating the jumps from that particular index so for that since we are calculating the second step we do step equal to step plus 1 and we find the steps from the first index which is minus 23 we can go to 0 or 2 or 1 but 0 and 1 are not reachable so we will add 2 in the queue now we will again remove -23 from our now we will again remove -23 from our now we will again remove -23 from our map next we'll go to fourth index so from 4th index we can go true minus 1 plus 1 and we could have also gone to index 0 but since 100 is not present in the map we would not be going to 100 or index 0 since it is already removed from the map so here we'll add 5 and 3 in our queue now since we have already got the places where we can jump in step 2 we are going to find where we will be ending up in step 3 so we do a step plus and we start processing our indexes from 2 we can reach to 3 so we add 3 from 5 we can reach to 6 and 7 so we add these two and from 3 we can reach to 9. now here we can see that 9 is indeed our last index and so here we'll be returning 3 which is minimum steps that we would be needing to reach the index 9 or the last index so we return 3 that's all about the theory part now let's start coding this okay so in the start we will take a variable n that would store array.length and if this n array.length and if this n array.length and if this n is 1 we would return 0 which is our base case for example 2. with this will take a map this map will contain integer and a list and will take a step which would give us 0. finally we are going to return step so we'll write this also over here now first step is fill the map so we take a for loop in this for loop we would add values in map so we would be using the function compute if absent what this function is doing is it sees if arrow phi is present or not if it is not present so it would create a new arrow list and if it is already present we would add index in it so this will give us the map next what we need is we would need a queue in this queue we would add our first index which is 0 and then we would loop while this queue is not empty so while this queue is not empty first step we do is we increment our steps as we are finding the jump to a next index so we do a step plus and we'll take the size at this point of time so psi is equal to q dot size now for each element in this queue for this particular size we would be running a loop so here and i equal to 0 i less than size i plus so here we are going to perform three steps that is jump to j minus 1 jump to j plus 1 and jump to an index k wherein array of j is equal to array of k so this we are going to get from the map the very first step in this for loop is getting the element from the queue on which we will be performing the operations that is finding the next jump so that would be j okay so now we would check if this j minus 1 is greater than 0 because we do not want to cross the bounds so if j minus 1 is greater than equal to 0 and map contains this element map dot contains key array of j minus 1 then only we'll perform the operations so we add this in the q similarly if j plus 1 is less than n and if that is there in the map then there can be two conditions either this j plus 1 is equal to the last element so we check that to j plus 1 is equal to n minus 1 if that is the case return steps or else add in q now the third is the one that we will be taking from the map so here if this map contains if this particular element is not processed we iterate over each k in this we first check if k is not equal to j because the position should not be equal to the same position on which we are there if that is the case we can see check if k is equal to n minus 1 return step otherwise put it in the queue after we are done processing all the reconditions we will remove this from the map so that's all let's run this code and we are getting a right result let's try for other test cases also that's it we are getting the right result let's submit this code and there it got submitted the time complexity of this code is o of n the space complexity also is o of n so thanks for watching our video see you in the next one
Jump Game IV
perform-string-shifts
Given an array of integers `arr`, you are initially positioned at the first index of the array. In one step you can jump from index `i` to index: * `i + 1` where: `i + 1 < arr.length`. * `i - 1` where: `i - 1 >= 0`. * `j` where: `arr[i] == arr[j]` and `i != j`. Return _the minimum number of steps_ to reach the **last index** of the array. Notice that you can not jump outside of the array at any time. **Example 1:** **Input:** arr = \[100,-23,-23,404,100,23,23,23,3,404\] **Output:** 3 **Explanation:** You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array. **Example 2:** **Input:** arr = \[7\] **Output:** 0 **Explanation:** Start index is the last index. You do not need to jump. **Example 3:** **Input:** arr = \[7,6,9,6,9,6,9,7\] **Output:** 1 **Explanation:** You can jump directly from index 0 to index 7 which is last index of the array. **Constraints:** * `1 <= arr.length <= 5 * 104` * `-108 <= arr[i] <= 108`
Intuitively performing all shift operations is acceptable due to the constraints. You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once.
Array,Math,String
Easy
null
305
hey hello there so today I'm talking about questions 305 number islands - about questions 305 number islands - about questions 305 number islands - which can be vulnerable to the question 200 number of islands since this is I guess the precursor question to that one gonna really quickly summarize what this question is about we have a 2d grid where the values inside the squared R 0 M ones and the 0 means water one means land the land can connect with each other piece of land where the four directional moves if they are adjacent with each other in that respect we can connect the lands to former island we won't count the number of islands so if we look at this question from the graph kind of a perspective the notes here are the individual little piece of land the edges are the four directional move connections if two lands are connected if we have this move the there is an edge connecting those two corresponding nodes inside this graph so the question of counting the number of islands is basically counting the number of connected components inside this graph so we could solve this by DFS or DFS search with some hashmap dos hosta to store the visited location so it would be a linear time with respect to the number of locations inside this 2d grid and we can also use Union fine to do this because every Union fine is basically we have a set of Penance and we want to partitioning those into some destroying two subsets each disjoint subsets can just be a connected components inside this graph and in the end after we you know producing every the every elements into individual you know just joining subsets we can just counter the number of subsets which is corresponding to the number of aliens corresponding to the number of connected components inside this graph so unifying to solve this to the reason I guess people will usually prefer DFS or BFS is that first is easier to write DFS whoa PFS a second is that Union fine is doing some extra work but it's going to be slightly slower than DFS or BFS just recall that for union find we maintain sizing information about each connected component each subset to do this union by the size or rank that's unnecessary if all we want to do is to count the number of connected components the sizing information is useless in the end and so it's just going to be slower than DFS or BFS slightly but the good thing is that for union find we can perform this Union one at a time and so that makes it adaptable to become an online algorithm so the we don't have to have the entirety of the to degrade upper front we can gradually to grow this you know if the values here are revealed one at a time we can still using Union 540 FS ntfs search it's kind of a one-off thing of a one-off thing of a one-off thing unless we do some serious modification to those two so the follow-up question to those two so the follow-up question to those two so the follow-up question is basically that one is sub 2 that the islands are revealed one at a time so we have a 2d grid we have M rows and n clones this is pretty much useless initially filled with water so zero everywhere we want to perform a Aadland operation which turns water into a land and we have a list of such operations so it could be a sequence or a stream of event and we want to after each event we want to return the number of connected components after each operation so yeah so this for this reason union-find is so this for this reason union-find is so this for this reason union-find is very good for this purpose every when every you know islands is revealed all we need to do is to try to Union it with existing Island land if it's surrounding the new newly revealed one if it's by itself we just add one connected components but by itself if it's able to merge into existing one then we don't add the number but that connected component because one larger and if it just so happened that this land can work as a bridge to connect a union different connected components then we would dig decrement to the number for connecting components inside this graph so we can do constant almost constant type work for each individual revealed land and for each individual query for the total number of connected component at any given time it's going to be almost a linear almost a constant so the total run time would be you know just how many operations are there is going to be how many operations you know some multiply of constant time complexity and multiplied by the total number of operations we have so it's a linear respect to the total number here so let's kind of talk about how all this works basically we're just going to have a totally empty set when there is a new animal come see we just have yourself as a single subset of size 1 and we also remember there's a long island when there is a new island company we also first what we do is to have it myself as a single subset of size 1 and increment the number of islands by 1 so we have 2 and then we search for the 4 directions if we find that there is a subset in that location in the adjacent location we merge this two subsets together and decrement the number of islands by 1 so yeah so after we insert this 1 we find there is a another subset another island here we were Union them together and decrement the count by 1 here we have another new island so it's by itself subset and we incremented number of violence here we find another one so we have yourself by self ss-sorry have yourself by self ss-sorry have yourself by self ss-sorry we have another element here so another note revealed so we yeah so it's by itself a single island very lastly if we can have something like another one here we would try to actually merge all those reading to one single Island and the decrement of the number finally count by 2 so first increase 1 for the initial like insertion and then decrease this by 2 so the total answer if we do have a 1 here would be 2 so that's pretty much how to use Union fine so let's actually just copy my template of our Union file over here I have a note about Union find on my github you can check about that yeah so just gonna use the recursive pass compression find because it's shorter takes less screen space so this is the offline conversion of Union fine we pre allocate the annotation for the parents is basically which connect it's telling us which connected component this node belongs to sort of it's telling you some neighbor and that neighbor knows some neighbor but eventually everyone is just going to have parent to be the cluster the connected component representative later on the size is keeping track of the size of the connected component only the leader the size for the leader is always going to be the current maximum size for the connected component the individual element inside that component might not be the sighting information might not be and in the offline version we initialize this data structure with this n here but since now this is pretty much online question we can just initialize this with two empty - empty initialize this with two empty - empty initialize this with two empty - empty things so for this two things we pretty much just going to annotate the locations around columns if we insert a node here I reveal a land here at as row 0 column 0 we're just gonna say row 0 and Colin 0 it's by itself a single connected component and it has size 1 so the rule and when Colin number is gonna be the key its parent initially it's just gonna be yourself the size is gonna be 1 so yeah we're just going to have the insert function real and Colin and actually get some quality of life changes game this is just not nothing but we will start this totally empty whenever we see a single note here we create a two slots here one slot for its parent a real annotation the other one is for the size about this potentially larger connected component inside this graph so yeah the keys are the real and column pairs initially it's just gonna be yourself so that's insertion whenever we have a new land revealed we first try to do this insert if it's already there we do nothing otherwise we will initialize this to two things and we also need to keep track of the connected components at any given time so initially it's zero whenever we're actually doing cert we want to increment this first and then we will try to do the Union we do have a key keeper here if the two land already belongs to the same connected component we wouldn't do the Union actually otherwise we will try to merge the smaller island into the larger one since that if we do perform a union that means that the two subsets are not a disjoint they will become a single subset that means the number of islands will actually decrement by one so we do you know decrement here so yeah so I think it was this modification we can pretty much solve this question really easily in terms of the actual code inside this solution kind of class yeah so all we need to do is just initialize this data structure and just kind of accepting the reveal of land one at a time so if this is it's already in the we'll try doing sorry first so yeah what weddings are because this has a safety mechanism here if it's already a land that we know we don't do this insertion so right we take a row and column yes after we do the insertion we would try to Union the land with the adjacent for different locations if there is a land there we do want to do that if the adjacent four values are not islands we will just skip that Union possible Union it's going to iterate over four different locations I'm just going to call this ours si if it's not actual island so that's if it's not in a key in other two hashmaps then it must be a water so if it's a water we don't do a union otherwise we'll perform union between this two piece of land so yeah so in the end we're just gonna yeah we this question is not truly online we have to return a sequence of the number of component count so we just gotta have a something to collect that let's just call it non components violence so after we deal with these four unions that means we have processed the potential you know island merge so we can just push this cell to end the Union find or an accounting of the number of the component counting counter onto this stack so in the end we just returned this it will be the solution to this puzzle yeah so let's give it a try nope not working continue is not properly in this loop oh okay I'm so sorry this one should be returned okay seems to work let's try to submit it that's working not super fast but it's okay so if you look up to the code it's pretty simple we initialize this union-find and simple we initialize this union-find and simple we initialize this union-find and in fact we does not care about the SEM and we don't care about this at all if we use union-find so what do we do here we use union-find so what do we do here we use union-find so what do we do here is initialize this union-find data is initialize this union-find data is initialize this union-find data structure which takes nothing we initializing to hashmaps they are totally empty initialize a zero counter counting the number of subsets destroying two subsets for each position we're just gonna create its annotations it's parent it's size and for the four adjacent possible locations we would try if the there is a land we'd fight it to this union and after that we will just update we just push this and the counter directly on to this result so if this is truly a online algorithm you will have a having a function that's called Aadland and so it's just gonna be this thing here this full loop body here be in the init function and this these two things I was just kind of this thing it's just going to be in the in constructor so yeah so you will be I if you look at the individual operations here we do for every new review of Al and it's a constant time operation here to do the insertion I just created two key value pair and increment this so that's all the insertion is to us it's constant and the Union here we know that it's almost a constant and then we just do four multiply of times of that so it could be consider like in constant time so this is indeed the number of elements inside this x is some relatively constant to stuff so it's a linear in time and a four space we the stuff we have is two hashmaps that grows linearly with the number of nodes that normal and we've been revealed in here so yeah so it's a linear time linear space solution using Union fine and the body here is pretty clear and that the modification to the Union fine template code is very little and it's very intuitive making sense you know when we reveal a single Ireland as by yourself a subset and when we reveal a new land we will try to look around to see if we can actually merge to set so it's very logical here yeah so that's the question today
Number of Islands II
number-of-islands-ii
You are given an empty 2D binary grid `grid` of size `m x n`. The grid represents a map where `0`'s represent water and `1`'s represent land. Initially, all the cells of `grid` are water cells (i.e., all the cells are `0`'s). We may perform an add land operation which turns the water at position into a land. You are given an array `positions` where `positions[i] = [ri, ci]` is the position `(ri, ci)` at which we should operate the `ith` operation. Return _an array of integers_ `answer` _where_ `answer[i]` _is the number of islands after turning the cell_ `(ri, ci)` _into a land_. An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. **Example 1:** **Input:** m = 3, n = 3, positions = \[\[0,0\],\[0,1\],\[1,2\],\[2,1\]\] **Output:** \[1,1,2,3\] **Explanation:** Initially, the 2d grid is filled with water. - Operation #1: addLand(0, 0) turns the water at grid\[0\]\[0\] into a land. We have 1 island. - Operation #2: addLand(0, 1) turns the water at grid\[0\]\[1\] into a land. We still have 1 island. - Operation #3: addLand(1, 2) turns the water at grid\[1\]\[2\] into a land. We have 2 islands. - Operation #4: addLand(2, 1) turns the water at grid\[2\]\[1\] into a land. We have 3 islands. **Example 2:** **Input:** m = 1, n = 1, positions = \[\[0,0\]\] **Output:** \[1\] **Constraints:** * `1 <= m, n, positions.length <= 104` * `1 <= m * n <= 104` * `positions[i].length == 2` * `0 <= ri < m` * `0 <= ci < n` **Follow up:** Could you solve it in time complexity `O(k log(mn))`, where `k == positions.length`?
null
Array,Union Find
Hard
200,2198
35
we are going to look at a lead called problem called search insert position in this question we are given a nums array and an integer variable target we have to return the index if the target is found else we have to return the index where it would have been present if it was inserted inside the array so in this case the target element is 5 you can find the target element here which is at the second index position because index position starts from 0 inside an array so 5 is at the second index position so you return 2 as the out it is given to us that the array is sorted so 2 should be inserted at the first index position between 1 and 3 so the index position is one right where two has to be inserted so one is out also in this case seven is not present inside the array and the last element present inside the array six which is the maximum element the target element is seven which is greater than six so you return 4 as the output by inserting it at the last index and the last index position is 4. in this case 0 is the target element the input array does not have 0 in it and 0 is the first element present inside the array which is at the 0th index position so it is returned as the output so this question is very similar to the binary search question so we have to perform binary search on this input array and wherever you find the target element you have to return its index and the only change between the binary search question and this question is that in binary search you have to return -1 when binary search you have to return -1 when binary search you have to return -1 when you don't find the target element inside the array here you have to return the index position where it has to be inserted and that index position where the element has to be inserted is present at the left index position i've already posted a video on the binary search question you can take a look at that video where i've explained binary search in the description box below or you can click on the top right corner i card to watch that video first let me show you the code for the binary search here is the code for the binary search question we are declaring an element called middle and we are declaring two pointers left and right left points at the left most part and right points at the rightmost part so in this question left is pointing here at minus 1 and right is pointing here at 12. we are going to iterate through the array until left crosses right find out the middle element here using the formula left plus right minus left by 2 and then we are finding out if the element at the middle index is equal to target we return the index position of mid if the target element is less than the mid element we assign the new index to right that is mid minus 1 so it means that the target element will be only present in the left most part whenever target is less than or equal to mid whenever target is less than mid else which means the target is greater than mid so you assign a new location to left that is mid plus one so that means the target will be present to the right part of the array after minute and here in binary search you return -1 and here in binary search you return -1 and here in binary search you return -1 whenever you don't find the target element but in today's question we have to return the index position left that will give us the place where the target element has to be inserted inside the array so let's code the same thing up and then replace minus one with mid let's start off by creating the mid element now let's declare two pointers left and right left will be pointing at the zeroth index position and right will be pointing at the last index position can be found out by the length num stat length minus one now that we have the two pointers let us start the while loop where the while loop will iterate till left crosses right so left should always be less than or equal to right now let's calculate the mid element mid is equal to left plus right minus left by 2. so whenever you calculate mid using this formula take care of the overflow condition now this is how we have to find out the mid index now let's find out if the element at mid is equal to target if nums of mid is equal to target we return mid as the output and in the lsf block coming to the first condition of the two that either target is less than mid or greater than width let's start off with the scenario where target is less than mid in this case we have to assign the new pointer to the right index position that is right is equal to mid minus 1 and in the else block coming to the second scenario where target is greater than mid we have to assign the new location to left that is mid plus one now finally outside the while loop we have to return the index position left this will give us the index position where the target element has to be inserted so in this case in the binary search question we have returned minus 1 whenever we didn't find that element inside the array here we are returning left that will give us the index position where the target element has to be inserted now let's try to run the code by getting the expected output let's submit the code there you have it our solution has been accepted that's it guys that's the end of the video thank you for watching and i'll see you in the next no one
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
144
all right so welcome back and this is called binary pre-order traversal and called binary pre-order traversal and called binary pre-order traversal and it's question 144 it's an easy uh tree traversal question and we're going to do exactly what it says we're going to traverse the tree in pre-order in pre-order in pre-order or i guess in pre-order and essentially or i guess in pre-order and essentially or i guess in pre-order and essentially what that means on paper is we traverse the current node then the left one and then the right one and so we kind of looked at an example just on google here uh on medium where we're given this tree and we would traverse in the order of the first one which is the current node and we go left and we visit that node and we go left we visit that node we then go the previous node and then here we go right and we go upwards we since there's no more on the left we then go right we visit that node left we visit that node upwards and then right and so unlike in order traversal where you just go as far to the left as possible hit that node upwards hit that node then go right you're actually visiting each one kind of iteratively in that sense that's how i always thought of it is each node that you step on you actually visit rather than for pre-order you just kind rather than for pre-order you just kind rather than for pre-order you just kind of slide down all the way to the bottom and hit it i think it's more like a depth first search kind of sense i'm not i don't know if that's totally accurate maybe this is actually depth first search but um yeah so why don't we go ahead and implement that it's actually a lot easier to implement this than the uh what's the other one called the in order traversal so for this we look at our return value and we're going to once again be returning our output of the values of our nodes in the order that we traverse them and so we take advantage of that's telling us to use the list here so let's go ahead and do that and so this will just be called output once again and it's of type integer and we'll just be returning this at the very end and we'll also be making use of a stack like we do for most of these traversal questions and so we'll just uh this is of type integer or no is of type tree node and so this is going to be what kind of maintains the order of which we're evaluating what we're going to be traversing next and we'll just call this stack and then immediately what we're going to do is we're just going to add our root node to the top of our stack and so in this case we see that if you look at uh pre-order traversal pre-order traversal pre-order traversal number one is the first one that we evaluate so we know that when we're doing this in pre-order the when we're doing this in pre-order the when we're doing this in pre-order the root node is what we evaluate first so we wanna add that to our stack and we're going to quickly pop it off our stack once we hit into our while loop here that we're going to make right here and so just thinking for a second um yeah so we're going to say wow our stack is not empty and so one thing that you might think of and they always have to add for a lot of these algorithms is our the simplest case of what if you have a non-existent tree so non-existent tree so non-existent tree so we're given a array that's just empty braces well we're going to want to check actually before we add this to our stack is we're going to check if our route is actually empty so if this route is null then we're just going to return our output oh i'm selling that all wrong output which will just be an empty array as we're not even populating any values with it yet so this if it gets this far then we know that we have a root okay so what we'll do is in here we're just going to quickly pop it off our stack so we'll have a pointer and we'll just call this current node it'll be equal to whatever we pop off our stack in the base case that's just going to be our root node at first and so what we want to do is just immediately add that value to this array and so that's just like looking at okay we start this node there is a value so we then enter that while loop we'll pop that off our stack and just immediately add it to our output array so we'll say just current node and we just get the value of it and so now that we have the value what we want to do is then go left and right so we would just want to add to our stack it's left and right children and so but we only want to do that if they're not null because then we could get an error where we're trying to say null dot value and then we get you know and this does not exist there or whatever it is so um yes we just do if no dot left or sorry not node not current node is not null then we'll want to add it to our stack so we're going to do the exact same thing but we're actually i kind of messed this up where we actually want to evaluate the right one first and so that's because we kind of add them in reverse order that we're evaluating them and that's simply because well we want our leftmost node at the top of our stack and so that come the next iteration what we're popping off our stack and using next is our leftmost node because it's current left and right okay and i think that's good so let's go ahead and try and run that there might be an error oh i actually just realized what i did wrong so we're going to want to add here the write node right here i'm just adding the current node so we want to fix that and here will be left there we go accepted and success so let's just go ahead and take another peek at this so we're making use of that arraylist as our output we return at the end we really want to check that base case like you normally do where it's okay is this root no if so just return an empty array otherwise we know that it's not null so we're going to add it to our stack and so while that while there's still something in our tree and it's not empty we're going to be evaluating it so we just pop off the first value like we do oh i'll just move it here we look at this value pop it off our stack we look at the next one pop it off for stack unlike in order we don't just go all the way down and then hit or pop off or sec where we hit at the bottom here we're just doing it kind of iteratively each step we want to pop something off our stack and so that makes it simple so we just pop it off for stack we add that value and we just add the right node and then the left node so that the left node is sitting at the top of our stack for when we evaluate it next great so i hope that helped and good luck with the rest of your algorithms thanks
Binary Tree Preorder Traversal
binary-tree-preorder-traversal
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,255,775
1,933
hey YouTube Welcome Back and today we have these problems called check if string is uh decompatible into value equal to substring Value equals substring and it's a new problem just has maybe 80 84 solution for it so it's really a new problem um and the good thing about new problems that you could find these types of problems in the upcoming interviews so we hope that if you got these type of problems you will not be surprised in one of your interviews so the problem say that a value equal to string is a string where all characters are the same for example we have this um four ones and three and two threes the R value equals to string and we have in contrast one two three is not a value equal to string because just they are different so we have one thing which should equals to each other the second thing giving a digit string is the decompose the string into some numbers of consecutive values equal to substring where exactly one substring has length of two so we should have one substrings at least have uh length of two and the remaining should have length of three would it turn true if we satisfy these two um two conditions so if this one is false because we have three ones three zeros three ones and three zeros again and we don't have any there is no substring with length of two this one is true because we have three zeros three ones two ones and three twos this was also it's not true because we have it's not true Justice because if we have three ones four zeros it's only like three and one zero and we have three twos and two three so basically we will have one string more with zero so because of that it would be false so how can we solve this problem is um we could search for um like we could search for one string with two length and we check that every other else is three it's as simple as that so let's just start to dig into it so first of all I want to make a simple base case so if it's of length less than 2 would return false okay this is the first thing um I want to say Okay I want to create account because I want to count the numbers so I'll start from one I wanna have lit tools and this will be false and basically I wanna um own a search on how many tools do we have if we have more than one two this will be true and we will return false and we return tools okay so basically we want to know how much tools we have and we hope that we have only one tool so and I'll tell you how we can just control this one so we Loop through the string so I'll say four lit I equals one okay and we're starting from the one position because we all the time start to make comparisons with characters in each previous value um I less than or equals is the length OE plus um I would say if i s dot link I use if I smaller than s dot length so there is nothing something to continue looking through and the character and s dot character it throw it um I equals is the short and I minus one um okay oh sorry so right now we're doing first of all if we have um if you have if I if we have something to continue looking in and the character of the current character equals its previous so first of all we just increase the count by one and else if it is not the case I will see something else if count um modded by three equals one we return false because that means the count is four it's bigger than three um and basically you're searching any value they have four just we delete we just return false directly and we have if the count ered by three equals two I will say if twos is false if two is true I will make it false okay otherwise tools will be true you can do something different which will be two that will be equals not twos but like this would be um different and look better but this one it's easier to be understood and um and yep and I guess I will say after um after this one count would be equals one because we start over again okay soon I'll just submit and yeah that's it so um that's it I guess the session for this one is pretty easy but you just have to calculate everything and just to have to make it step by step to be easy so that's it this video I hope my social is quite good if you like my content make sure to subscribe and hit notification Bell so you'll never miss a video if you think that one of the sort of message wrong wasn't good make sure to give me a comment to tell me what you didn't like exactly so I can improve my content over and over
Check if String Is Decomposable Into Value-Equal Substrings
number-of-different-integers-in-a-string
A **value-equal** string is a string where **all** characters are the same. * For example, `"1111 "` and `"33 "` are value-equal strings. * In contrast, `"123 "` is not a value-equal string. Given a digit string `s`, decompose the string into some number of **consecutive value-equal** substrings where **exactly one** substring has a **length of** `2` and the remaining substrings have a **length of** `3`. Return `true` _if you can decompose_ `s` _according to the above rules. Otherwise, return_ `false`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "000111000 " **Output:** false **Explanation:** s cannot be decomposed according to the rules because \[ "000 ", "111 ", "000 "\] does not have a substring of length 2. **Example 2:** **Input:** s = "00011111222 " **Output:** true **Explanation:** s can be decomposed into \[ "000 ", "111 ", "11 ", "222 "\]. **Example 3:** **Input:** s = "011100022233 " **Output:** false **Explanation:** s cannot be decomposed according to the rules because of the first '0'. **Constraints:** * `1 <= s.length <= 1000` * `s` consists of only digits `'0'` through `'9'`.
Try to split the string so that each integer is in a different string. Try to remove each integer's leading zeroes and compare the strings to find how many of them are unique.
Hash Table,String
Easy
null
20
using a stack is essential for coding interviews so let's get some practice we're given a string s containing just the round brackets curly braces and square brackets I want to determine if the input string is valid we are going to use a stack it's going to start at empty and when we see an Open Bracket we're just going to put that on the stack we'd see an Open Bracket so we put that on the top since we have a closing bracket is that matching this bracket well yes it is we can pop this element off the stack is that matching with the top yes it is we can pop it off as well pop it off we have nothing left at the end this is valid so we have a stack and a dictionary that Maps the closing bracket to its correct Open Bracket we'll go through each of the characters in the string and say is that character a closing bracket if your stack is empty you need to return false otherwise we'll pop off the stack and make sure your Open Bracket matches if your character was an Open Bracket we just put that on the stack we just need to make sure our stack is empty and then we can return true I can almost guarantee you'll get asked this question so make sure you save the video
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,624
hello guys and welcome back to lead Logics this is the largest substring between two equal characters problem from lead code this is a lead code easy and the number for this is 1624 so in the given problem uh we are having a string s and we have to return the length of the longest substring between two equal characters excluding the two characters and if there is no repeating characters then there uh is uh no substring and we can return minus one and uh if you don't know you might be knowing what a substring but just in case you don't know a substring is a continuous sequence of characters within a string like it is a continuous part of a sub string uh con part of a string taken out from a string like suppose you have a thinging A B C D E F G H so b c d since this is a uh all the uh continuous sequence we take from the string that is called a substring so let's see through examples what the question is telling us so since we have the first example as a and we have to return the longest substance between two equal characters so a and a are equal characters yes so what is the subst in between them so in between them there is no characters so the output is zero because the optimal substring here is an Mt string okay then in the next example we have a b c a so which are the two equal characters in this case a yes A is the equal characters and so what is in between the both the is BC length equal to two so that is the output so the optimal substring is BC here and in the third case there is all the characters are unique there is no repeating characters so we cannot give a possible solution thus we return a minus one okay now let's see how we are going to do this we are going to initialize a variable current and it will be starting from the back of the string like s do length minus one as the maximum length possible or the index whatever you say and then we are going to iterate over all the possible substrings starting with the longest ones and then going toward the shorter one since we are taking the current as the larger then we'll take the substring from zero to the current and we'll go on decreasing that and uh then we'll check for each substring and uh if two equal characters are possible if present then we check the maximum length and then we store or return that so we'll iterate through all the substrings we'll so for the first iteration we'll have the substring a b c and BCA since a is already occurring and BC will be the part so this means that we have reach the possible solution and we'll simply return the length equal to two so let's come to the coding section but before that do like the video share it with your friends and subscribe to the channel do length minus one so I think this is correct we have to initialize with length minus one because otherwise it will give a string index out of bounds and this is a brute for solution which I'm going to give you and uh later in the later part I will also show you the optimized code using a hash map we can use a hashmap to optimize so I will start from not I the loop I will start from s do length minus 1 and I will go till zero IUS okay and then we'll have a in J = to and then we'll have a in J = to and then we'll have a in J = to Z J less than equal to uh this will be S do length minus uh not minus I we can do a plus I here and then it will be justified won't flow out of the string and now we have the I and the JF pointers just let me fix this now all we have to take is the substring or just you need to make sure that the car at I if it is equal to S do G at J since we have the starting and the ending point and if they are same just return the number of uh characters in between so the number of characters in between this are IUS 1 and if you try to calculate this using the in you will still get IUS one and after this you can do a current minus and then uh in case where nothing is getting returned we can return a minus one so let's see if it runs fines fine or not so there has been an error let's see I is greater than Z iusus okay so what's the let Mo this current will be as do L minus one okay m so yes I think you will have to check the J + 1 index with the J index not the J + 1 index with the J index not the J + 1 index with the J index not the a because I we are taking as the current so J plus I you have to check the j+ I index with the J the j+ I index with the J the j+ I index with the J index it took a while for me to check what's the problem so as you can see uh this beats 100% of the users in see uh this beats 100% of the users in see uh this beats 100% of the users in time and passes with a good time complexity and a good memory complexity so let's talk about the time complexity is not actually very optimized the time complexity is O of NQ and the space complex it is O of n o of one because we are not using any extra space so we definitely need to optimize it uh for the uh time because n cube is a solution that the interviewer might not be happy with so I have already tried a hashmap method to solve this you can see this I will just copy it here so this was my earlier submission so we are going all we are going to do is we are going to take a hashmap of characters with integer and we are going to store the occurrence of an element so since we have the first occurrence of an element and if it occurs again in the string anywhere you can check the last occurrence of that particular characters and count the number of uh character in between and simply return the length of that so that is what we are doing we are iterating on the string we are storing the last occurrence of the particular character and the characters in between them till so this is how we are going to solve the optimize you can also get the code in the solutions panel by going into here you can check the intuition approach the complexity the JavaScript Java python C++ jav code the JavaScript Java python C++ jav code the JavaScript Java python C++ jav code and yes do remember me to upload I'm just going to upload the optimized Solutions solution as well to the Sol to this post so I hope you understood the logic thank you for watching the video have a nice day
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
97
hello everyone welcome to coderscam we are second day of june lead code challenge and the problem we are going to cover in this video is interleaving string input given here is three string variables s1 s2 and s3 and we have to return true or false if we can form string three by interleaving string one and string two so what does interleaving mean here is like you can concatenate the substrings of a and b or s1 and s2 like in sequential order but any characters from either from s1 or from s2 so let's understand this problem with an example consider this example where our s1 is apple s2 is strawberry and s3 is combination of these two strings so the given s1 and s2 are this and we have formed s3 by concatenating the substrings from s1 and s2 so now if you see we have app starting with our substring from s1 and then another substring straw from s2 and then le from s1 again and then finishing it off with s2 so this can be substring of any length even a single character and combination of both in sequential order so how are we going to approach this so our brute force approach is going to be we are going to have a result string where we are going to construct all possible concatenation or interleaving of these two input strings and if any of the combination is matching of s3 then we are going to return true so how we are going to do that is we are going to have a variable result in that we are going to construct the string by interleaving these two strings given so for example if we are considering a character from our string yes one then in that case we are going to append this to our result and gonna consider the rest of the word from s1 and the complete word from s2 for our next concatenation same way if suppose we are considering s from our s2 then in that case we'll append s to that and we will consider the rest of s2 and then the rest of s1 for our rest of the string to be constructed in our result so this is going to be a recursive process that is we are going to consider one string and the left will be considered as the second part for concatenation and it will form all possible combination of the words for example here it is gonna take k from the first word and yes from the second word and p from the first word and p from the second word and so on and construct the complete word by considering all the characters in both es1 and s2 same way it can also be constructed as a p and then s t and then goes like p l and then r a and so on same way it can be n number of combination of these two words s one and s two and in this list if any of the combination that matches the s three then in that case our solution is going to return true if not it is going to process all possible combinations and return false and as this is going to do or construct all possible combination of s1 and s2 it is definitely gonna time limit exceed but we are going to understand the code of this brute force in order to move to an optimal solution because we are not going to do much of a change it is going to be the same logic but we are going to implement memorization in that in order to obtain an optimal solution so let's go and understand the code for this brute force approach and then come back to the optimal approach so here is the main method first we have to check the basic condition that if s1 plus s2's length matches the s3 then only it is a valid scenario because we have to consider all the characters from s1 and s2 to construct s3 so we are going to check that first so the first condition if it is not equal to s3's length then straight away we can return false if not we are going to call a recursive function let us name as is enter then i'm going to pass s1 comma 0 comma s2 so here the parameters are nothing but are string one string two and string three and these zeros are nothing but the pointers are index of s1 and index of s2 and here the empty string is our result which is going to be constructed and compared with our s3 so let's write our is inter function so here we are checking as this result is the constructed s3 so we are checking if our result matches our s3 and all the characters in s1 and s2 are also included so here we check whether a result is equal to s3 and i and j is equal to the length of string one and string two which means if the indexes are at the last character of s1 and s2 which means we have considered all the characters for constructing our result so if not we are going to compute our answer so first we are checking if our i is less than s1 dot length which is nothing but we still iterating our string 1 then in that case we are going to compute our answer we are going to call the same function recursively and pass on string 1 comma if we are considering a character from string 1 then we have to construct our rest of the result by considering the rest of the characters from string1 so which means if we consider the character at index i then for the rest of the result we have to consider from i plus 1 and as we have considered this character from s1 s2 will be the same so we simply pause j and result will be added with the character as s1 so s1 dot carrot i so yes if not we are going to perform the same thing for string two that is if we are considering string two's character then in that case our string one is going to be same and string two will be from the rest of the string 2 after considering that particular character at index j so yes and one more thing we are missing here is this answer actually will be having all possible combinations so this in is inter is gonna return true or false for all possible combinations so in that case if any of the case for example your second combination is true then it is gonna compute still gonna compute third and fourth combination in that case it is gonna become false so we are going to check if any one of the case is true then our answer should be true so we are going to perform an or operation which is nothing but even though the next combinations are going to return you false if any of them are true then in that case around the answer is going to stick with true so for that we are going to perform our operation with all the combinations so finally we are going to return a result so yes this is it let's run and try so yes let's submit but this is actually gonna time limit exit so yes it is time limit exceeded so here we are going to optimize the same solution or the same logic using memoization so our previous solution has been time limit exceeded because it has constructed all possible combination of s1 and s2 interleaving so here in this approach we are going to implement memoization to stop concatenating the string if we know that it is not going to be valid anymore so let's understand very simple logic before understanding where we are implementing memorization so here consider the first s3 is actually constructing app from string one and then straw from string to l e from string one and then very from string2 so in this case if you have considered apple completely that is app first and then straw from the second word and then le from the first word so now our pointer i is exactly at the last character of our string one so we don't have any other characters left in the string one to help us construct our result or s3 so in that case the rest of the string has to be constructed only by the characters from s2 because we don't have anything left in s1 so in that case if we have reached i to the end of one string and j at somewhere in the middle of string 2 so we are going to compare the constructed string is actually the first half of our s3 and what is left behind in s3 is actually is what left behind in rest of our string in s2 so if this is matching then in that case we are going to simply return true also consider another s3 which is again the interleaving of string one and string two given here which is the formation of ap from our first word and straw berry from our second word and ple from the first word so in this case we have reached our j at the last character in our s2 so what left here is nothing but the rest of the string in our s1 so both of the cases we are going to return true also in our previous approach we have constructed all possible interleaving of these string 1 and string 2 and then if any of the cases has been true then we assigned it to our answer but here we are going to construct our result or s3 only if we know it is going to be matching s3 if not in halfway if we know it is not going to construct our s3 then we are not going to proceed with that combination so here comes the role of memoization so we are going to maintain a two dimensional array memo of index i and j so this is nothing but index of string one and index of string two so we are going to assign the values like minus one or zero or one so minus one is nothing but we did not cross the index i n j yet and if we cross or if we reached index i and j of string 1 and 2 in that case we will assign the values 0 and 1 so if so far the string is matching then we assign one if not we are saying zero for example let us start constructing a and again we are taking our i is here and our j is here so again i'm adding p and again and adding p so in this case my i is actually going to be at the index 2 same way my j is at index 1 so here memo of 2 comma 1 is actually formed to the string a p s so in that case we are going to check if this app s so far is matching till that index i comma j so yes it is matching abp yes then we are further going to proceed this combination if not if it is not matching apps then we are simply going to drop this and go and try another combination so again for example if it further proceeds with a p s and adds l from our string one in that case it is going to become a p s l and the index is going to be three comma one so three comma 1 will be assigned to 0 because our string is not a p l our string is a p yes so sorry a b p s t but here a b p s l has been formed so in that case we don't really have to for further proceed concatenating this string so we are assigning 0 but m of 2 comma 1 would be having 1 in that case if it is a 1 then we are going to proceed with that combination so this will actually reduce our time to half because we are not going to form concatenation of every possible string instead we are going to proceed with only the valid ones so hope you are understanding this approach and this is actually going to work in the goal of m cross end time complexity where m and n are the length of string one and string two so let's go to the code now so here is a code for our approach to again we have implemented the same logic with a little change so again in our main method we have checked the same basic condition and if it is not returning false we are going to call our recursive function with all s1 s2 and s3 and along with that a memoization so here i have declared a two dimensional array memo and i have filled minus 1 in all indexes so now here comes our inter method is enter method so here as i said i'm gonna check if my i is equal to s1 dot length that is my index of i reached the last character in my s1 in that case s2 rest of the string is equal to s3's rest of the string then we are going to return true so like k is nothing but here is an extra pointer that points at the index of s3 so if the rest of the string in s3 and the rest of the string in s2 matches then true if not false the same way it is applicable to the string two as well if it reached the end of the string two then we are going to compare what is left in the string one and what is left in string three matches so if it is not then we are going to check if our memo is greater than minus 1 because if we did not cross that index then it would be having minus 1 if not we would have assigned the value 0 or 1 so in that case we are checking if it is a 1 then it is a true which means we will further proceed with that combination if not we are simply going to written false so after all this if we are proceeding in that case we are still constructing our s3 and we are actually working on the positive concatenation so here we are checking the same logic that is if the character at s3 match the character at s1 then in that case we are going to consider the character at s1 and we pass on the same values by having i plus 1 and j is going to be the same if not if the character at k i mean like in s3 matches the character at s2 then in that case we're going to consider the character from s2 so j plus 1 but s1 is going to be the same so it's nothing but the same function we called in approach one so if any of the case matched then in that case we are going to assign our answer to true and here comes if the answer is true then we are going to assign one which means it is a positive concatenation we can further proceed if not if the answer is false then in that case we are going to assign it with zero finally written what is in the answer so this is it hope you are understanding this approach let me run and try yes so let's submit yes a solution is accepted and runs in one millisecond so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
Interleaving String
interleaving-string
Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an **interleaving** of `s1` and `s2`. An **interleaving** of two strings `s` and `t` is a configuration where `s` and `t` are divided into `n` and `m` substrings respectively, such that: * `s = s1 + s2 + ... + sn` * `t = t1 + t2 + ... + tm` * `|n - m| <= 1` * The **interleaving** is `s1 + t1 + s2 + t2 + s3 + t3 + ...` or `t1 + s1 + t2 + s2 + t3 + s3 + ...` **Note:** `a + b` is the concatenation of strings `a` and `b`. **Example 1:** **Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbcbcac " **Output:** true **Explanation:** One way to obtain s3 is: Split s1 into s1 = "aa " + "bc " + "c ", and s2 into s2 = "dbbc " + "a ". Interleaving the two splits, we get "aa " + "dbbc " + "bc " + "a " + "c " = "aadbbcbcac ". Since s3 can be obtained by interleaving s1 and s2, we return true. **Example 2:** **Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbbaccc " **Output:** false **Explanation:** Notice how it is impossible to interleave s2 with any other string to obtain s3. **Example 3:** **Input:** s1 = " ", s2 = " ", s3 = " " **Output:** true **Constraints:** * `0 <= s1.length, s2.length <= 100` * `0 <= s3.length <= 200` * `s1`, `s2`, and `s3` consist of lowercase English letters. **Follow up:** Could you solve it using only `O(s2.length)` additional memory space?
null
String,Dynamic Programming
Medium
null
1,814
Hello friends uh welcome to my channel let's have a look at problem 1814 can't Nest parents inner array so this problem actually is essentially the same as lead code 2426 23 40 64 493 Etc so here we still present two methods the first method is a dictionary and a check and the second method is direct cons so first I'll read through the statement to digest the requirement and then we do the analysis and share the code so first let's look at the statement so we are given an array Norms that consists of non-negative integers so we consists of non-negative integers so we consists of non-negative integers so we Define reverse of X as the reverse of the non-negative integer X so here is an the non-negative integer X so here is an the non-negative integer X so here is an example the reverse of venture three is three to one and the reverse of 1 to 0 is 2 1 so ignore the leading zeros a pair of indices i g is nest if it satisfies all of the following conditions so first is that I and G are inbound and I is strictly less than J and secondly this equation holds so it involves two indices so we are required to return the number of Nest pairs of indices since the number can be too large return is modulo 10 to the power 9 plus 7. so here are two examples so in example one so the output is two so in the explanation the two pairs are specified and 0 3 and 1 2. so in example two so the output is four so we're going to analyze the output of example 2 in the analysis part so before we look at the analysis let's also look at the constraints or we may regard them as additional assumptions first is that the length of the nums list is bounded below the one in particular is not empty and bonded above by 10 to the power five so this constant actually defines the problem size so the second constant is on the range of elements in the nums list so with that said we are ready to look at the analysis so as we mentioned actually we now look at this problem or revisit this problem after we're solving a problem 24 26 and there are related problems so here we are going to look at the two methods again so one is the dictionary and check and the other is direct counting so the second method is more specific to this problem itself and the first method is of general purpose so we emphasize this first method so both the two methods actually based on the observation here so this is the main condition so given best Star so copied from the problem statement so this is equivalent to the double star so I will just make some simple Arrangement mathematically so these two are mathematically equivalents however so we are viewpoints changed if we transform from Star to double star the reason is that in double star the two indices I and G are decoupled in the two sides in other words the left hand side involves I only similarly the red handset involves G only so this way actually it enables us to examine the difference list because I call it auxiliary so in other words we can compute the numbers I minus the reverse of this number for each of the elements in nums let me just focus on this ox so first let's look at the direct and check method dictionary and check method so the idea is actually very simple when we do the linear traversal what we are going to do is that we may look at each atom in the aux so it corresponds to an index G right what we want to find is the previous eyes with those can pair with G to form Nest pairs so for this content we just need to use a dictionary so this is very routine so in this regard actually we can regard this problem as an extension of the classic 2.2 sum problem 2.2 sum problem 2.2 sum problem so let's use example two to do an digest so this example two right so if we compute the ox so 30 minus 31 10 minus and then 0 1 that is 1. so similarly 76 minus 67. so in other words if we compute these numbers so at negative 18 and nines so if we look at index 0 so there's no left indices so it comes from zero so if we look at none so to the left there's no net appearing so we get zero so if we look at negative 18 to the left there is 1 negative 18. so there's a good pair so we add one so if we look at the second this index 0 1 2 3 index three so this is negative 18 and to the left there are two negative eight hinges so this contributes to two good pairs so we add two so now if we look at the last index that is index four so to the left there is one um nut that is index at index one so it curves contribute to one good pair so we add one so in total we get four that's the return in example two so this is the first method so now let's first do uh do this coding so then we look at the direct content method so for this we're going to first we introduce a constant so this is not absolutely necessary but we want to make our code modulized so this is 10 to the power 9 plus 7. so actually do not forget to modulo this number so if we do not modulo this number so get a wrong output and then we are going to get the aux first so this is actually very easy so what we are going to do is to use a list comprehension so why then we are going to first change this y to be a string so that we can use the reverse right and then we compute the integer corresponding to this the Reversed string and then so we just for Y in Norms so this gives us the difference list aux and next we can do the for Loop so for this we can initialize a result for the counting and we are also use a dictionary for recording so and then we do the for Loop so for y in X notice that we do not need to track explicitly the indices right so for y in X what we are going to do is to increment the results by to how many y's appear in the previous state of the dictionary that is D gets y so if Y is not a q so we're going to set it to be zero and then we're going to update this dictionary so in other words we get the Press frequency if it's not in the dictionary so we're going to use 0 as default so here we overall we want to add what so that's the for Loop that's the dictionary and check step and then we're going to return a result module that's Capital C so actually in between if we update this result we can do this modular operation so also let's first do a special case check so solution object has a hood let's change the function signature let's check again yeah it passes the first example so now let's look at the generic case oh yeah it passes all the generic cases so here this round answer actually is due to the fact that we forgot to modulo this Capital C the large number so as we mentioned so if you want you can also do the modulo here so let's check again so that's also okay but it's not necessary we'll see so this is the first method so we're going to use dictionary and check so this is actually a general purpose method which can be used to solve a wide variety of problems so for this specific problem here so actually we can use direct content so the reason is that we want to find a nest pairs or good pairs so we still use the auxiliary list so for example two the auxiliary list is given here and then after we get the auxiliary list actually we can do a contour so we can sense the unique value and their corresponding frequencies and then we do the counting right so with just a sum with this kind of expression so for weight in frequencies if we experience than what so for example the ox corresponding to example 2 is given here so negative 18 appears three times and then appears twice so the good pairs so we can so this corresponding to three indices so we can choose any of two so we can choose three choose two that is three right so this is the three and two choose two that is one so three plus one is four so this is the second method so actually for the second method it's very easy to coding so we can actually even use one lamp but let's write some details here so let me change this to be V1 and now let's do the counting so first I'll count um I'll copy this one copy the system and then also I'm going to get a contour so collections the counter so we are going to use this aux so let's copy this directly and then what we are going to do is the return right return the sum so I can use iterator from expression so that is V times V minus 1 divided by 2. this corresponds to choose 2 out of V so for v in D values if we convert to that one so actually this if condition is not in S3 because if V is 1 so this is zero right but let's use this filter so with that set so we finish the second format of solutions so now let's look at a check yeah it passes the first example now let's look at the generic case so the wrong answer let me see whether it's the wrong so again so we want we need to modulo this letter State let's do the check again yeah it passes all the cases so that's important to modulate this C according to the problem requirement so with that said so that's about it for this video uh so here uh we presented uh two solution formats so one is a direct content which is specific to this problem and the other is a dictionary and a check so this method is what we want to emphasize because it's of general purpose so with that said that's it thank you
Count Nice Pairs in an Array
jump-game-vi
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])` Return _the number of nice pairs of indices_. Since that number can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[42,11,1,97\] **Output:** 2 **Explanation:** The two pairs are: - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. **Example 2:** **Input:** nums = \[13,10,35,24,76\] **Output:** 4 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109`
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking.
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
Medium
239,2001
48
to a new problem today so yeah this one has uh attracted my interest um i've just spotted it and i thought i'd do a stream pretty much immediately because i think it's really cool problem so the idea is to rotate a grid uh by 90 degrees clockwise and there's a constraint on here where we are not allowed to allocate another 2d matrix and do the rotation because yeah i guess it's trying to simulate a scenario where you'd have to be really careful with memory allocation and i thought that was quite an interesting problem and um yeah i don't see this as being massively difficult um to be honest because um i think you just have to get your head around how to loop over things um but yeah i haven't completely come up with a solution or anything i've literally um you know stumbled over this a minute ago and uh i thought it'd be an interesting problem so let's uh get going so one thing to notice or one thing that i noticed is that there's a subtle difference between how we would work with an odd numbered grid so a grid with an edge of a length that's an odd number versus that of one that has an even number because here we don't have a center whereas here we do have a center so i think that may give some nuances to how we want to deal with the problem but looking at this example yeah i think um i think it's reasonable so you could so what i was thinking is uh you could just consider if you consider a corner item this 15 for instance um yeah sorry this five um the transformation would be to move it to this corner but in order to do that without holding a grid you have to you effectively have to do every corner in order to complete that transaction you can't just handle one number you have to do the corresponding location everywhere so i think it would be good to create a general purpose function for handling that to say given this position transform the grid by rotating that single cell so i think that would be a good place to start and then the problem becomes well how do we iterate over the cells that we need to transform and you'd only have to iterate over one quadrant and say okay this one pass those into our function those positions and assuming our function works it would perform the tr the transformation and the problem will be solved i think so yeah i think that's a pretty good approach so let's create the function transform oh let's go rotate cell and what we'll do is we'll have the matrix let's copy that and we'll have an x as a number and a y that's a number and this function will transform it essentially so and this is where it gets mathematically interesting actually um i'm just trying to think so if we had this cell the rotation would have to take us to this cell so if we have i guess that would be an index of zero um zero sorry no it would be zero one then it would have to become one um three let's open excel um start your free trial oh really oh that's annoying oh okay that's a bit frustrating but i can't actually edit anything can i oh i can okay so if we have a grid then let's just say one two three four five we'll call that our grid zero so we so let's just say we had two here we wanted to go here um zero one two three four so we have zero one becomes one four becomes oh okay this is interesting because um oh let's not confuse the issue let's go xxx x so that's the transformation so this is interesting because i think the opposite is in many ways easier than this 90 degree rotation because you're always going to be you're going to be the maximum number and minus the number that you're on so we're three here so we're one across from this edge when we're rotating 180 degrees that means we'll be one across from this edge so that's easy to do to calculate this one and the row similarly if you were here let's just say y and y you'd be one across and one down here you're still one across and one down so that's cool but yeah this calculating this one i guess actually it's not that if you think of it in terms of deflection from the corner you're one across and zero down so here you're one across and zero down so yeah if you think about it in terms of being relative to this corner let's zoom in yeah so if you think about x in terms of the position it is relative to this top left corner it's one across zero down and you can apply the same principle here it's one across zero down but rotate it one across zero down so that i think gives us the way that we can solve this problem i think so given a number x and y first of all i think we need the length so we'll go edge then equals number now this should just be number dot length i think zero one two three length is four um so that's fine edge length so i think we can just if i'm right i think we can just assign this matrix directly i think what we're going to need is to store the original value yeah otherwise we'll lose something so we need to go const um original value equals and we'll do number x y so that stores the original value in that location and now i think we just need to assign the values so we're going to overwrite this now and we're going to overwrite let's just for argument's sake think of this top left corner again so we'll assume zero so in this situation what we want to do is overwrite with the value contained here so yeah i think this is fine so what we can do is say well we need to specify this corner in terms of x and y but relative to the y coordinate so yeah so let's think of um let's think of one actually that makes it a bit easier because you've got a deflection so you've got one here so that'll be zero one x do you know what i need to sort of think about yeah so these rows x is actually the second array um yeah it's actually y x i think the way this array is structured we can um just test it actually let's uh so i think this would be the input if we say console.log number console.log number console.log number and we'll go zero um one just to output that value just to see what we get oops matrix my bad yeah so stood out is two yes so the x is actually the second thing so it's kind of row column okay that's a good important clarification so we've got in fact let's change it to row and column so this row and column or this one let's say would equal the maximum y value so that would be edge len minus the column so i'm using the edge length of four in fact edge length minus 1 because it'd be 0 1 2 3 so the edge length is 4 so to get to this position it would be three and then the column is a deflection of one so we deduct by that column value which is one to get the row i think that makes sense and then here getting the column becomes well for argument's sake well we have no deflection here so we're at zero so maybe let's use this four as an example so we're currently in row one therefore we yeah we need to actually use the column so yeah let's just let's do two actually so if we're two we're in row index one so we need to actually take this 14 which is in column index one so i think what we can do is just use the row index here yeah and i think that works next we need to assign this now so assuming this reference is correct we now need to do something else to fill that value because yeah we've just taken the value with this line of code we've just taken the value in this cell and applied it to this one now we need to take the value of this cell and fill it in this one that we've just used to overwrite this value so now we need to calculate how to get to here now i've got a hunch that is going to be something like edge length minus 1 minus the row so if we're here yeah we're basically saying this is zero we're over one cell and if we're talking about 12 for instance as replacing yeah sort of relative to here we want to be relative to this edge so it's edge length minus 1 minus the row and also for the column it works the same and now often with this stuff there's a pattern and um i've got a hunch that this is likely to be very similar to what we need in fact i would hazard a guess that it would be this so this is getting this value so if we consider five and we're trying to get here relative to this five how do we get this value so instead of row we use the column in fact i would say the row yeah that makes sense so if we think about one currently that will be row one but if we're trying to get to ten that would be column one so that makes sense that we would use the column reference as the row reference here because if we're in one we would end up being row one and as for the column this would be edge length minus one so that would be three which would be this column minus the row which makes sense because if we were row two we would want to come in by however many rows down we are so i think that adds up so now the final step would be to overwrite this value with the value that we stored earlier and let's just put some semicolons and i think that is a now a function that will rotate a cell so when we call this with a given row and column so say 0 just for argument's sake when we've got zero we take well we store it first then we overwrite the value of zero with the value of edge length which is four minus one which is three minus zero so row three just this row three and then the column will be the original row so zero so that's correct we will then overwrite this value with this value which will be edge length minus one minus zero which is three and this is also three so that's three and then we will overwrite this with this value which is column zero um which if you remember is the row thing so that's um so that's row zero and the column is four minus one minus zero which is three so that's this value so yeah we overwrite this value the 5 with the 15 the 16 with the 15 sorry the 16 overwrites the 15 the 11 overwrites the 16 and then we get the original value which was the 5 which overwrites the 11 again and um yeah i think because we're doing it in this manner we're calculating the relative positions of the items um you know relative to the position of what was passed in we can actually now just call this rotate cell function on any cell and it will rotate the four corresponding cells so now the problem we have to solve is what do we iterate over so i think what we just need to do is iterate over a quadrant now something that occurs to me is um what you do with an odd well we just need to make sure that we iterate over the correct block because if you see you've got these um these sections that seem to sort of correspond with each other so if you rotate those so if you iterate over these call our function for each of these that should actually solve the problem so yeah i think we're good we just need to make sure that we iterate properly the only other thing is if we have an even number what do we do then yeah what do we do then so we it's essentially the same except for an odd number we just have this extra little bit here and we completely ignore the center so i think we can do this no problem so again i think we need the edge length kind of crucial and in terms of iterating we're going to need two loops let row equal zero now then let's think const rows equals edge len divided by two now if let's go back to our diagram so the number of rows we need to iterate over given a length of 5 is 2. so when we divide by 2 we need to truncate the decimal point because 5 divided by 2 is 2.5 because 5 divided by 2 is 2.5 because 5 divided by 2 is 2.5 2.5 uh oh well that's not showing us 2.5 2.5 uh oh well that's not showing us 2.5 2.5 uh oh well that's not showing us 2.5 but 2.5 um 2.5 um 2.5 um therefore we need to just round down so we can do math dot floor and this gives us the number of rows we need to iterate over let's row equals zero row is less than rows and we do row plus so that's going to iterate over the rows that we need and now we need to do the same thing but for columns i'm already kind of thinking what this is likely to need i'm thinking this is going to need this function i spelt that right now yeah it's fine because the difference is with the number of columns we're going to round up because five length of five we're going to have three now the brilliant thing with this is this rather elegantly handles the case of an even number as well so 4 length of 4 divided by 2 equals 2 which if you take the floor of two is two similarly if you take the ceiling of two it's also two so i think this solves the issue um so now we just need to make sure that we iterate uh over it and we'll say coal equals zero coal is less than coals and coal and um we'll call rotate cell and we will pass in the matrix the row and the col and in theory this should do it let's try let's run the code wow first time that's amazing i'm even impressed myself so i did quite thoroughly check it to be fair so now we'll submit it and see if that catches all of the cases the possibilities and if it done it does then fantastic look at that so yeah i'm pretty pleased with that excellent um reasonably fast and uh yeah that's a good solution so yeah if you enjoyed watching this then um if you found it educational or just enjoyable then i would really appreciate a uh if you subscribed um so i'm the random coder and uh that's it for today thank you
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
46
hey yo what's up my little coders let's solve today they literally question 46 permutations basically given a collection of distinct integers return all possible permutations i will not lie it's quite challenging but it's a very interesting problem and it's very useful to know how to solve it um let's let me show you how we're going to do it so to store our result value which we're going to return in the end let's have the linked list of lists or linked list of array lists so let's declare it probably let's just call it result and yes you go to the new linked list of lists and probably somewhere in the end we are going to return it once we do all our permutations and we find them um let's defer another variable to keep track was the current size of the result but for now it's just the empty length list right so let's add our first new release inside just the empty one nothing special okay we add the empty r list now let's do some proper stuff let's iterate uh through all the numbers uh from the input array so okay we're iterating um okay now let's check what's the current result size and while this we have some elements inside right so while our size is greater than zero of course somewhere in the end we will need to do earth size minus otherwise we will never escape from this level so about this condition applies we are going to use one very nice function which the linked list has and this function is called pull first so it basically just removes the first element from the linked list or basically removes the head of the link list uh and elsa we will remove it we'll also store it and we'll call it permutation so which is just result dot oh first very useful function okay we took the head so remember initially we just added the empty release right we took the head and right now we are going to iterate through all the elements from this permutation and remember we just added an empty release so there are no elements there at the moment so it just empty right that's why we need to do ios for recording permutation dot size and i plus so we're starting we start our iteration okay there's nothing initially inside the permutation however we need another permutation we need a new permutation okay it will start to make sense very soon guys don't worry so we declare a new permutation and basically this new permutation is just the copy of this permutation so we put we create the copy of the permutation okay again guys it initially was just you know empty released we took it from the result right so result doesn't have any of ours right now at all we took it from the result and we create a new permutation okay why do we need this new permutation we need it because we are going to add the values to this new permutation so basically what we are going to do is you will take you know imagine that's the input array we take first number from the input array right we took the first value then you know we just added ours out we add this value to our result then we're going for the next iteration right we're taking the next number two you're creating a new permutation you know so we are taking just this error list which has only one number and then like well do while we are iterating so i is less or equal than one so we will go like you know twice so when on the first iteration is equal then zero is equal to zero we just you know add a num to a specific index so index i so and the number is equal to two so initially we just add two in the beginning then the next iteration we add uh two on index one because i becomes equal to one the next iteration and you know and we add this to permutation to the result and then we are we will go on the next iteration we will consider number three and we will just you know add three to all the possible places basically system output print ln and that's how we are going to solve this task guys so just new you know so the first permutation then you know uh then the second one and then you know we add number three to all the possible places and then in the end we get all our permutations so we stop you know we solve the sub problems and then we solve the main problem while we are iterating uh simply as that guys so a very interesting problem in my opinion a little question 46 we got a very good results we solve this question however it's not them guys i will ask you to do homework guys so i show you how to do this question uh iteratively now you're tasked to do this question recursively so if you have any questions please write in the comments below but try to do this question recursively yourself and you will become a very good lead holder if you will manage to do it okay thank you guys thanks for watching please subscribe this channel and see you later
Permutations
permutations
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Example 2:** **Input:** nums = \[0,1\] **Output:** \[\[0,1\],\[1,0\]\] **Example 3:** **Input:** nums = \[1\] **Output:** \[\[1\]\] **Constraints:** * `1 <= nums.length <= 6` * `-10 <= nums[i] <= 10` * All the integers of `nums` are **unique**.
null
Array,Backtracking
Medium
31,47,60,77
334
are you stuck on a coding challenge don't worry code Crusader have got your back let's dive in and solve the increasing triplet sequence problem together the problem is to find if there exists a triplet of increasing numbers in the input array nums the solution starts by initializing two variables first and second with int underscore Max is a predefined constant in C plus which represents the maximum value that an invariable can take this is done to ensure that the first and second smallest elements seen so far will always be less than int underscore Max then it iterates through the array using a for Loop within the loop it checks if the current element nums I is greater than the current value of second it means that it has found a triplet where the first element is the smallest the second element is the second smallest and the third element is greater than the second element so it returns true if the current element nums of I is greater than the current value of first and less than the current value of second it means that the current element is greater than the smallest element seen so far but less than the second smallest element seen so far so it updates the value of second to the current element nums of I if the current element num's I is less than the current value of first it means that the current element is the smallest element seen so far so it updates the value of first to the current element num's I if the for Loop completes it means that the solution has not found any increasing triplet so it returns false so the given solution is trying to find if there exists a triplet of increasing numbers in the input array nums the solution iterates through the array only once and uses two variables first and second to keep track of the smallest and second smallest elements seen so far for example if the input array is 1 2 3 4 5 the solution would initialize the first variable with int underscore Max and second variable with int underscore Max as it iterates through the array it updates the values of first and second as when it encounters the first element one it updates the value of first to one when it encounters the second element too it updates the value of second to two when it encounters the third element three it finds that three is greater than two the current value of second which means that it has found the triplet one two three and returns true let us take another example if the input array is 5 4 3 2 1 the solution would initialize the first and second variables with int underscore Max as it iterates through the array it updates the values of first and second as when it encounters the first element 5 it updates the value of first to five when it encounters the second element four it updates the value of first to four when it encounters the third element three it updates the value of first to three when it encounters the fourth element 2 it updates the value of first to two when it encounters The Fifth Element one it updates the value of first to one as it reaches the end of the array it has not found any increasing triplet so it returns false now coming to the complexities of the solution the time complexity of this solution is Big O N because it iterates through the array only once and the space complexity is big o1 as it uses only constant number of variables thanks for following along I appreciate your attention and I hope you found that explanation helpful if you found this video helpful make sure to hit the like button leave a comment and subscribe for more content like this
Increasing Triplet Subsequence
increasing-triplet-subsequence
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** true **Explanation:** Any triplet where i < j < k is valid. **Example 2:** **Input:** nums = \[5,4,3,2,1\] **Output:** false **Explanation:** No triplet exists. **Example 3:** **Input:** nums = \[2,1,5,0,4,6\] **Output:** true **Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6. **Constraints:** * `1 <= nums.length <= 5 * 105` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
null
Array,Greedy
Medium
300,2122,2280
143
to solve the problem 143 reorder lists this is a popular single unless problem so for the input there is a given a singly linked list and for the output we have to reorder it to this pattern so for example 1 there is a given 1 2 3 4 we have to reorder 2 1 4 2 3 and another example 2 given 1 2 3 4 5 we have to reorder 1 5 2 4 3 so first of all I'm going to use a start to solve this problem and in these questions is say you may not modify the values in the list notes when you noticed all may be chains so I'm going to create the variable annuity which is ahead and I'm going to create the wire so we have a stack with that number here once I've done that I wanted to create a loop which is the I position going left to right and I 1 also wanted to create the variable call R which is going from right to left ok so inside of for loop I have to put I have to make a reorder in this pattern so I'll say the stock up I put some next is stuck up our because after I next we're not putting number two we have to put five so that's what our is here they start from number five so of I plus one because after this we have to put number two so which is I plus one - and this is for loop and we plus one - and this is for loop and we plus one - and this is for loop and we keep repeating that pattern until we make it this reorder list so let's keep going so after next stack up I next stack of our so it's four right remember our is stuck up length minus one minus I so it's going already going from five four three two one parent so three one five two four is four and then after next is I plus 1 which is 3 and I plus one after that stuck up I next things are so it's also three so I cannot keep putting the number here so I have to create if statement to break off from this for look so I'll say if Arliss great oh no I is greater than or equal to R then stuck up I next this no it's not a stack of our anymore and then I'm going to break off from this root so I partition our posture in this case is the same so to break up from this room so I think that's it so I'm gonna run the code okay that's scepter and then I'm gonna submit okay so yes so I use a stack and that's if for this problem
Reorder List
reorder-list
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[1,4,2,3\] **Example 2:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,5,2,4,3\] **Constraints:** * The number of nodes in the list is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 1000`
null
Linked List,Two Pointers,Stack,Recursion
Medium
2216
901
hello everyone and welcome back today we have 901 online stock span it says here to design an algorithm that collects daily price quotes for some stock and return the span of that Stock's price for the current day and this span is defined below where the span of a Stock's price in one day is the maximum number of consecutive days starting from that same day and going backwards for which the stock price was less than or equal to the price of that day so for example if the prices of the stock in the last 4 days is 7212 and the price of the stock today is two then uh the San of today is four because starting from today so today would be the fifth value here the price of the stock was less than or equal to two for four consecutive days so 2 1 2 and then the current day two four consecutive days also if the prices of the stock in the last 4 days is 73412 and the price of the stock today is eight then the span of today is three because starting from today and that's once again the fifth value here in this example uh then the span of today is three because the starting from today 8 the price of the stock was less than or equal to 8 for three consecutive days so starting from today with value 8 yesterday two and the day before one three consecutive days and the implementation is here where we have an init and we have a next function which Returns the span as an integer of the stocks price given that today's price is price all right so I thought we'd start uh we will go through this exact example but I thought we'd start by examining our prices so these are the prices from the first example and the idea we want to use is a stack where the stack will actually be intended to have the highest numbers here so let's say there's some high number here and then uh next highest here and then if there's ever a lower number which follows another higher number then this will somehow know that it has some number of lower numbers uh below it so the idea is each stack item will be the value of that current date price so the price on the current day and uh this will also have the span for that day which will always be at least one to represent the current day and any of the previous days so if a lower day let's say this was some lower number and this is span had a two then the next value would consume that to and it will be uh 1 + 2 which will be uh 1 + 2 which will be uh 1 + 2 which will be 3 okay and we'll go through a concrete example here so these are our days left to right this is our first day we can initialize our stack as being empty uh here we go so we have our empty stack and we can add 100 now 100 uh has itself as the span and the stack is cly empty so we can continue we're done with the 100 next day we have an 80 all right so we know that this is at least the one to represent itself and do we have anything at the top of the stack which is smaller than or equal to 80 so that we can consume it too in this instance we do not so that's okay we add the 80 and we add the span which is one for itself all right next up we have 60 is at least one to represent itself at the top of the stack do we have anything that's less than or equal to 60 we do not and that's okay so let's add 60 and the one all right we're done with 60 now it's interesting we're at 70 which yes it starts at one to represent itself doesn't have anything at the top of the Stag Which is less than or equal to itself it does we have a 60 over here so we can actually consume its one value so let's remove this guy add it to our result and then next at the top of the stack is 80 which is not less than or equal to 70 so that's okay that guy can say let's add our Sol our value is 70 and then we add our span which is two we're done with 70 now we're at 60 again 60 at the top of the stat value is not less than or equal to 60 that's okay so we add just ourself which is 60 and 1 all right 75 we do have something at the top of the stack 60 so we can consume this guy right so we have 1 + 1 consume this guy right so we have 1 + 1 consume this guy right so we have 1 + 1 that becomes 2 now this is popped off but look there's another one 70 is also less than or equal to 75 so we can consume it two and the reason we're consuming it two is because this already consumed this so we're essentially consuming both but we're doing it through this all right so now this becomes four okay and so now the next value and we can pop this guy up the next value is 80 which is not less than or equal to 75 so that's okay these three are gone represented here we can add ourself which is 75 and a four all right and then finally we're at 85 now 85 is uh has a value Which is less than or equal to itself so let's first consume it's four okay so now this becomes five and then we can pop that guy off these are already popped off and then next at the top of the stack is 80 which is also less than or equal to the current day price so we can consume its value and make that a six and here we have 1 246 which is 1 246 that's basically what we have and uh if we look here uh it's basically the same so we have some value uh we initialize it empty we have an empty stack then we have 100 for the next price we returned a one to represent itself and then we had an 80 and then we turned one to again represent itself and then 60 and return one because there's only one value Which is less than or equal to it from today and that's today only and here we consume this guy so we have two and 60 we have itself 1 75 we have four because we have today and yesterday day before and the day before that so that's a four and then finally for 85 this is larger than or equal to the current day plus this and this logic is pretty much represented here all right so let's translate this into code and the way we can do that is first of all what did we have we had a stack which we implemented as an array and then whenever we get a price uh the first thing we have is some number of days we're looking for the span so let's say days to represent the span it's always going to be at least one to represent the current day and while we do have a stack if it's empty that's okay if it's the first value then we just have the current day but if the stack is not empty and whatever is at the top of the stack which in the array implementation is the last value if it's and remember this is a tuple uh it's a tuple of the value in the days or the day span okay now if its values value which is at zero with index if that is ever less than or equal to the current days price then what we want to do is consume its span into ourselves so we'll increment our days by whatever is at the top of the stat and we want its Day spin which is at 1 and index okay and we'll continue to do that uh until we get all the values Which is less than or equal to us and after that we can say all right now it's our turn to get into the stack so self. stack. aend and what we're pending is our current price along with our current day span so days and then once we have this make sure to uh return the int of the number of days uh which spans the current days price and then all the days prior consecutively which has a price which is equal to or less than the current days price so return days and yeah I mean that's pretty much it so let's try running do we have any mistakes okay we do which is not callable right so self. stock is uh not callable so let's remove that do I have that anywhere else let's run oh hold on Sone stack okay so we have the stack um oh I see what I was trying to do I was trying to pop it off the stack and then once I pop it off I get this T from this twool I want the one index which is the day span okay that should work all right and let's submit okay there we have it this is once again a 901 online stock span where the main idea we're using is a stack where if you notice uh all the higher numbers are on the bottom and we keep adding to it if we ever encounter a number which is higher than the number prior then we keep eating it and then we can uh carry it forward thanks so much happy coding see you next time
Online Stock Span
advantage-shuffle
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day. The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. * For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days. * Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days. Implement the `StockSpanner` class: * `StockSpanner()` Initializes the object of the class. * `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`. **Example 1:** **Input** \[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\] \[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\] **Output** \[null, 1, 1, 1, 2, 1, 4, 6\] **Explanation** StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6 **Constraints:** * `1 <= price <= 105` * At most `104` calls will be made to `next`.
null
Array,Greedy,Sorting
Medium
null
701
hi everyone welcome to my channel let's solve the problem insert into a binary search tree so binary search tree is a very famous data structure in the in terms of interviews problem as well as the very like standard applications so we should know that the basic operations in binary sashi like insert a node delete a node and search a node so i have already video on delete and search if you haven't solved them that try also so let's solve this problem so in this problem given a root node of the binary search tree and the value and that value we need to add in our binary search tree and it is also given that all the nodes in our binary search tree is unique value and the value which we need to add which is not already present in our binary search so if you are not familiar with binary search t so let me just give you some clue so in binary search tree follow the property all the nodes of the right sub tree this is our right subtree value greater than the root value and all the node on the left sub t this is our f sub tree of the four is less than or equals to the root so now let's say we need to add the node 5 so we will first compare with the root node and if it is based on this if it is less than we will go to the left subtree if it is greater than we will go to the right sub tree so the currently 5 is greater than 4 then we will look for the right subtree so right subtree is exist and we will again compare with the 7 then it is go to the left and left subtree doesn't exist over here then we will add the new node over here so let's say if we need to add 8 then we will go again the same right step and here the right we will add 8 now if we want to add minus 1 then we will go to the left subtree as minus 1 is less than 4 and minus 1 is also less than 2 and minus 1 is also less than 1 so it will go to a and there is no left here so we will add the new node minus 1 over here so this is the basic approach and it's like if you got the idea it's like very easy to implement recursively so let's implement it recursively first so we will check first if root is not exist null then we will return the new node new tree node basically the node of that value and this should be node and also we will check if root dot well is greater than well then it means our node value will be exist in the left side so we will do root dot left is will be root dot left which will uh insert into bst from root dot left and the value also and the last case like else it will be on the right subtree then we will write root dot write insert into value root dot write value and in the end we will return the original root node which is we have to result so let's compile the code and see if it is compile i am getting success for the test case yes this is so if we submit this let's see so it is accepted so now what is the time complexity of this solution is the height of the tree and the space complexity is constant plus the recursion stack whatever so we can also implement this as iterative solution so for iterative what we will do we will run first copy that tree node into a current and keep the root node as it is from the root node now we will run our infinity loop while true and look for the place for the new node we need to add then we will compare first if root dot val is less than the value so this means this will go to the right sub tree then in right we will check if root uh instead of root we should use the current not the root over if current dot write not equals to null then we will update our current with the current dot right otherwise else we will add current dot write is equals to new tree node of l and then break this infinity loop over here or the second case can it be on the left side so for left subtree we will do the same condition in the left for the left node current dot left not equals to null then current dot current is equals to current dot left else current dot left is equal to new tree node of l and break this infinity loop so this is the iterative solution so let's compile the code and see if it is working so code is compiling and getting success let's submit the code and it is accepted the time complexity of additive solution is also same and the space complexity is here straightforward constant so if you like my solution hit the like button and subscribe to my channel thanks for watching
Insert into a Binary Search Tree
insert-into-a-binary-search-tree
You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return _the root node of the BST after the insertion_. It is **guaranteed** that the new value does not exist in the original BST. **Notice** that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return **any of them**. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[4,2,7,1,3,5\] **Explanation:** Another accepted tree is: **Example 2:** **Input:** root = \[40,20,60,10,30,50,70\], val = 25 **Output:** \[40,20,60,10,30,50,70,null,null,25\] **Example 3:** **Input:** root = \[4,2,7,1,3,null,null,null,null,null,null\], val = 5 **Output:** \[4,2,7,1,3,5\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-108 <= Node.val <= 108` * All the values `Node.val` are **unique**. * `-108 <= val <= 108` * It's **guaranteed** that `val` does not exist in the original BST.
null
null
Medium
null
1,237
hi everyone so let's talk about finding positive integer solution for a given equation so uh basically you definitely need to know like you have to input and then the input is basically based on the z so if that is equal then you just have to put it into the list right so you are given a function id so which is custom function so you need to give two input based on the x and y so x and y is between one and one thousands then you are giving the integer z and find the possibility of how many peers you can generate based on the input right so uh i'm going to just quickly just draw a diagram and then and see so x equal to one y equal to one thousand right and then you just increment your x and give them a y right uh this is pretty much a solution so um for every single time i would have to uh use a customer function so c dot f right you have a function f right and then you pass in uh x and y and if that's equal to z then you just add the two integer into the list of this right and if this is less than uh which mean which means you have to implement your lower value which is x right so and then if this is greater then uh this thing like y is too big because y starting from 1 000 so y just people and this is going to be pretty much a solution so let me just start holding it and then maybe you understand quickly so list of things and list of lists of integer right so i'm going to resort new arraylist i'm going to return result i need to generate x 1 y 2 1000 right so uh based on the input so this is the input and then we will just try first so while x is less than equal to one thousands and also y is greater than one right so uh once increment until one thousand the other one decrement until one and then you just have to say okay what's the current value for the custom function dot f x and y right so if a value is actually equal to z so i can just say result i and then arraylist and now passing x and y into the list of lists right so this is generate a new release and then you need uh you will have to uh input for the release so you just add into the result then without moving that then we have to implement our deployment of y right so lc x sorry val is less than v so what does that lesson believe mean so x is too small so just basically from your x and then the other way is going to be greater so you can say else it's a val it's greater than v right but this is only the last case i'm going to use else so just white and this is going to be the solution so let me run it all right let's talk about time and space so for the space it's going to you're going to have um peers right so uh for example like one two four and four to one they're actually look like the same right so it's gonna be um pierce in general and the time you have to traverse from one to one thousand right so it's gonna be all of earned so time and space are all often and represent what and represent the length between one and one thousand so it's only one thousand one and this is a solution and i'll see you next time bye
Find Positive Integer Solution for a Given Equation
reported-posts-ii
Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order. While the exact formula is hidden, the function is monotonically increasing, i.e.: * `f(x, y) < f(x + 1, y)` * `f(x, y) < f(x, y + 1)` The function interface is defined like this: interface CustomFunction { public: // Returns some positive integer f(x, y) for two positive integers x and y based on a formula. int f(int x, int y); }; We will judge your solution as follows: * The judge has a list of `9` hidden implementations of `CustomFunction`, along with a way to generate an **answer key** of all valid pairs for a specific `z`. * The judge will receive two inputs: a `function_id` (to determine which implementation to test your code with), and the target `z`. * The judge will call your `findSolution` and compare your results with the **answer key**. * If your results match the **answer key**, your solution will be `Accepted`. **Example 1:** **Input:** function\_id = 1, z = 5 **Output:** \[\[1,4\],\[2,3\],\[3,2\],\[4,1\]\] **Explanation:** The hidden formula for function\_id = 1 is f(x, y) = x + y. The following positive integer values of x and y make f(x, y) equal to 5: x=1, y=4 -> f(1, 4) = 1 + 4 = 5. x=2, y=3 -> f(2, 3) = 2 + 3 = 5. x=3, y=2 -> f(3, 2) = 3 + 2 = 5. x=4, y=1 -> f(4, 1) = 4 + 1 = 5. **Example 2:** **Input:** function\_id = 2, z = 5 **Output:** \[\[1,5\],\[5,1\]\] **Explanation:** The hidden formula for function\_id = 2 is f(x, y) = x \* y. The following positive integer values of x and y make f(x, y) equal to 5: x=1, y=5 -> f(1, 5) = 1 \* 5 = 5. x=5, y=1 -> f(5, 1) = 5 \* 1 = 5. **Constraints:** * `1 <= function_id <= 9` * `1 <= z <= 100` * It is guaranteed that the solutions of `f(x, y) == z` will be in the range `1 <= x, y <= 1000`. * It is also guaranteed that `f(x, y)` will fit in 32 bit signed integer if `1 <= x, y <= 1000`.
null
Database
Medium
null
1,984
welcome guys so that's solving is 194. uh sorry 194 uh medium motif respeding highest and lowest k scores okay so you're given zero index arrays where the numbers are represented score and the i students and your keys so also given integer k and the picker score and in k students from array so that the difference between high gates and the lowest case score is minimized also a little bit harder understand so basically uh let me just write a definition so basically the idea is that uh right so you have let's say you have one student and you need to choose k of them so let's say this is a 1 a n and you just say you choose b 1 b k which is a subset of let's say this set is s okay or multiset because their score can be duplicated and the goal is to minimize uh the maximum of the set as it is that is a max minus minimum a so basically you choose all b which has lens uh k b subset of k s okay so uh knifely so nicely uh you will have what because the maximum and the minimum a do not depend on order right so uh you will have the s choice of uh k choice right so this will be explanation especially when k is roughly s over two you'll get something uh explanation okay so uh this is so brutal right this is the beautiful solution well so for example uh 90 so when case one is very easy right case one answer must be zero because you can only choose the same okay k is closer to the answer is two in this case you can choose seven and nine okay also what um uh what the my idea is very simple we just do the sorting okay so the idea is that i just sort it so you first sort so story will cause unlock n okay so yeah well once you sort it let's just say a1 a2 let's say okay so let's say you choose first one let's use index zero okay so this is a minus one so if you choose zero and let's say you choose k of that right because you want to minimize right so you just choose this so this will be a k minus one so your answer will be so your answer must be the minimum of these a0 up to ak minus 1 and a1 up to ak and the a2 up to ak plus 1 ok and then finally uh you will be a n minus one now this is your final one right and the length is k so be a and minus k uh yeah okay so yeah so you just sorted and you define a minimum to be the infinity okay and you go through nums uh minus k plus one remember this is the this is very important right so this is the final one you need you can choose and then you compute the difference with i plus k minus one which is just these minus these two leads to these two you can easily see that this must one of these must be the answer right and the final return mi nice shot okay uh okay so see you guys next videos
Minimum Difference Between Highest and Lowest of K Scores
maximum-distance-between-a-pair-of-values
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **minimum** possible difference_. **Example 1:** **Input:** nums = \[90\], k = 1 **Output:** 0 **Explanation:** There is one way to pick score(s) of one student: - \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0. The minimum possible difference is 0. **Example 2:** **Input:** nums = \[9,4,1,7\], k = 2 **Output:** 2 **Explanation:** There are six ways to pick score(s) of two students: - \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5. - \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8. - \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2. - \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3. - \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3. - \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6. The minimum possible difference is 2. **Constraints:** * `1 <= k <= nums.length <= 1000` * `0 <= nums[i] <= 105`
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1]
Array,Two Pointers,Binary Search,Greedy
Medium
2199
168
Hello everybody welcome back to hike my name is pranal j today we are going to understand a question called Excel sheet column title first of all we going to understand the question then we are going to code this in so watch the entire video all right let's get started with the question given an integer column number return its corresponding column title as it appears in an Excel sheet so first of all we are going to try to understand how it actually appears in the Excel sheet so the First Column is a then we have a b moving till z so these are the first 26 columns a is 1 B is 2 Zed is 26 if you have to go to the 27th column it is a this is 27 a B this is 28 and like this we go till a z then we have ba a and so on this is basically how this numbering goes on it is somewhat very similar to converting a decimal number to a base 26 number because we have 26 different characters right so it is exactly working according to that but there is just one difference we do not have a zero in this number system so how do we code this in look at the code very carefully now all right so let's start coding this in now so initially we are going to take a string s we going to return this string as the answer so it is initially empty now why this column number is greater than zero if the column number is a multiple of 26 that means the character that we are looking for right now is z so s now becomes equal to Z + to Z + to Z + S we do a column number minus otherwise if it is not a multiple of 26 we need to find out which character do we want to enter here so here we will enter a plus column number mod 26- one for plus column number mod 26- one for plus column number mod 26- one for example column number is three so a b c we need to find out the character C so column number that is 3 26 is equal to 3 - 1 is 2 a + 2 is a + 1 is equal to 3 - 1 is 2 a + 2 is a + 1 is equal to 3 - 1 is 2 a + 2 is a + 1 is B A+ 2 is C so we have found out C so B A+ 2 is C so we have found out C so B A+ 2 is C so we have found out C so this is how we are finding the letter that we need to find at the end we have to do column number divided by 26 this keeps on going until column number is greater than zero at the end we can simply return the string so we need to add a semicolon here so we have to typ cast this before adding it to the stren let's try to run this now you can see all the test cases have passed let's submit this so the solution has been accepted thank you so much for watching the video I hope it is understood what we have done over here and if you like the video make sure to like share and subscribe thanks a lot see you in the next video
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
54
hey so welcome back and there's another daily code problem so today it's called spiral Matrix and it's a medium level problem so it's a like a two-dimensional problem so it's a like a two-dimensional problem so it's a like a two-dimensional array traversal problem where you're given a matrix here and you want to navigate it in a spiral kind of path and so all that you want to return is like the actual path in which you Traverse this Matrix so you just keep track of you know the value at every single like cell that you travel in that particular order and then you just finish once you can't kind of keep spiraling anymore without repeating a cell that you already visited okay and so to do this all that you gotta do is basically keep track of four different variables the starting column s underscore C is what I use the ending column and then the starting row which is like kind of this row right here and then the ending row and then other than that you just need the kind of response variable or array that you want to Output at the end so let's go ahead and implement this so what you do is you just Define your result and then you just want to return this at the end and then let's go ahead and Define our four different kind of flags or variables that we're using to keep track of those four different dimensions and that will be the starting column the ending column the starting row then the ending row and this will just be equal to zero then the length of The Matrix at zero to get the number of columns since this the number of columns and number of rows might not match and then we also need the um starting call or starting row and then the number of rows okay and so from here I think we also want to minus these by one just so we don't go out of bounds and we want to keep evaluating this while our starting column doesn't overlap with our ending column in our starting row doesn't jump over our ending row great okay and so let's go ahead and start going from left to right which is like the first path that we take and so to do that we just say okay let's go through every column in the range from our starting column to our ending column plus one since it's non-inclusive in Python non-inclusive in Python non-inclusive in Python and then we do we want to add to our result this path that we're traversing and so we just say at this particular index so the current row is the starting row since we are just traversing the topmost row here and then we just want to iterate through every index that we're going through in this for Loop okay and so after this because we just navigated through this entire topmost row we want to decrement or actually increment sorry our starting row because we just visited it okay and so now we want to go from top to bottom right and we want to do it from the rightmost column here from top to bottom and so to do that we just say okay let's go through every row in this particular range from our starting row to our ending row plus one since it's non-inclusive in plus one since it's non-inclusive in plus one since it's non-inclusive in Python and then we want to append this path that we're taking which is from the current row that we're at on the rightmost column so the end column great and so after this then although that we want to do is something similar where we just traversed this entire rightmost column so let's decrement our rightmost column which is the end column minus one to bring it inwards okay and so because we just evaluated these we do actually need like if condition to make sure that we're still Within These bounds okay so I think I can just do this here and we'll want to do this twice since we're going to travel two other paths here and so we want to do something similar where we want to say okay now we want to go from right to left on the bottom most column so for every column in this particular range from the end column to the starting column minus one since it's non-inclusive and we want to since it's non-inclusive and we want to since it's non-inclusive and we want to be going backwards so we just decrement by one each time and so once again let's add this path to our result which is the current row that we're at which is the end row and the current column that we're traveling through and so because we just traveled the bottommost row let's decrement it by one so it moves upwards and so then we just say the ending row minus equals one fantastic and then finally you want to go from the leftmost column from bottom to the top so then we say okay for every Row in this particular range from the end row to the starting row minus one and then we want to decrement it so we subtract one each time so then we want to maintain this path once again and grab it from our Matrix here and we Traverse through every row and then the column is the leftmost column so the starting column okay and then you just want to say okay let's take this column and we want to increment it by one since we're moving this leftmost column inwards okay and so let's just see if this runs see if there's any bugs looks good and that's the solution so for space complexity it would be o of M by n since this result will basically be all of the variables that is in this Matrix and so I get three by three will have nine values and so this Matrix naturally has nine values in it okay and then for time complexity same thing here because we're just iterating through every single element once it also will have a Time complexity of O of M by n just to clarify if you can't just because it's kind of hard to hear that o of M by n where m is the number of like rows and N is the number of columns okay so yeah I hope that helped and good luck with the rest your algorithms thanks for watching
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
1,099
hello and welcome to another video in this video we're going to be working on two Sumas less than K and it's very similar to the original two sum except for instead of finding two numbers that add up to a Target now you're asking for give me the biggest sum that I can use making two numbers that's less than this K that they provide so in this first example it is 34 and 24 right here and it will give you some 58 in the second example you can't get any two numbers that gives you a sum less than 15 because anything will give you bigger so there's a few ways of doing this and what you're really going to want to do the original two some um use the cache to get an exact number but we don't want an exact number we want to get the biggest number possible so we're going to use something else so we're going to do is now obviously you can just have like an N squ solution but the way this is going to work is if you're looking for like the biggest number possible it's going to be very convenient to sort our numbers and then we can look for solutions that we can use so we're going to sort this over here and now there's two ways of doing this that one is pretty obvious and the other one is not too difficult either and they're both the same time complexity so for the first one we can just go through every single number so if you think about it the Brute Force solution would go through every single number and then it would like manually search through everything here and look to find the biggest sum possible but if we know that our sum needs to be less than 60 that means their biggest sum can be 59 let's say that means that if we use the one our second biggest number has to be 58 or less so we could do a linear search but because this is already sorted we can just binary search for the second number so we can binary search for the biggest number we can find which will be 54 and then our sum will be 55 right so we can binary search which would bring down our time complexity from n s to n log n because for every number you would binary search then for eight we're going to look for the biggest number we can find and you can also I guess if you wanted to like do it in like a smart way you can bring down your constraints as well and this is kind of give you the intuition for the other problem so if you see like for one it's 54 so for eight it can't be anything bigger than 54 so you can just start with like your right side being what your first one was right so for initially when we do one we could say like okay well we want to search through the whole array but then for eight we don't need to search through the whole array it's never going to be anywhere over here because we increased our left number so the right number can't be bigger so for eight we could search through any anywhere through here so the biggest number is going to be this number here and we're going to get 42 then the same thing for and 42 is worse than um 55 so we'll keep 55 then for 23 we can say the same thing we don't need to search through any of this because we increase our left number so our right number has to be at least this so if we add these together then we will get 57 which is better and then for 24 same thing it can't be anywhere over here so we'll try starting we'll try this area here and so our best number is 34 so we'll get 58 so hopefully you're seeing the intuition for the second way to do this and then for 33 um remember it can't be anywhere here so we would only have to search this number here and we didn't find anything and that's fine because you don't really need a number like if there's nothing bigger than the number that means you might have already used this number before and so you're basically done so we can basically write down like for each number our right has to be less than or equal to previous array right like for the one we search through the whole array but then for the eight we know like for the one this was our number so then we our right can be this like our bounds can just be this section and then because you know for the eight we use this number that means for the 23 we'd have to use this and so on so this is the other intuition for the problem so let's actually go back and Cara this and this we're going to show the other intuition so the other intuition now that we know that we can reduce our constraints every time is just going to be a two-pointer time is just going to be a two-pointer time is just going to be a two-pointer again and the way it's going to work is we can just check for what's our sum and if our sum is too small we'll increase and if our sum is too big we'll decrease and we'll just record all valid sums and then our best sum so let's take a look at that so we're looking for 59 or 59 is like our best possible sum so if we get 59 we can just return I guess that would be another way to do it like if you get K minus one just return right there because that's the best so that's slight optimization but not too big of a deal so here our sum is 76 so it's too big so if it's too big we need to move down our right side right so let's actually learn how to use this program for once by doing this and then we can make another one of these and like this now we can actually move these arrows instead of deleting 100,00 times okay so our sum is deleting 100,00 times okay so our sum is deleting 100,00 times okay so our sum is too big so we need to make it smaller so now we have a valid sum which is 55 and now if we have a valid sum we need to see if we can get a bigger sum right because we're looking for the biggest sum possible so we're going to look for this sum this is too big so we're going to reduce it so this is valid but it's smaller than what we had before so we're going to try to increase it this is better so 57 now we're going to try to increase it again so this is obviously better as well so we get 58 and we're going to try to increase it again and this is too big and then finally when we try to decrease we will have our left meet our right and they can't be on the same number right so you do this until your numbers overlap so essentially if your sum is too big you make it smaller if your sum is good you record it and then you make it bigger so it's kind of like just a greedy two pointer and you can see that from the binary search your constraints keep decreasing and decreasing so you don't actually need to binary search you can basically just sort and do a oneast solution until your pointers meet and yeah so now we can code it up so we can say uh left equals z right equals length numus one we want to sort our numbers and finally we'll have a result and what we can do is we can just set the result equal to Nea 1 and we try to maximize and if there is no valid sum ever we'll just return negative 1 which is what the problems so we can say while left is less than right we can get a total value which is nums left plus num right and then if total is less than K we have valid sum so we will say result equals Max result total and we will try to increase our total by moving the left up yeah and if not then our total is too big so we need to decrease the rate then we just Loop through this until we until the pointers hit and then we can just return our biggest number that we found return thereal oh I need a zero uh actually I need this okay now hopefully there we go and yeah so pretty uh efficient solution uh this is basically n logn is as good as you can do so binary search will also be n logn but in practice it will be slower because you're actually doing nlog n for every single time so yeah you're basically doing like an nlog N plus n log n and the other one is n log n plus n so this is as good as it gets I think for this one um and for the complexity here so we did a sort which is a Mugen and then we also uh don't use any space we just use left and right with a uh twop pointer so yeah hopefully this was helpful uh definitely a kind of cool problem uh haven't seen it before so definitely kind of interesting um me yeah if this was helpful please like the video and subscribe to the channel and I'll see you the next one thanks for watching
Two Sum Less Than K
path-with-maximum-minimum-value
Given an array `nums` of integers and integer `k`, return the maximum `sum` such that there exists `i < j` with `nums[i] + nums[j] = sum` and `sum < k`. If no `i`, `j` exist satisfying this equation, return `-1`. **Example 1:** **Input:** nums = \[34,23,1,24,75,33,54,8\], k = 60 **Output:** 58 **Explanation:** We can use 34 and 24 to sum 58 which is less than 60. **Example 2:** **Input:** nums = \[10,20,30\], k = 15 **Output:** -1 **Explanation:** In this case it is not possible to get a pair sum less that 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 1000` * `1 <= k <= 2000`
What if we sort each cell of the matrix by the value? Don't include small values in your path if you can only include large values. Let's keep adding a possible cell to use in the path incrementally with decreasing values. If the start and end cells are connected then we don't need to add more cells. Use union-find data structure to check connectivity and return as answer the value of the given cell that makes start and end cells connected.
Array,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix
Medium
1753
653
today I am solving little problem number 653 to Psalm 4. the input is in a binary search tree it is almost like the twosome problem uh which is in the form of array so here uh in the two sum problem we actually create a set where we store the complements of the elements that we encounter in the array and here also we are going to do the same so I'm going to create a set where I'm going to store the complements of each of these elements and each of these elements are Traverse one by one so it's the same almost the same thing that we are doing it but the only difference is it is a binary search tree here so here we need to have uh our base condition if it is now we're just gonna return false and if nothing satisfies whether it's gonna return false and then here I'm going to write my code now so we'll first check the set if the value the complement of the value exists in the set or not so if um set that has K minus root dot value return true so we found our complement and hence we are just gonna return true if not then we add our root to the set and then we check to the left and then we do the same thing in the right so this will give us our answer okay ah great
Two Sum IV - Input is a BST
two-sum-iv-input-is-a-bst
Given the `root` of a binary search tree and an integer `k`, return `true` _if there exist two elements in the BST such that their sum is equal to_ `k`, _or_ `false` _otherwise_. **Example 1:** **Input:** root = \[5,3,6,2,4,null,7\], k = 9 **Output:** true **Example 2:** **Input:** root = \[5,3,6,2,4,null,7\], k = 28 **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-104 <= Node.val <= 104` * `root` is guaranteed to be a **valid** binary search tree. * `-105 <= k <= 105`
null
Hash Table,Two Pointers,Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
Easy
1,167,170,1150
424
what's up guys it's leetcoder this is elitecode424 longest repeating character replacement so we're given a string such as a b and we can choose any character of the string and change to any other uppercase english character we can perform this operation at most k times and we have to return the longest substring containing the same letter after performing the above operations in this case the longest substring we could get would be if we replace this b here with the capital a and we only have that operation one time so we would return four okay how do we approach this problem the brute force solution is to check every possible substring like this you know etc then it would be checking this etc this would be a very slow algorithm obviously so let's think of a better solution than this for string problems like this where we want a substring generally the idea is to use something called a sliding window so what is a sliding window well in this case we can see this a is valid then this a is valid because it's all just a this a b is valid because it's a we replace this b with an a and we add another a and it's still valid then we get to this b and we see well it's no longer valid because we have two b's and three a's and we can only replace one character so we have to keep removing elements from the substring until we get a valid substring so if we start out like this and this is not valid so we have to remove a still not valid because we have two a's and two b's so we remove this a and now it's valid because we only have one a and two b's then we add another b here and it's valid because we only have one a and three b's then we add this a here it's not valid so let's go like this and now let's remove characters until we get a valid substring so we can see from doing this algorithm that the longest substring we get is of length four we would get it here and so our answer is four essentially when we check if a substring is valid we want that operation to take o of one time because we're going through the array once right that's o of n we cannot make an o of n comparison every iteration because then our algorithm would be o of n squared which is really slow so we're aiming for time complexity of o of n which means each iteration we need an o of one check so how do we do that if we're let's say here how do we know if this substring is valid we can go through the whole substring we can get the max character which would be a because there are three a's and there's only one b and then is the amount of characters in this substring that are not a less than or equal to one in this case it is because there's only one b okay first we need two variables here before we can get started we need a max val which is going to be initialized to zero and we need a hash we'll just call the scene and it's going to be a hash all the elements we've seen and their amounts now we go through first element here is a and we see okay so we add to the scene now max val is equal to the maximum of itself and the newly seen character so max of zero and one therefore it's 1. and now we check if the substring is valid so is the substring valid we can see that it is but how do we do that with an algorithm well we compare the length of the current substring so the length of the current substring minus the max val if this is bigger than k then it's not valid and we'll see why this works in a little bit so let's continue here so we add a here so now this a in the scene is going to be 2 max val is going to be the maximum of either 2 and 1 so it's 2. and it's valid because the length of the substring is 2 minus the max val zero so we're good now we add this b here we add b to the scene max valley does not change because it's still the maximum of 2 and 1 which is 2. now we check is this string valid well the length of the substring is 3 minus the max val is two that's going to be one and one equals one here which is fine now we add a here now we make this two a three now we have to update max val and check the length of the substring four minus the max val three so that's going to be one that's still equal to one so we're good now finally we have this b here and this is where it gets interesting now we add one to b in our scene max val is still going to be three length of the substring is five so five minus three is 2 and oh that's bigger than k and therefore this substring is not valid so now we have to remove elements from the substring until it's valid okay so we remove this a and we subtract from c and we do the same comparison again so the length of the substring is four minus the max val three which is one and actually our algorithm says that it's valid and technically this is not correct because this substring is not valid however it doesn't matter we're trying to return the maximum output for the entire string so it doesn't matter if this substring here is equal to the substring and this substring is invalid because the length is the same so we're always going to be returning 4 no matter what here and so that's kind of a way we can avoid having to update this maximum value variable it's always just going to be the maximum possible okay i moved the hash down here because i was running out of space now we add this b here and we add 1 to our b in our hash max file is still three so now the length of the substring is five minus three is two okay so this is not valid now we remove one from the substring now we remove this a from the hash and now according to our check because the length is four and we subtract three it's valid which is actually correct in this case and then finally we get to this a so let's add this a here now we add to hash here maxwell still stays at three now we have a length of five subtract by three it's two okay so it's not valid so then we go subtract here and we add here and now according to our algorithm this is valid and it doesn't matter so at the end of the algorithm we would have returned four and it would have been set at any one of these points and it doesn't really matter which one and the space complexity so this is time the space complexity is going to be o of 26 because this problem specifies that the characters are only going to be uppercase english characters which means there's only 26 at most and we can reduce that down to actually of one before we get to the code if you found this helpful so far please give a like and a subscribe because it really helps the youtube algorithm and with that said let's get to the code okay let's define our hash we'll call it scene let's define our left pointer and our max val which is zero and our output which is initialized to zero we're going to do some loop but at the very end we're just going to return output so now here's our loop so we'll say for right in range of the length of s so left is the left side of the substring right is the right side of the substring let's get our right character which is going to be s at right and we'll say scene at right character equals scene dot get right character or zero plus one basically initialize it to zero if it hasn't been initialized otherwise get it and then add one to it then we need to update our max value so max value is equal to the maximum of itself and the newly seen character amount okay now while the length of the substring minus the maximum value is greater than k we know the substring is invalid and to get the length of the substring you have to do right minus left plus one and this plus one is important because right actually starts out as zero so now we say seen at s of left minus equals one because we're removing that left character from the substring and we just move the left character up by one now finally in our loop we have to set output equal to the maximum of itself and the length of the substring and we can see we got the right answers for the two test inputs so let's submit and boom that's it let's recap on this problem here we first thought of a brute force solution which was obviously too slow and because of the substring problem we can do a sliding window algorithm instead now the trick is to figure out how to check an o of one time if the substring is valid or not and the way to do that is to use the length of the substring and subtract the maximum value that we've seen so far and while the substring is invalid we simply move left up by one and the other trick here is that maximum value never needs to be decremented because it doesn't matter if we get an invalid substring that's the same length as a valid substring because we're going to return the length of that valid substring anyway and that's it so if you found this helpful please give a like and a subscribe because it really helps the youtube algorithm let me know down in the comments if there's any other problem you'd like to see next see you next time
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
124
hello world Joshua here I want to be teaching you about how to solve this problem binary tree Mattson path some alright we're tackling finally a big boy hard or big girl to be gender-neutral hard or big girl to be gender-neutral hard or big girl to be gender-neutral Oh me actually you know what I would retract that statement I don't want to exclude anyone else because given a nonempty binary tree find a maximum path sum for this problem a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent child connections the path must contain at least one node and does not need to go through the brute alrighty then okay so let's look at some of the examples oh by the way before I actually start solving this I would include the problem description the link to this lico problem in the description below so let's get right to it alright the first example in this case the maximum sum will be maximum path sum will be 6 cosmic 2 1 3 they all add up to make a sixth value now in simple - to make a sixth value now in simple - to make a sixth value now in simple - it's just gonna be 15 20 and 7 no make 42 that's because they don't include an 8 or 10 and 9 is because it will decrease that sum if we included into that value no hints wow this is gonna be so easy so first what is a binary tree I you know I could flash this funny meme oh gosh darn it there's so many memes what's just ah but anyways what is a binary tree first let's go over the concept of a tree let me see if we can find a good example right here is there diagram ok so a tree is like you know there's a parent node and has children no it's right below it and that children know but have children right below it as well now a binary tree it's just like this tree right here it's when that parent only has up to two nodes so it could be one know it can be no nodes for each node now in my case I think I would if I want to go find out the maximum path so what I need to do is hold on for a second guys my apologies I'm gonna drink some water hmm so I'm thinking about this there's some scenarios that have to consider one then note itself could be a maximum and to know it at the right itself it can be a maximum let's just say if like you know this there's a negative value okay yeah we're just legal this possible scenarios right here because we know that it could be at least one note it's an inn and just you know if they're all negatives except this 20 right here then that 20 will be the maximum path song because it could be at least one node let's see what else and they're all negatives you have to find that the least that you know the smallest negative number so that it would be you know greater than the rest but could you say you see like you know negative one they get three and negative five in this whole tree negative one and itself will be the maximum path sum so if you consider that as well huh that's right so let me think about how I break this down if I want to traverse through this tree how should I do that let's think about this only think about this intuitively first before I start solving this question so that perhaps you know if you follow my train of mind make you both agree in the solution so let's see right here so if I started at this node I'm giving this no brain oh this is the root and I can determine the children right to its left until it's right so what I want to do first is I want to go gather information could it go left and right is there any other branches to extend from that root and if so I want to see if we calculate the maximum path sum if that two and itself would be its own tree or the three itself would be its own tree and I'll kind of repeat that pause that process you can see that it's gonna be a recursive function because you know I'll be repeating that sort of idea recursively I'm gonna keep calling idea alright if there's a temporary tree right here but this by itself be its own max create its own maximum past some that if it were to the original root value or its parent they will not have that value and you can see that in this scenario right here the root value is gonna bring that maximum path some down and the base condition what it will stop is if the I travels to and you know there's no it reaches that end point and there only no values right below it okay so I think least I could define that for now so let's just type something per second we want to find the maximum sum okay the maximum sum for now we're going to just put a placeholder value to be the root dot Val and I'm gonna create that recursive function based on starting at the root and I want to return the maximum sum at the end now let's create that recursive function public int Traverse tree node now the base condition so when I do travel through each of these branches below I have to know when to stop and as I mentioned I stopped when it reaches an end point when only null values extending from that node so it'll be node equals no okay and now you might be asking why I made this an int because on the way that we travel are you gonna say that we're gonna need to know we're going to need to know if it's I don't think about this I made it ends okay so you know when they start with this when it's this.parentnode right this when it's this.parentnode right this when it's this.parentnode right here and we check its left and right values we're going to investigate what these values at their maximum path sums at each of these branches what will those be that's why I made it int so okay first I'm gonna return zero here because which reaches to null it's basically there's no value to add to the temporary sum that you're creating now if there is a value you want to it left equals Traverse node left and int rights equals Traverse node dot right okay so we get the values from the left and the right hand side when we recurse right through it okay and now if the left and the right would return a negative value do we want to add that as our maximum with the left-hand side of the right with the left-hand side of the right with the left-hand side of the right hand side no we don't you just want to neglect that value so that's what made it a zero so let me just explain to you my thought process right here because the zero right here sorry about that Traverse okay so here's what we did with Traverse eterno left and we found out that it's going to return a negative value now once it has the left and right values in it for example the right and also has a negative values so now I compare the maximum sum at this point right here about some sum equals now to decide do I want to keep the maximum sum that I currently have which is zero or I mean the root value I'm sorry the current root value or do I want to include the path with the left and right and Novell now you can see this you know the sonars that I've referenced earlier like what just say that it's negative and it's all negative it wouldn't be useful to add it to this next Sun because it's going to only make it's gonna bring that sum that you're in create right here it will bring it lower so that's why you know I had the choice do you want to add that the value is maximum path sums of the left hand side or not and so far you know what to say the values there are negative from the left-hand side like would you say this left-hand side like would you say this left-hand side like would you say this negative 2 and it's negative 3 and the root value is 1 which say negative 2 negative 3 and this is 1 we don't want to take any of the values from negative 2 negative 3 because they're mechs and pass some if we include that to include that include those branches it's gonna be negative 4 so we want to exclude that so we don't add them at all we just basically stick with an old value that we have now we have the maximum sums now let's return so now we have let's just say that we found out what the maximum sum is we've finalized that one now what can we do then now there might be snared oh so you think of Center these scenarios as well so we have the scenario that we know we try to see we could add all of them at once or you know let me think about this hmm now I want to see if I can return the math among Max of the left and the right hand side oh yes so you know as we Traverse we're creating that sort of temporary sum so let's think about it right here or negative 10 27 and now we've tried from that node value like previously right here you know what go right here will be 20 plus 7 or 20 plus 15 we the choose which path might give us a maximum what you say we Traverse so what I'll be doing right here is that I want to choose to max the maximum value of which pathway gives me the biggest value this is the mathematics of the left-hand side is the mathematics of the left-hand side is the mathematics of the left-hand side that would get me the bigger value or the right-hand side you can see right the right-hand side you can see right the right-hand side you can see right here that you know 15 will be the bigger number so that case I'll just travel right through as plus note Val so let's see so let me think about this I want to make sure my thought process is let me just summarize right now so one we initialize the maximum sum to be the root value just as a placeholder until we could find a sum of value bigger than that and we create a recursive function that goes through the whole tree to find that method the maximum path sum and it will stop once it reaches the woods it knows that it's an end point where the nodes will be known now the left hand side in the right hand side we check both sides to see if it's actually gonna bring up the maximum sum of the value if not we don't want to add it to what we're finding out so what you say this is negative 2 but 1 3 are the same that means we just want to use the 1 &amp; 3 means we just want to use the 1 &amp; 3 means we just want to use the 1 &amp; 3 itself and this would be would you turn the zero to left the inside and then the method max sum that point will be just write plus no dot Val and compared to the maximum sum then if you are take to this example that is set here this is 1 3 and this is negative 2 then 1 plus 3 is 4 which is bigger than root value which is 1 so 4 will be the new maximum sum and now once we've done that we want to return the maximum sum up you know oh my gosh I can see why this question is hard man let me just slow down for a second okay so they'll be what's a traversal um calls done you know as we traversed this whole treaty and you know returning the mathema max of the left and right flows know that Val we cannot something we want to like emphasize I should have said earlier in this video my apologies for not doing this there's no backtracking so I can I do this negative ten twenty fifteen twenty seven I can't do something like that it has to be just one direction and no backtracking so this is why did return math that max of left and right let's know that Val because when we traversed through this tree I want to see which one will bring me the bigger value the fifteen or the seven because we're checking that you know optional so if we do one whole long path like this would that creates the maximum sum and if not then we just stick to whatever the maximum sum was so this is why I'm returning you know the option I want to add this note that Val and then you know if it's good extend to one of these pathways right here it's gonna be one of these the one from the left-hand side or the one from the left-hand side or the one from the left-hand side or the one from the right-hand side one from the right-hand side one from the right-hand side all right so let's hope that this works cuz I went through a long explanation and if it doesn't work then I'm sorry for the twenty minutes you've listened to me oh I'm not sorry cuz it's right away actually slow down Joshua let's submit the problem huzzah okay so this works so I hope that this makes sense if I were to find its time complexity and space complexity of this answer since we'll be going through every single node I would say it's around all and time complexity and the space complexity will be around let me think about this I'm not really so good with space complexity to be honest but since there's a bunch of traversal calls worst case scenario if it's all one line they'll be all then if it's just like this maybe it's like Oh Levin over to because you know there's the traversal calls going go up to you know if it's a well balanced retreat like this it will go up to or bent over to so you know please leave in the comments below if you know if you even explain what better than what I did about space complex daytime complexity about you know solving a problem like this I'm afraid that's like a weak point I'm trying to improve I would like to learn also so please post in the comments below and there's a better way to solve this I think there's a better way like if you use an iterative solution then and use the stack I think that could be another way to solve this problem I wasn't able to implement it myself but you can go in and try if you'd like to and that's about it guys thank you for watching and for sticking me hard with this hard you know this hard question I'm gonna send you a free bubble sore when you wake up next morning your mommy and daddy will carry you a Bulbasaur and put it on your lap and you get to play pokemon all day long just kidding guys just kidding I'm a bit exhausted today and I'm gonna eat some food have a good day guys see ya
Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum
A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root. The **path sum** of a path is the sum of the node's values in the path. Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 6 **Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. **Example 2:** **Input:** root = \[-10,9,20,null,null,15,7\] **Output:** 42 **Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. **Constraints:** * The number of nodes in the tree is in the range `[1, 3 * 104]`. * `-1000 <= Node.val <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
112,129,666,687,1492
849
Hello Hi Everyone Welcome To My Channel It's All The Problem Maximized Everyday Person Should Give An Are Representing Role Subscribe Skating Subscribe And Leave With Subscribe And Subscribe This Video Not Shyam One Of The Distance From 0001 Number To Distance From Subscribe Now To 9 Ki Is Flexi Song Seat Number Three Leg Race Jinx Ko Dhawan So Tourism Activated Similarly Galaxy S8 September 5 Hours Distance Between A Person After And Siswan Sauce Maximum They Can Change R Intellect And See The Number To Two Our Channel Like This Problem Sure From Starting Telefilms And See between two directly on this latter subscribe 22000 can set a galaxy or duos distance from subscribe quite a light three white two which is one in the need two plus one so lets player for placid between two person for this is the person Sitting MP PMT Vansh Na Election Seervi Phase Distance From This Person To Distance From Evil Resident Evil In Between Obscurity In Between Two Per Subscribe Candy Distance From Were That Its Plus One To Subscribe My Two To Two Meanwhile This Vansh Shoaib Display Switch Distance wave display switch off distance to but is serial starting free embassy from election servi this distance from clothes percentage oneplus one plus one witch 300 g maximum from this example which can see the election will servi and maximize the distances three cases like this is pet Clear your Hair Distances 1872 Overhead Tank Maximum Like and Share a Guest Post Video Trading and Depend 120 Days Candy Maximum Cases Sentence from Doing to Setting Persons So Let's Start Thinking How Will Solve More Optimally in One 5 Years Golden Will U Will Start the Point From eligible to minus one and traditions are off from equal to zero is it is perineum time right one switch on Thursday subscribe withdraw cases minus one is the distance between two are next will update you salute to this place because know the laptop the right Nau End E Will Be Till Close Setting Person Will Be Displaced A Helicopter Vikram I Between Is To 9 For This Is Not Want To Give What I Will Reach And Notice Of One Side Subscribe No Know No Death Subscribe Between To The Distance Provide - - 21 2011 Subscribe Now To Two Person Then Is No Person Right Most Effective Way Setting On This Been To Consider Again Descended On Which Will Be The Subscribe - 151 - 110 003 100% 68 - 110 Four - 151 - 110 003 100% 68 - 110 Four - 151 - 110 003 100% 68 - 110 Four Subscribe Now To In One Sentence Subscribe And Different From its length that and life also defined as result will keep absolutely maximum and let's take a pledge for max distance from any situation with great numbers from 1 to 10 of your plus will be first seats of this 1200 10's mind this is a b i Maths.max and business can I take which is the same in Maths.max and business can I take which is the same in most cases will take demax this as chief acts of next diff as chief acts of next diff as chief acts of next diff types of and chief - bell boy to types of and chief - bell boy to types of and chief - bell boy to raghu dixit that and will app for every case will update Our Advisor You For Internal Par Setting Pulsar DTS-i Next Chief Suresh Will Rise In DTS-i Next Chief Suresh Will Rise In DTS-i Next Chief Suresh Will Rise In India And Will Check Dil Khush Wa Seat Saunf Minus One Is Equal To Zero In That Case Be Me To Take Medicine At Again From Me To Take Medicine At Again From Me To Take Medicine At Again From The End Different Languages In the last person in last row of a person from this is this facility of experimentation so let's compile code and series voting key settings informed e want s can landslides to tens maximum test cases Shoaib Scars 06 boundary wall extra oil from laundry consumption 05102 90 Electric 2006 Things Will Cover Most Wanted Spider Compiler Experts In This All Taxes Was In No Way Are Confident That They Can Submit Dissolution And Shifted To Accept Subscribe Accepts Know What Is The Time Complexity Of Dissolution The Amazing Elements Of Obscuritism Like And Share This Video You will help you thanks for watching
Maximize Distance to Closest Person
maximize-distance-to-closest-person
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return _that maximum distance to the closest person_. **Example 1:** **Input:** seats = \[1,0,0,0,1,0,1\] **Output:** 2 **Explanation:** If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. **Example 2:** **Input:** seats = \[1,0,0,0\] **Output:** 3 **Explanation:** If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. **Example 3:** **Input:** seats = \[0,1\] **Output:** 1 **Constraints:** * `2 <= seats.length <= 2 * 104` * `seats[i]` is `0` or `1`. * At least one seat is **empty**. * At least one seat is **occupied**.
null
null
Medium
null
398
back to the cracking pain youtube channel today we're going to be solving lead code problem 398 random pick index before we get into the question prompt you guys know the drill please subscribe to the channel if you haven't already it really helps me grow and i want to reach 10 000 by the end of the year so please help me with that goal anyway given an integer array nums with possible duplicates randomly output the index of a given target number you can assume that the given target number must exist in the array and we want to implement the solution class and the solution object will be initialized with an array nums and it has a pick method which takes a target and returns a random index i from nums where nums of i equals to the target so basically returns one of the indexes uh where that value with the value of that index is target and if there's multiple valid indexes then we should have an equal probability of returning one so let's look at a example here where we have um you know our object and we're given the values one two three and we are asked to basically pick a few values from there and the way that we're going to solve this example is by the naive approach to the solution which is not what your interviewer is looking for although it is pretty intuitive and that is the dictionary solution so what we want to do is basically create a dictionary for each of the values and we're going to map the indexes that we see it at right so 1 occurs at the 0th index two occurs at the first index and three now occurs at the second the third and the fourth index right so now when we're asked to actually pick a three we need to return one of these indexes and you know it has to be at random but since we have this list we can just simply uh take one from here at random right we can just pick one and all of them will have an equal probability of being picked so it doesn't really matter what we return here as long as it's two three or four so that's fine easy peasy for the one there's only one thing we can choose from so we just return the zeroth index and then we're asked to pick three again and basically it's fine we can just pick literally anyone from here at random and we're good to go so this is really simple it's really intuitive but the problem here is that we actually need this extra dictionary so this means that our space complexity is going to be big o of n whereas the problem what they want you to do is actually solve it using constant extra space and you may be wondering how the hell am i going to do that if i can't store the actual indices and well this is one of those questions where if you haven't seen the trick you're probably not going to be able to solve it which is probably why you're watching this video in the first place but once you've seen it and you understand the trick then it's super clear and it's like one of those aha snaps and you now understand it and the way that we're actually going to solve this is by something called reservoir sampling so let's actually clear all of this text here to give us some more room and what we're going to do is we're actually going to walk you through how this solution is going to work in order to achieve that space complexity of big o of one and to be honest when you see the solution and it clicks for you it's kind of like magic it's a really cool one you're probably not going to come up with it on your own uh hence why you're watching this video so let's uh stop talking and talk about how we're going to do this thing called reservoir sampling okay welcome back we've now cleared all of the extra text and we can now talk about how to solve this using something called reservoir sampling it's okay if you don't actually know what that is it doesn't really matter as long as you can solve the question then you're good to go it doesn't matter what it is in practice we're just gonna use it so obviously in order to get big o of one space the easiest way would actually just be to do multiple loops through our array here uh but obviously that's not great uh because we're gonna have um you know we could have potentially like a quadratic run time which is not good so we want to be able to ideally do this in one pass-through and with no extra space one pass-through and with no extra space one pass-through and with no extra space which is basically what the interviewer is looking for so what we're going to do is we're going to go from left to right over the array and we're going to have a few variables to help us along the way and we're going to have a variable called count which what count is going to represent is the number of times that we've actually seen the element that we're searching for so for example this three every time we see a three we're going to increment the count pretty straightforward and we're also going to have a variable which is going to be called pick index and this is going to represent the index that we've picked for this value right and we're initially going to set it equal to zero because obviously we haven't picked any index now what we're going to do is we're going to go over our array here from left to right and like i said if we ever encounter the number that we're looking for count is gonna get incremented so you know we have our array one two three so let's kind of go through it and we'll go index by index so first we're going to be here is one equal to three it's not so now we're going to go to the two is two equal to three it's not okay so now we go to the three is three equal to three yeah so that's what we're looking for so we're going gonna increment our count by one so it's now going to become one and here is where the magic happens so let's think about this if you have a bag right let's say we have a bag and okay that's a horrible we'll say we have a box right and in that box we're going to put some marbles into it now if you have one marble in the box and you're asked to pick a marble at random you're always going to pick that um that marble right there's only one marble in there you put your hand in there and there's only a probability of one right so okay but now you know you add a second marble to the box so now each pro each marble now has a what one out of two or 50 chance of being picked right 50 and in the first case it was a hundred percent and now if we add a third marble it becomes what 33 point you know whatever repeating right percent that it gets picked and same thing if we add a fourth marble here it now becomes a 25 chance of being picked now what do you notice about these denominators well what you notice is that every time we see the value we actually increase the count here so you know when we see the second one it becomes two so now when we have two of them each individual one has a one out of two chance of being picked so what we can do here is we can actually update our pick index to be you know whether or not um it equals to the count right so what we're going to do is because we can't store the actual indexes what we're going to say is we're going to pick a random number between 1 and our count and if this number actually equals to our count variable then we're going to say that count is our random pick and this is how we're actually going to achieve randomness here without actually needing to store the values and let's kind of think about this and why it works and kind of think about our example so in the first time that we see count right it's initial count is going to be zero we see the first three and count equals to one so we're going to do this and we're going to say our pick now is going to be the random choice so we're going to take random of one to one right because count is one and is this going to equal our count which is one so obviously picking a number between one and one is always gonna give one a hundred percent of the time so in this case we take our pick cool so now our pick index is one because if we only see one three in here then we should always you know take that one index but the tricky part is when there's multiple threes okay so now we're continuing we get to the second three and now our count equals to two so now we wanna update our pick but only if it equals the count right so we're gonna say we're gonna take another random pick from one to the count which is now two and if that number comes back and it equals the count which in this case is two then we wanna update our pick to be the index uh that we're currently at which in this case is going to be the index so this is zero one two three so three right and that's basically how we achieve the randomness every single time and then again when we get to the final three right count now becomes three and again we're going to take a random number between one and three because that's the new count and if that value actually equals our count which is three again obviously that has a one and three probability of being picked right because we have a probability of picking one which has a one and three chance we have a probability of picking two which has a one in three chance and obviously three has a one and three chance so obviously you can see that each element has the equally uh you know chance of being picked which is what we want given that the indexes are the same so this is how essentially we're going to pull off our uh magic here and if it hasn't clicked for you watch it again and you know kind of think about this box example about how every time our probability increases and this is directly proportional to the amount of marbles we had in the box right and you can think of the marbles as our like count variable here right and kind of once this all clicks for you and how this maintains the randomness then this question becomes extremely trivial but it is imperative that this part clicks for you otherwise it's going to be very difficult for you to explain it um but essentially this is how it works the code for this is super simple but if you don't understand why you know picking the random value and then if it equals to count actually gives you that equal probability chance of being picked then you're going to struggle here so at this point let's move to the code editor and actually write this up it's like 15 lines of code easy peasy okay we're back in the code editor now let's type this up so in our init function we basically just need to store the nums that we're given so we're going to say self.numbs given so we're going to say self.numbs given so we're going to say self.numbs is going to equal to nums if i could just spell and now what we need to do is we actually need to go through our you know nums here from left to right what we want to do is we want to keep track of the count and we want to keep track of the picked index right and this is they're both going to be 0 at the beginning so we're going to say 4 i num in enumerate no of self.numbs no of self.numbs no of self.numbs it again type today uh what we're going to do now is we're going to say if the number equals to the target then obviously our count increments by 1 because we've now seen uh our target and now we want to say if random dot randint from 1 to count actually equals to the count we're going to say that our picked index is going to equal to i and the last thing that we want to do is actually return the picked index so let me just make sure i haven't made any syntax mistakes and we are good to go to submit this and actually when we submit this we're going to get a time limit exceeded for absolutely no reason other than lead code is terrible and we'll see in a second that this is going to tle and it happened to me like a few minutes ago so i don't know why elite code is doing this if we look at my accepted solution from 2021 let's look at this one it is yum okay literally the exact same code that we've written right line by line the exact same code same with my whoops where did it go with my previous submission here back in what is that september of 2021 again we can see the exact same code actually this way i did it with a default dictionary and it was accepted so now even with the reservoir sampling for some reason it's not being accepted although you'll have to trust me that this is actually how you do it if we even look at the solution here uh let's see reservoir sampling yadda this is they do the exact same thing right they check whether or not the number equals to the target they increment the count and then they do a random uh integer and again they're returning the index i mean this one's in java but it's the same idea right for some reason it's not being accepted despite being the solution that leak code tells you to do something is going on in the back end i don't know what it is this is just to prove to you that this is the solution anyway as you can see um the time and space complexity it's going to be big o of n time because we have to go through the entirety of our nums here when we do the pick and we're not using any extra space here for the pick so it's just going to be big o of one so again i don't know what is going on uh with lee code why this is tleing it shouldn't it was accepted in the past but it is what it is uh this is how you solve it as you saw even the official solution does the exact same thing so i don't know what's going on anyway so that's how you solve random pick index the only tricky part here is really understanding why this actually gives you the you know randomness that you actually desire and once this line here clicks for you uh as it did you know hopefully the box and marble example helped uh if it didn't maybe go re-watch it one uh if it didn't maybe go re-watch it one uh if it didn't maybe go re-watch it one more time or you know maybe read through the discuss section for this problem and hopefully that will help anyway that's how you solve random pick index one of those stupid questions where if you haven't seen it before there's absolutely no way you're getting the solution before unless you have like 200 iq or something you're probably going to solve it with the dictionary and they're going to tell you no that's not going to happen you need to do it better uh so definitely you want to know because your interviewer is going to want this ridiculous solution that no one knows about anyway that's enough of my rant that's how you solve random pick index if you enjoyed this video please leave a like and a comment it really helps with the youtube algorithm if you want to see more content like this please subscribe to the channel and otherwise thank you so much for watching
Random Pick Index
random-pick-index
Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array. Implement the `Solution` class: * `Solution(int[] nums)` Initializes the object with the array `nums`. * `int pick(int target)` Picks a random index `i` from `nums` where `nums[i] == target`. If there are multiple valid i's, then each index should have an equal probability of returning. **Example 1:** **Input** \[ "Solution ", "pick ", "pick ", "pick "\] \[\[\[1, 2, 3, 3, 3\]\], \[3\], \[1\], \[3\]\] **Output** \[null, 4, 0, 2\] **Explanation** Solution solution = new Solution(\[1, 2, 3, 3, 3\]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums\[0\] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-231 <= nums[i] <= 231 - 1` * `target` is an integer from `nums`. * At most `104` calls will be made to `pick`.
null
Hash Table,Math,Reservoir Sampling,Randomized
Medium
382,894,912
493
so hello guys welcome to this new video and in this video we're basically going to uh discover the question that is a reverse pass so uh in this question from lead code that is of hard difficulty level we will basically be given an array and we'll have to return the uh the number of reverse pairs that are present in the array now let's see what reverse pairs are so they are basically a pair of two indexes like uh as you can see it's given over here that there are a pair of two indexes i comma j such that i is less than j and both the indexes lie uh in the array itself and uh the value of uh like value that is present in the at the ith index that is uh and numbers of i should be greater than 2 into numbers of j so uh like these are the two conditions that is i less than j and nums of i uh should be greater than 2 into numbers of j that is double if nums of j so this is the condition that we can establish a reverse pair we can detect a reverse pair in the array given to us now let's see in this example given over here as you can see uh in this array this 3 comma 1 will be one reverse pair y because three is present at the index three zero one two three and one is present at the index four so three is less than four if we take is three and we take uh like j as four so three is less than four so the first condition is satisfied now we go to the second condition uh that is numbers of i that is three should be greater than two into numbers of j that is one so two into one three should be greater than two into one so three is greater than two so obviously that condition is also satisfied so uh we are basically going to hold that as one of our uh reverse pairs so now next up you can see this three is also present over here so three one also makes a reverse prayer so there are total of two reverse space in this array none other than this so the output is true so uh we'll be basically uh have to detect or the total number of reverse pairs that are present in the array with these two conditions so now let's go to the approach so uh okay so let's see this example over here that is one three two three one we'll work on with this example itself so let's uh create this array over here one three two three one so what is the most basic approach that will come to anyone's mind uh the brute force approach as you call it so that will basically be that you hold one element okay you take one you start from the left traversing from the left you hold one value of i is zero suppose and you uh you know you just traverse all the elements all the indexes are that are on the right of i uh and you take like you basically traverse them as j like you take every indexes j and you check for the two conditions so i less than j so if you're traversing on the right obviously this condition is always satisfied so now the only condition that you have to check is basically if array of i is greater than double of area of j so you'll have to check this for all the elements that are present on the right of the ith index so this you will have to do for each and every element you go to that element you traverse on the right side of it to find any element that satisfied this condition okay so you're basically doing this now can you imagine that traversing like you hold on to one element and then you traverse to the right side like the whole area on the right side of that element that will take essentially o of n time right because you're essentially like on an average you're basically traversing the whole array itself so uh now when you combine these both you will also have to you know hold on to every element is i right and you know traverse to the right so it's essentially when you calculate the total complexity so there are two or two operations of o of n one is for that you are holding every element is it index and then you are traversing on the right for the whole index so if you combine those two the s uh the effective uh time complexities in the order of n square now uh like for questions like this an order of over n square is not really recommended like so we will need to reduce it so that's when our optimal solution comes in so uh like cutting on to the point uh many of you would be knowing about the concept of merge sort right you must have done the concept of merge sort it's in uh it's a basic sorting algorithm i won't say it's very basic but it's like something that everyone should know if you know about searching and sorting in arrays so uh we will be using an implementation of merge sort over here in order to count the inversions present in this array okay now let's erase all this so now what we're going to do is that first of all we are basically going to uh see that what the merge sort actually does so merge sort has an effective complexity of o of n log n in the order of n log n and i'll exactly tell you how so what merge sort does is that merge sort will first of all like suppose you have two pointers in merge sort okay you have one left pointer and you have one right pointer or you can consider that as low or high okay so uh like suppose they're lower high and then you have the low one is zero and the high one has uh where is this four okay initially so what we basically do is that we divide this array into halves into two halves okay let's divide this into these two halves okay now you can put the middle element in any of the sides if you want to you can put two here or two here that doesn't matter actually so this is how we did it okay now again okay suppose again we divide this into two halves so by default we are considering the middle element in this left half suppose so we divided this into two halves okay done so now what we do is that again we divide this into two halves again so this becomes one and this becomes three right so we went to the roots like we basically went until and unless those elements became like singular elements okay so now what we're going to do is that this is the last stage we can't divide it anymore right so we basically now start doing our main operation that is merging now we divided okay now we divided this array into halves like this now we will be we'll be merging these okay now what the condition that we'll be checking before merging is that is one less than three yes one is less than three so it will basically stay in its original order now just for example i'm saying just for example suppose this would have been 3 1 instead of 1 3 suppose here it would have been 3 and then 1 2 3 1. so in this case this year would have been three one and here there would have been three here there would have been one if this would have been the case in this case actually you can see that here we will be also performing the division and here three is one okay fine so i'll explain it with this only i'll not mess you up with this i'll explain it with this so uh here it's three it's divided into three and one right so here it's already uh this pointer this left pointer is uh is basically the value is right less than the right pointer so we basically continue with this combination itself but here the left pointer value is basically greater than the right pointer value now this won't work why because we need to sort this array okay i forgot to tell you one thing we are uh by default sorting this in non-decreasing default sorting this in non-decreasing default sorting this in non-decreasing uh order okay this merge sort i'm that ex example that i'm explaining is for sorting the array into non-decreasing sorting the array into non-decreasing sorting the array into non-decreasing format so uh since if this element is greater so we know that we need to since we need to uh like convert this into a non uh decreasing format so we need to turn this into less than so what we do is we simply swap these both values so this becomes 1 and this becomes 3 done so now we backtrack now this is c this is our termination we swapped also now we backtrack so this became 1 3 right because we had we have swapped the value so this has become 1 3 right now okay so this is this part is 1 3 right now this over here stays 1 3 because it was not swapped because it was already less than so now see now our main part comes in okay now this is 1 3 and this is 2. now our main merging the essential merging algorithm comes in what happens when we like you know you must have also studied uh the question that is merge two sorted arrays i'm assuming that if you are doing this question you must have gone through this question that is merged to sort if you have not gone through this question you should just go this is a medium level question this question that we're doing right now is a hard level but this is a medium level question so you should just go and try this out once if you have not done this already so here we are going to be following the same concept of uh merging to sorted arrays so what we are going to do is like suppose uh like just for example i'm telling suppose we take this total okay this 132 this total length of one temporary array okay so what we do is we start one pointer from this array suppose we're taking p1 at the start of this array and uh this is just uh i'm not uh i by array when i'm saying i mean the part okay don't consider it as a different that we're breaking it into different arrays at every level we're just dividing it into parts and just based on uh indexes maybe we'll see that later in when we implement the code so suppose we take the p1 pointer here at this index and p2 pointer here okay so now what we do is now uh we uh suppose we take a p we have this temporary array over here for storing all these three values in sorted order okay so what we do is first of all we check if array suppose this is a array of p1 we check if it is uh greater than ra of p2 okay if it is greater than array of p2 we know that we have to convert this into less than right as we have already seen in this condition over here that if this condition sorry that if it is if any at any point in this whole uh process if we encounter any such pair okay any such pair of indices where this greater than like the index is on the left of the second index and the greater than com uh relation occurs between them we always have to swap that and we have to convert that into less than okay so here what we're going to do we're not going to swap but we are just going to store it that like we are going to store this second element over here in temp but here as you can see that array of p1 is basically less than array of p2 right so we are just going to do nothing we are just going to store this p1 value over here because this is the less value right so if we are going to store our final sorted array in non-decreasing order so sorted array in non-decreasing order so sorted array in non-decreasing order so we need to store the lesser value first right so if ra of p1 is less than arrow of p2 we will obviously store array on this array itself right so this uh like this uh this p1 only right so uh we just do this and we forward p1 from this to here okay uh from one to three to this index now see now array of p1 is actually greater than array of p2 okay if it is greater i have told you if it is greater we have to inverse it we have to swap like we have to basically make it less than so now what we do is now we don't uh carry the element of p1 into 10 we carry the element of p2 into temp so we put this over here too and then what we do is now we see that this p1 only one element is left so we put the remaining element over here so you can see that this is basically forming a finally sorted array right like we gave it two uh like different uh sorted sections and it uh made that into one total like one full length sorted sequence so that is what the magic of this merging algorithm is okay so now this process now this got converted from one three two into one two three okay fine so now what we have to do is now we have two sorted arrays again year one three and here one two three now the same thing we will do we will put one p one over here we'll put one p two over here okay now uh as you can see we'll create again one temp array now the temp is length will be one two three four five okay here so one two three four so this is the temp array for this stage now here what we're doing is we're checking if array of p1 is less than array of p2 less than equal to okay so fine that equal to also we can consider so uh here one is less than equal to one so okay we if we put this one over here and we forward this over here okay v p one v forward it now what we do is now two is greater than one right so now it comes to this condition that uh this is array of p1 is uh greater than rf p2 so we need to change it so now what we do is we copy the value of p2 here so we copied one over here and we advance p2 to the next index now we see again uh that if up array of p1 that is a 2 is it greater than 3 no it's less than 3 so obviously we will uh put the value of p1 first so we put 2 over here okay and we forward p1 so p1 comes over here on three now is three uh less than equal to three perfect so we put the p1 over here okay and p1 reaches its end and only p2 like here in this second section only one element is left so we just put it off over here so the final sorted array over here is one two three so this array will finally get converted into the final sorted array using this merge sort algorithm so as you must have seen that this was basically our total merge sort uh algorithm and at every stage we are basically dividing it into uh like two uh par two sections now at every stage of the uh section that we are making we divided this whole arrant into two sections first then we again divided that uh like both the sections into two of its other sections so this way this whole dividing process will take a time complexity of login order of login okay and this merging thing okay this merging that is happening all around like this merging that emerging so it all of these merging techniques will uh effectively take a time complexity of off and order so when these both things are combined so the total uh effective that is uh the total effective uh time complexity taken by merge sort algorithm is o of n log n okay so the total time complexity effective time complexity taken is o of n log n okay so this is our merge sort algorithm now how will we implement our merge sort algorithm uh for doing this specific question that is reverse pairs okay fine so i will be erasing all of this over here so what was our array again it was uh 1 3 2 3 1 right so we will write down our area here 1 3 2 3 1 okay so now uh in this question uh we have to basically find i'll write down those two conditions again i is less than j and r a i should be greater than 2 into array of j okay so we have to find uh all such i j k pairs okay i j pass we have to find all such pairs so what we are going to do is that we divide it in the same fashion okay we just divide it in just like the same fashion that we did over there also uh in merge sort so we did this uh three one over here okay so here the you know what the only difference that we're going to make is really simple we are still going to merge uh like merge sort this the whole merchant algorithm will still apply on this question too we'll have to sort this we're dividing this and we'll again have to sort this again just like it happened in the merge sort algorithm but in the meanwhile in the middle we'll also have to include one more step okay remember when i told you that you will be given one like we will have to take one p1 and then we'll have to take one p2 you remember that part right so uh what we do is that in the meanwhile in the middle when we merge these like these two sorted arrays like suppose this is already sorted one three one two so when we merge these two arrows okay in the merging part what we'll have to check is we'll have to insert this condition during the merging part okay so we'll be checking if array of p1 okay if it is greater than 2 into array of p2 because as you can see p1 like p2 is starting from the second section so it will always have to uh like lie on the right side of p1 that it will always be greater than p1 so that condition is already satisfied that is i uh less than j p1 less than p2 so here the only condition that else that we need to satisfy is that array of p1 is greater than 2 into array of p2 okay and this condition we will try to satisfy when we merge these both uh sections so now as you can see that when we try to merge this uh like we will get into one two three okay one two three uh sorry one more section so we will get the final areas one two three but as you can see here no uh like no such uh pairs of p1 and p2 will exist which exists uh which uh you know uh satisfy this specific condition so okay we reach here we have one two three over here okay and as you can see this will get swapped so this will become one three so we have one two three and one three over here okay perfect so now what we're going to do is that uh we are going to put our p1 over here as usual we're going to put our second pointer over here at the first index over here zeroth index and what we're going to do is now we're going to try to again set like move and satisfy this condition okay uh so uh as you can see there are uh basically here there is one uh point of p1 like suppose if p1 is over here and suppose if p2 is over here okay if p1 is over here and p2 is over here so in this case we are going to ha uh we are going to see that uh this condition stays true right because three if rap1 is three right it is greater than two into one so yeah this condition is true so if from here what we do is suppose we have a count variable okay that is counting our reverse pairs so we just do count plus if we find this condition over here and also okay fine we want to count plus okay here it is very easy to see because there is only one element will not essentially do count plus we will do count uh plus equal to mid minus uh this p1 plus one now i'll tell you exactly why we do this okay mid minus p1 plus one why we do this see the thing is that suppose uh this like this is the mid you know right when uh like this array when we divide it we know that this is the middle element so we are taking this as mid okay so this three is made over here which lies in the first section so suppose now just think of this uh that here it would have been uh like this array over here it's not one two three suppose this is one 135 now you know that this array always has to be sorted right because we have done all the swapping and all that before suppose this array would have been 135 just in case this array was 135 instead of 1 2 3 and this arrow over here is 1 3 as usual now see this when p1 will be on this three this will form a reverse pair with this one right because it obviously satisfied with uh with this condition that three is greater than two into one also if you can see every element that will be greater than 3 will also satisfy the condition right because if 3 is greater than 2 into 1 so any number greater than 3 that is 5 like we can start from 4 5 6 7 everything is going to be greater than 2 into 1 right every single element that is every single number that is greater than this 3 so we know that this is our sorted array this section is totally sorted and every element that rise on that lies on the right side of this three will be inc uh like more than three right and we know that all of them will form an uh reverse pair with this element over here so what we can do is we are simply doing cnt plus equal to this mid suppose this mid is at five okay our middle element is five just think of it so we have what we're doing is we're doing count plus equal to mid minus p1 that is mid is this so we have a plus one so we have your two elements right because see three one forms a reverse pair and again five one will also form a reverse pair so in total there are two elements over here including three that will form reverse pair with one so we did this again when we go to five will again form a reverse pair with one okay so you know that again gets added so plus one so in total it is three so just like that okay just like that we are simply going to be doing this now uh if you have uh done the questions i'd like to point this out that if you've not done the questions called count inversions okay i urge you to go and uh at least like watch any video regarding that once because this count inversions question is really important if you want to understand this question like if you have clarity on this count inversions this is just a very slight modifications of the just one step ahead of the count inversions question so if you have not done that just to go do that you will have a lot of clarity with this question too so okay fine so now we do uh now we understood that how we are counting this uh reverse pairs over here okay so now what we are going to do is we are simply going to uh like check uh that what how we can implement all this in terms of code okay so okay let's go to the id so this over here so first of all as i told you that we will be using merge sort okay so first of all i'll tell you that how exactly do you use merge sort i if you've not watched any merge sort video or any tutorial i would very much urge you to go and see that once uh because uh you know that is a very like essential form of sorting method that you should always know so it will essentially be like we will have a one merge sort function okay so i will have one uh like two indexes over here that will basically mark the starting and ending this i and j they will basically mark the starting as i was telling the low and higher left and right no so this is uh this will i and j will basically mark the starting and the ending index of every section that we're going to pass into this function okay uh so like this will basically help us dividing the array like dividing that array into specific sections and then sorting them accordingly so we are going to be doing this and then we are going to pass the array obviously and also we are going to be uh you know pass that uh we are going to be passing that temporary array as i told you one temporary array i'll explain you the functions of each and every data structure that we're using later like why you're using those data structures so okay fine so first of all what we do is uh like we basically take one counter that is reverse counter okay so first of all we apply this uh recursive step over here now if you've not watched merge sort i'll just uh like urge you to go and see that once because otherwise this whole concept would not be very clear to you so here uh we'll basically be doing i plus j uh by two and uh just to avoid the overflow we are going to be writing that in a more fashionable way that is i plus j minus 1 by r2 and by 2 you can write it as this uh right shift one that does the same function so ref c plus equal to merge sort uh first section that we're going to pass is from i to mid i is basically the starting point initially we're going to pass it to zero so zero to mid and then mid to uh one once uh like once we called it from uh zero to mid like i to mid so we put the temp and nums over here and then next time we make one more recursive call okay that is i uh that is uh this mid plus one now we covered the section from i to mid now we're going to move from mid plus one to j that is j is our higher the end of the section that we're passing this merge chart function so we are going to be doing this and the last uh thing that we're going to do is merging we also have to have a function that merges both the sections right in the sorted fashion so we're going to be passing this i mid j temp and nums perfect and ultimately we're going to return the maximum like the total reverse count that we have gathered so now let's write the merge function okay that merges both the uh sorted sections of the array so here uh we will be taking the starting mid and the ending of the section of the array we're going to be taking the temporary array we're going to be taking the array that is given to us okay so uh i had also to point out this in that in this merge sort function we're also going to be writing a base case that is i greater than equal to j because if the starting of the array itself is greater than equal to the ending of the array then obviously it will not return any reverse count it will just terminate this is the base case in recursion basically if you don't know that you can watch any recursion videos so um fine so this is uh the merge function so initially what we do is we take three uh variables okay like suppose i to make it simple i will just take it as p one and p two itself so p one we take as one okay and uh so p two what we have p two will be basically taking as a mid plus one because obviously you know right that one section i like to show you this that one section is from uh this uh like so suppose this is a p1 okay so one section is from p1 to mid and one section will be from mid plus one to p two uh sorry not p two uh mid plus one to j like i to mid it's not p one sorry i to mid and one section is from mid plus one to j okay so these are the two sections that we have divided the whole array into so here what we're simply going to do is we're going to do this and uh for the uh for just for the sake of uh you know marking the third array like the temporary arrow in which we are going to store the all the elements in the fashion are like sorted fashion we are going to be taking this p3 a pointer okay so okay done so now first of all we will be counting all the reverse space okay so we start uh writing uh the code for counting the reverse space and what we do is we basically going to be uh like running a loop uh which will be basically from p1 uh to mid that is from i to mid that is in the first section and also at the same time we'll also be checking for the second pointer that is from mid plus one to high okay that is j so we're going to be doing this now simply what we're going to be doing is we're going to be like uh we're going to be cutting it short we're simply going to be checking for uh the reverse base okay so if nums of p1 is greater than 2 into nums of p2 now i have to point one thing out that multiplying with two now suppose it's a very now as you can see these are constraints over here it's like your uh in like this number can basically range from negative or the intima this is basically the most uh less value least value of that an integer can hold and can uh range up to the like the most that maximum value that an integer can hold so if it's two into something like this so it'll obviously overflow right the integer will overflow so what we simply need to do is we need to convert into a long okay so the range of long is obviously greater than uh this so we simply do this and uh just to for the sake of comparing it we are just converting both into a long okay so now what we do is that uh if this condition for our reverse pairs if this exists we're simply uh going to be taking a reverse count over here too and here what we're going to do is as we discussed in the in our approach we're going to do reverse count plus equal to uh the mid plus 1 minus this p1 right here that's all that we want to do over here okay and at the same time we are also uh we moved our p1 array over there uh like our p1 pointer over here so the same thing we're going to do over here also so here uh the like if this condition is not holding basically so uh sorry i'm i think i just missed it over here we don't do p1 we increase p2 if this condition doesn't hold that means that we simply have to increase p1 here okay so this is how we counted the reverse space okay now after counting the reverse space as i said that the merge sort algorithm will totally appear in this question too so we'll have to merge the array so that in every such like every sorted uh like while combining two sorted arrays we can count this uh number of reverse space in order to do that we'll merge uh we'll also have to merge uh the array two sorted arrays at every step so now we're going to basically come into the merging part okay merging into a single sorted array so what we're going to do is we're going to reinitialize p1 to i okay did we change the value of p2 uh yeah we also change the value of p2 so we're going to initialize p2 to mid plus 1 as they were just before so the just the way i initialize this over here the same time same thing i'm going to do so we didn't change the value of p3 so i'm not going to change the value of p3 so it's the same condition over here okay if p1 less than equal to mid and p2 less than equal to j okay done this is done so now just simply the here we are checked for reversing like the reverse space condition right here we are going to simply check the condition for uh merge sort the uh basic merge sort algorithm that is present sorry i wrote this p1 and p2 it should be right so this is the step if this happens we simply uh like forward of p2 and if it's in normal order we simply uh you know forward our p1 but here as you can see that we have also taken and like we have to store this sorted fashion like element in one other array we're going to be using this temp array for the same so we are basically going to be storing this over here okay the element at p2 we're going to be storing at p3 and we're going to forward port p3 and p2 so this is going to be like storing all the elements in our sorted fashion okay this is just the way that i've explained earlier in this uh on the whiteboard on the blackboard so this is basically the same essentially the same thing so we did this now we have we are checking that if in any of the sections now this basically we have merged both the sections but if it might be possible that in any of the sections there are some of the elements that are still left so in that case we're simply going to you know put all the uh all those elements also in the final array okay if p1 is less than equal to mid i'm sorry if p1 is less than equal to mid then we are going to do uh we're going to put all those up left uh values in this first section to temp and if p2 is less than equal to j we're going to put all the leftover values in second section to temp okay as simple as that we did that now what we have to do is we have to copy now we have stored the sorted values in temp now we have to copy all those sorted values into the final array right to make it finally sorted so what we do is we take uh this like we go from i to g i n j where are the like first and last index of our the whole section that we had passed on to this function right so we will go from i to j and we will copy uh all those values nums of x uh is equal to temp of x that's what we did and we return the reverse count from here okay fine perfect so uh this is all we did okay this is all we did we have merged also we have counted uh the in reverse pairs also we have merged them also we've merged the array and then we have returned the reverse count so now writing the main function uh that had been given to us we're basically going to return this like first of all we'll have to make this a temp array right like we're going to be passing the reference to the temp array and so that our space is saved so we're going to be defining it as the same size of nums because uh in that case we won't be able to d we won't be having to deal with a lot of index playing so we just simply store it at the index that it is so we do this and then we return this merge sort function zero comma the last index of nums like initially as i told you we're going to be passing on the full array right as the as one whole section so we're gonna be passing this and we're gonna be passing the temp array and we've been passing the nums array okay so let's see if it runs properly so okay so i think this is uh nums it should be nums over here right because yeah it should be numbers away i wrote array so the whole crux of this uh merchant algorithm basically lies in this merging part like this is where you uh play with all the uh you know so let's test it okay so fine so let's test it on other example cases this is a problem with lead code that i'm facing recently like you can't run the code frequently so fine this is producing a right result so let's submit it and check okay so it's passed so as you can see that in this code we have essentially like let's break down the intuition behind like why did we choose this merged merge sort algorithm the only crux of this uh that of this question that lies in our mozart algorithm is basically this step over here okay this step right here this is the most important step that we have okay this is why we're using the smart chart algorithm just to like during the merge sort algorithm when we uh like when we have an option to merge both the arrays right both the sorted arrays now while doing that we haven't we are reducing the time complexity significantly right here because suppose you have an element right i would like to show you i would have to go back to the blackboard suppose you have an element over here and you are basically traversing to the right side and you are checking all the other elements okay now instead of that in this merge sort algorithm you just have to do nothing just during this merging like nothing else nothing very hi-fi is happening okay hi-fi is happening okay hi-fi is happening okay just during the merging part of the sorting you're basically checking for this reverse pass and if this reverse space exists you don't again have to check for all the elements on the right do you imagine you if you find one reverse pair then for this uh first pointer if you find that this forms a reverse pair with this one over here so you don't have to check like this sorry not this is unsorted this is a sorted one so suppose this two is forming a reverse pair with this one suppose uh so uh in this case like three let's take this three is from your reverse pair with one so in this case you don't really have to again check that for five or any element suppose this was one three five seven nine and it goes like to a very long section suppose you had that you don't have to again and again check for each and every element that lies on the right side of three right you know that all the elements uh that are greater than three will always be greater than uh you know always satisfy the condition of the reverse pairs with one if three satisfied the reverse space condition with one all the elements that are greater than three will also satisfy the reverse press condition with one as uh mentioned over here so that is basically essentially are the crux of this uh of using this algorithm over here that we are reducing the complexity like we simply here we are not checking for all the elements that lie on the right side of uh this point of one right on the right side of three we are simply doing wherever we have our mid okay in the first section wherever we have our mid we just do mid minus p1 so the all the elements that lie between p1 and mid inclusive of p1 and mid are basically all of them are will be forming a reverse pair with this one so we know we do that in like oh one operation the same thing that we had to do in of uh n likely to search all the things all the elements on the right we do then o of one and essentially as this merge sort totally requires an o of n log in time so we are not doing anything very special over here we here also f effectively in this uh in this question also uh since we are using the same algorithm just one step we are adding and it doesn't change the average time complexity so it basically stays off n log n so we reduced our time complexity from o of n square to time complexity of o of n log n that is significant so uh here basically that is the crux of the algorithm we first have to like i showed you that how to write the merge sort if you're not really clear with the smart sort uh algorithm writing then you can just go and watch some tutorial based on that and apart from that this part is the this line is the main crux of the whole uh program that we have written so that's how it is so i would urge you to do two problems if you have not already done them first is account inversions that is present on lead code and uh the one more problem is basically the merge two sorted arrays that is also present on lead code so uh both of this you can do and you can get a better clarity of this question so this is basically like a cherry on top of those both questions so that's all for this video if you have uh enjoyed this video you can like and you can put your suggestions in the comments for the next upcoming videos if you have any requests i'll be uh ready to solve those questions for you thank you and have a great time
Reverse Pairs
reverse-pairs
Given an integer array `nums`, return _the number of **reverse pairs** in the array_. A **reverse pair** is a pair `(i, j)` where: * `0 <= i < j < nums.length` and * `nums[i] > 2 * nums[j]`. **Example 1:** **Input:** nums = \[1,3,2,3,1\] **Output:** 2 **Explanation:** The reverse pairs are: (1, 4) --> nums\[1\] = 3, nums\[4\] = 1, 3 > 2 \* 1 (3, 4) --> nums\[3\] = 3, nums\[4\] = 1, 3 > 2 \* 1 **Example 2:** **Input:** nums = \[2,4,3,5,1\] **Output:** 3 **Explanation:** The reverse pairs are: (1, 4) --> nums\[1\] = 4, nums\[4\] = 1, 4 > 2 \* 1 (2, 4) --> nums\[2\] = 3, nums\[4\] = 1, 3 > 2 \* 1 (3, 4) --> nums\[3\] = 5, nums\[4\] = 1, 5 > 2 \* 1 **Constraints:** * `1 <= nums.length <= 5 * 104` * `-231 <= nums[i] <= 231 - 1`
null
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
Hard
315,327
80
Hello Hi Guys Welcome to Your Deeds and Such Today Solving Questions Remove Duplicates Question Remove Duplicates Another Posted in 1231 Subscribe Number One to Three What You Want the Giver Has * Repeat a Number 100 is too deep to be repeated or * Repeat a Number 100 is too deep to be repeated or * Repeat a Number 100 is too deep to be repeated or not done Tomato Sudhir Withdraw from the post After point to that point when skin number posts from to is what is the element there appearing mordhan device with the one status not compare this element at index - element and will not take place value channel subscribed to the enmity elements and Friends Will Need To Follow And What Will Start From To [ Start From To That I Will Teach You I Will Not Listen What To Do Take Off Measurement Not Able To Find Replace Big B In subscribe and subscribe the Channel to set up alarm makes and not submitted so the time complexity of algorithm and complexity a
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int\[\] expectedNums = \[...\]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\] **Output:** 5, nums = \[1,1,2,2,3,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,0,1,1,1,1,2,3,3\] **Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\] **Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order.
null
Array,Two Pointers
Medium
26
349
hey everybody it's me Abdullah welcome back and today I'll be doing another lead code three four nine intersection of two arrays an easy one given two integer arrays nums one and nums two return and array of their intersection each element in the result must be unique and you may return the result in any order so we do not have to we can't have duplicates in our output list and we have to just return the intersection point there was a function in Python at least where you can just set the numbers because we do not want the duplicates and then perform the intersection with set again with nums 2 and that's it we'll be writing another solution to open slot second yeah this works so what you will be doing now is just setting nums 1 and nums 2 and now I'm drawn and set numbers to we are done we will be making our output list and now we will check for I in nums one okay that I is in if I is in nums 2 also what we will do is just append it to our output out output oh not this okay so append that I and after this we are just done we can just return I think our output and that's it
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
1,685
hey everybody this is Larry this is day 25 of the leco day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm uh I'm still in okanawa in naha um yeah I got to remember to do the intro so maybe tomorrow but yeah today's Farm is 1685 some of the absolute differences in a sorted all right so you given a num sorted non deing order built an inder sne so hang on oh man sorry friends hang on um all right well got that out of system Let's uh let's continue on the problem shall we summation of absolute differences between Nam and all other elements in theay H what does that mean so 235 where's 235 oh wait what huh all right let me reread it build and return it with the same length such that we saw I is summation of absolutely Lo differences between num of I and or l oh okay so this four means uh 2 - 3- 5 okay um I mean I think this is kind of tricky but you have to uh I mean so n is 10 to the 5th so you know that you have to do it in N log end time at wor n square is going to be too slow um maybe you could do something exotic to all the complexities but I don't know uh I think the idea behind this problem is just is going to be built for one thing and then slowly work your way through the other incrementally right if you're able to do that then you're able and you have to do it you can really calculate every time because that's n Square so yeah so let's say we have the answer for the first one right so yeah so for I in range of N I say we have to something like this right okay and then what does that mean that means it's okay and um oh and this is sorted so that means I don't actually don't need absolute value I forgot about that okay and then now we're trying to build it uh incrementally right and the way that I would think about it is uh let me actually just pull up a painting thing right hang on and again oh what was going on here uh there we go yeah I'm on the touchpad so forgive me for a little bit for uh you know bad drawing possibly so you have basically the number line right uh and in this number line you have a sorted list of um can do they have to be unique I guess no they could be the same only go 10 to four as well but yeah basically you have some uh you know let's just say points let me change the color real quick you know points that we care about right it doesn't really matter what they actually are and then the idea is that okay so let's say we have an answer for here for the leftmost one right let's just say the sum is some t for total right then now going to the right just sweeping then we just have to do math basically now we have this distance right and let's call D for Delta gez let me try again and basically because you're going from left to right um You have all these amount of them that's going to toh subtract D each right so that's going to be just the number of them uh multiply by D or yeah know subtract I mul ID and then subtract it and then everything to the left we add d right because now um should have added a few more things I mean in the beginning there's um obviously in the middle in the beginning there's nothing to the left but then as you get more and more then now you have plus d and minus t so that's basically the idea that we're going to use here and yeah and that's know with that visualization in mind it should be okay to uh calculate so yeah let's see so yeah okay so now we moving so Delta is going to be N Sub I minus N Sub i- one right to be N Sub I minus N Sub i- one right to be N Sub I minus N Sub i- one right and then how many things are to the left of answer of sub I which where it increases Delta right well um there should so if I is the first element then there's one element that's going to increase so it should be just I * Delta so we add should be just I * Delta so we add should be just I * Delta so we add um yeah so it is the previous answer plus I plus Delta and then minus um how many are on the right it should be n minus IUS one maybe or maybe minus two something like this and that's pretty much the answer though and then we return I might have to actually count all right so let's say if I is one uh and N is say five how many numbers are to the right um well it's going to be 1 2 3 4 so yeah uh oh oops oh I meant oh oops wrong uh thing huh same thing again confused way all right uh why is that h i mean we should at least get the first element right so maybe we just have a typo somewhere also negative is definitely no good oh this Delta has to be absolute value but that shouldn't yeah that shouldn't change the other what is going on here tell me why okay so um why is this doing it do oh why did I put I need this to be this yeah okay I think I confused it a little bit all right there you go uh when I converted to an sys okay so yeah uh let's give a submit and that looks good 1334 day streak uh and obious see you know we can do the complexity it's going to be linear time linear space you can do better on either linear time because well you just have to look at food away so that's the lower case or lower bound sorry uh and space is going to be of n because that's what you're returning so can also cannot do better than that uh yeah that's what I have for this one let me know what you think stay good stay healthy to go mental health I'll see yall later and take care bye-bye
Sum of Absolute Differences in a Sorted Array
stone-game-v
You are given an integer array `nums` sorted in **non-decreasing** order. Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._ In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**). **Example 1:** **Input:** nums = \[2,3,5\] **Output:** \[4,3,5\] **Explanation:** Assuming the arrays are 0-indexed, then result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4, result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3, result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5. **Example 2:** **Input:** nums = \[1,4,6,8,10\] **Output:** \[24,15,13,15,21\] **Constraints:** * `2 <= nums.length <= 105` * `1 <= nums[i] <= nums[i + 1] <= 104`
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
Array,Math,Dynamic Programming,Game Theory
Hard
909,1240,1522,1617,1788,1808,2002,2156
639
Hey Already Guys Welcome To Our Channel Tweet Sunny And You Will Be Talking About Telescope Problem And Its Name Is Back Roadways Se Contents And 163 Interest Categorized As Hata Problem Playlist Ko Tit Soe Singh Ka Meeting Special Video Like You Will After A Long Time E Think It Was Quite Busy Software Second Hour WhatsApp Free Time Show I Think They Should Have To Make Video Recording List Of Positive Guys So I Can Think The Number Of Likes 0 Dislikes Why This Means That And Run More Not Been Able To Do Subscribe Cigarette Counter Total Number of Births Studio Code Particular Like Being Given String OK Sorry for the talk about Subscribe Like You Know the Concept of Dynamic Programming Subscribe Now subscribe to the Page if you liked The Video then subscribe to The Amazing Containing Tales From Which Can Be Included In the following manner at midnight and effective year gone into the notched for its own up to likers dedicated addition to decode particular important messages for all the best pick group and the map back into the letters in the river sindh mapping and dad what are the thing But will explain this in various employment like the sun considered extremely 1110 69 you can see 55510 6 subscribe and acid and total subscribe and subscribe pimp ko particular digit so they not love letter particular number dissolve a bit this point time digit Solitaire ch1 Unfit A Stand Still Lying In The Mid Term Character ch2 Andhe Tubelight ch3 ch2 Subscribe To A Chief Whip One In This World Can Also Give One 06 Egg White The Video then subscribe to the Page if you quid described and candy multiple ways me too Find the total number of vacancies Dancer can be launched by considering by taking small with his prime number at the question is not like Pratima simple question is like modified to make a complex system person in addition to subscribe this Video not subscribe The Channel Please subscribe and over and subscribe that testicles 129 we need to find the total number of this oil please like streams and me from time to time every effort flirting what is the number of S2 deposit right now looking for the problem statement Vikram Slightly complex will start Character skin twist introduce obscene poster this typing or its tricks introduce right now comes to bring to front doing total number of his two-day co dependence and number of his two-day co dependence and number of his two-day co dependence and conditions with students model 10.1 superintendent conditions with students model 10.1 superintendent conditions with students model 10.1 superintendent temples and detail na dhrau solution is like you can also consider of solution But I don't thing login solution is going to like to request to solve this problem using dynamic programming for the topic Anmol is going to talk about meeting so let's move forward to understand this problem with help of Shiksha Temples where built the best solution for this. Problem Night So Let's Move On To Your Solid Start With Tanning Sample Vighna Vinson To Start You Can See But What Is Going To Let's Talk But Very First Character Video First Character You Can See I'm Not Talking About This Point Stock But Tire Subscribe Like To 728 So And Observations From One To Know What Is The Subscribe Button And You Can Do Subscribe Widow Considering The What Is This To Ansh Like Behind Gas Okay So Its Term Electronic Cigarettes Start From One Injured In More Subscribe And Like Subscribe Now To The Number One Can Enter Subscribe Button More But Tarzan Oak That He Human Dubai Is Like Doing Enemy Friend Okay Soft Dough Ponting Right Now British 181 More Okay What's My Channel Subscribe And Skimming Tours That Sufi Low Cover Ho Like To Start This Coming Of Parshad Jaswant Example So Let's Move Forward To The Approach Of Virgo In To-Do's Black Dynamic Programming To-Do's Black Dynamic Programming To-Do's Black Dynamic Programming Solution Ugar Ne In His Interview Christmas Meeting One Talking Water Frequently Dynamic Programming Okay So Let's Talk But What Is Pollution Love You All Like This Problem Install This With Dynamic Programming Night Okay Not Considered As Example Like 12:00 Start Considered As Example Like 12:00 Start Considered As Example Like 12:00 Start Reel Okay Now You Can See Listen To Particular Event To Decode It Is Like You Can See Late Can They Like It Well And Can They Stop And Three Idiots Or Can They Stop And Subscribe Like First Decoding Subscribe To The Like Subscribe And 2 And 112 Others Like This Looters Sequence E Know You Can See What Do Something Called Overlapping This Channel Like This Subscribe Mode on this tumor subscribe Video then subscribe to the Page if you liked The Video then subscribe to this value and computer labs for the balance of this translation into computers for the total number of cost to decode distinguishing you need not destroy this patient provides Religious Programming And Programming For Considering That Strike And Talking Subscribe And Like Subscribe And Can Very From Way Subscribe Quid Means Date For Entry Into Different States Have Been Introduced Many Characters Right Now Over Jhari Lavai Need To Know All Subscribe Screen More Subscribe Example Like subscribe and subscribe ok if you need to know what is the number of this subscribe must subscribe the ladies toilet me and decoding ok there is one more year decoding deposit is here about 6 you can see your traces lights S2 is like to You can directly invalid decoding backstreet boys one or rate countries like it disturb 6od prohibition decoding and start mode 2012 subscribe The Channel subscribe like this point upon what is the present to avoid subscribe now to find the total subscribe to that ripe solid savior in Minute DP Are cases pending cases of district today subscribe to these celebs What is the number of way subscribe and what is the number of the particular subscribe and subscribe the Channel and subscribe the way 123 like pulsar and not consist of its president witnesses subscribe like subscribe And festival subscribe like subscribe to your British like it wedding from 129 electro this point to fill up like tpf lineage adv1 person to ok now school staff quarters to-do list pick up in quarters to-do list pick up in quarters to-do list pick up in particular and talking id subscribe to the Page if you liked The Video then subscribe to a noise s3 start raw possible grease is s30 like weddings from one character vansh and it's kind enough to this character not talking id subscribe like this time subscribe this Video plz subscribe Channel that Bigg Boss important partitioning over different deposits - Pandit Nand Singh Life is like deposits - Pandit Nand Singh Life is like deposits - Pandit Nand Singh Life is like a straw nikale 1000 from one to take medicine tarzan the co subscribe like subscribe and can very from 9th ok no of protestors from 129 vacancy date derivatively one possible way ok shoulder should not tourist hobby to effective 12951 possible two Take Medicine Like Subscribe Possible Like To Know Witch Element Plus Minus One My Favorite Song This More Like Partitioning Over Navodaya Avoid You Can Also Partition Dushman Over All Notification Over All Possible So Let's Talk About The Do Subscribe My Channel Like More Subscribe Now to like and subscribe like subscribe and that effective taker fit start and now e want to talk to digest three ok not the volume impossible key see ok no effective system inverter dad three withdrawal start subscribe like this can be field within ourselves and not possible to consider subscribe 12951 more share and subscribe must media not talking toe hai dushman 21381 what dushman hai loot ok so let's talk about this point two they can have one vikram two and they can have three long dense of tennis golf 251 adhuri suid over the Number of this Video give and subscribe 10 I show you Ephesus S2 resources and what is the number of subscribe partition in times of - subscribe notification is in times of - subscribe notification is in times of - subscribe notification is not equal to stop acid attacks subscribe 123 liye subscribe jis position subscribe 123 456 idma labs for boys qualification For Dushman To Aaya Researcher Condition The Taste Of Math Class Loosening 12602 Possible West Wife - Ya Ko 12602 Possible West Wife - Ya Ko 12602 Possible West Wife - Ya Ko Adarsh ​​One More Peaceful Life Ironing Adarsh ​​One More Peaceful Life Ironing Adarsh ​​One More Peaceful Life Ironing Slide Great Do Subscribe Button Shiksha Niti Govind Saraswat Like It Is Like It Means The Time To The Principal Is Not Talking Id 2017 Subscribe to the channel Like This Member That's OK Know What About Waste Is Not Equal To Start Waste Is Not Equal To Return To Avoid All The Possible Benefits Or Latest Dresses Like Places Not Think Of Krishna President David subscribe this Video Talk To Me OK Know The Thing Is Like Effective Who Defeated 2012 Find Out The Things Different Office Let Not Talk About This Alive And But Must Subscribe Blue Star Key And Space Research Not Equal To Stove Ne Brahmani Possible Kiss Like It Is 182 Space Create And Stree Is not equal to start with you find out all the possible is like 9 am talking about this estimated start and activities like one and to 9 this incident is talking about this cash withdrawal is equal to and is not equal to think what this like This Position System Subscribe Possible Unit - 20121 Subscribe One To Unit Two Increment And Service Six Times Of Deposit - To Not Six Times Of Deposit - To Not Six Times Of Deposit - To Not Considered One More Thing Subsidy Na Modya Not Able To Stop This Not Equal To Mid Term Character Of Units Withdrawn In The Middle Subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Famous Points of Economic No Units Ko Debt of S Fast S Possible So Lets Move Brotherhood According to Main Aapke Show A Single Step Isko 10 Submissions and Dislikes Goodbye End Awards Optimized Space in This Okay So Let's Talk About the Way Can See It in LS Long Term Deposit See the Interior Maximum Vendors Model Has Not Disturb Difficult Plus One of the Best Places to Return Because They Know the Way to Decode World Cup 2015 Like Video And subscribe start from 2nd subscribe no interview subscribe this Video not provide questions for vacant positions one to like multiply my likes and the way to decorate the best position and define this diwali for any improvements you dance like this point next9 2220 just go With the previous one liquid like us to get the character like this is not know what about introduce character notification like this is the position of to subscribe benefit from one adhikar TV9 spoken in this note start and content is cycle daily 126 you can see do it Is the like to where is the chief minister of the subscribe to the Page if you liked The Video then subscribe to subscribe that character to effective strike acid bases check out my second Characters will mark this necklace Technical Tips 6 And You Can See But You Need To Go With Upavya So 08000980009 Video And Subscribe YouTube Channel Latest Updates For Watching This Video In
Decode Ways II
decode-ways-ii
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 "`. **In addition** to the mapping above, an encoded message may contain the `'*'` character, which can represent any digit from `'1'` to `'9'` (`'0'` is excluded). For example, the encoded message `"1* "` may represent any of the encoded messages `"11 "`, `"12 "`, `"13 "`, `"14 "`, `"15 "`, `"16 "`, `"17 "`, `"18 "`, or `"19 "`. Decoding `"1* "` is equivalent to decoding **any** of the encoded messages it can represent. Given a string `s` consisting of digits and `'*'` characters, return _the **number** of ways to **decode** it_. Since the answer may be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "\* " **Output:** 9 **Explanation:** The encoded message can represent any of the encoded messages "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 ", or "9 ". Each of these can be decoded to the strings "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", and "I " respectively. Hence, there are a total of 9 ways to decode "\* ". **Example 2:** **Input:** s = "1\* " **Output:** 18 **Explanation:** The encoded message can represent any of the encoded messages "11 ", "12 ", "13 ", "14 ", "15 ", "16 ", "17 ", "18 ", or "19 ". Each of these encoded messages have 2 ways to be decoded (e.g. "11 " can be decoded to "AA " or "K "). Hence, there are a total of 9 \* 2 = 18 ways to decode "1\* ". **Example 3:** **Input:** s = "2\* " **Output:** 15 **Explanation:** The encoded message can represent any of the encoded messages "21 ", "22 ", "23 ", "24 ", "25 ", "26 ", "27 ", "28 ", or "29 ". "21 ", "22 ", "23 ", "24 ", "25 ", and "26 " have 2 ways of being decoded, but "27 ", "28 ", and "29 " only have 1 way. Hence, there are a total of (6 \* 2) + (3 \* 1) = 12 + 3 = 15 ways to decode "2\* ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a digit or `'*'`.
null
String,Dynamic Programming
Hard
91,2091,2251
67
hello and welcome to another one of my lead code videos and this one we'll do lead code 67 add binary this is basically creating a binary Adder so the question is very simple we're given two binary strings and we have to produce an output which is another binary string that adds the two binary strings and note that the strings could be of different lengths so we need to take care of that so what will be our approach to solve this problem basically we can just think of a binary Adder right so let's say we have you know some number of bits to add like this and you know at each point in the adder will produce a sum bit which is the sum over here and a carry bit which will carry over right so in each round we'll produce a sum and a carry and since this is a binary Adder everything is either just zero or one so we can just create a truth table to see you know based on the values of the A and the B what will be the sum and carry bits right and then obviously if the you know let's say if one string is longer than the other like this then we'll just fill in the remaining with zeros right so we'll just pretend that there are zeros in the places of the shorter string so first let's create our truth table right for the sum and the carry bits so here I have the heading of the table we have the previous carry right at each point we have the previous carry bit we have a and a b which is the current index we're processing and then we have to compute the sum and the next carry bit right so to fill this up I'll just fill in all the values all right so here we have our table basically if a and b are 0 then the carry 0 the sum is zero and you know if this is the previous carry bit so if a and b are 1 and the previous carry bit is zero carry zero write one right and so on so basically if you notice if there's only one because that will be one right so we carry zero we write one in the sum if there are two ones like here right we basically carry one and write zero because that's two in binary and if there are three ones like in this case we carry one and write one right so this is how you fill the table just using binary Edition right so we'll use this when we write our code so let's go ahead and write the code we'll start by initializing our a index equal to a DOT length minus one because as you can see the addition algorithm goes from you know the back of the string to the front of the string similarly we'll do the same for B and we'll initialize our string Builder which will be our answer and for the answer we'll just append all of the values of sum right and at the end if we have a carry that's greater than one meaning it even after the last addition we have a carry we'll just append that carry at the end so we'll have a string Builder equals to new string Builder and obviously at the end if carry right is true we'll append another one to the answer and then we'll return and start reverse dot to strain right because all of the numbers will be also appended in reverse and our answer because we'll be starting from the right to the left right so now let's go ahead and write our Loop so we'll have while any of these is greater than zero right so if either a is greater than 0 or B is greater than zero we'll keep going right because we haven't finished the strings and so we'll compute our and we can just use Boolean because all of these will be zero or one right so the a string will be set to 1 if obviously a index is greater than equal to 0 means we haven't yet run out of a and our a DOT car at a index is one right so if this is the case a will be 1 otherwise a will be zero and we'll do the same for b as well right and at the end of the loop obviously we want to just decrement these two indices as we move you know further along to the left and what we want to do also is we want to maintain a carry bit right so initially our carry will be false because we're starting with zero at the start and so then you know let's compute our sum and our carry based on the table below and obviously what we'll do is to our answer we will append sum right so if sum is uh one then we'll append one otherwise with a pen 0 right so this is our whole structure and now let's compute the sum and carry based on the table here so if you notice the sum is just going to be the xor of everything right because if you just ignore the carry for a moment if you just look at A and B you'll notice that sum is a X or B right because if they're the same we're going to end up writing 0 and if they're different we're going to end up writing one and so then you can imagine that becomes the new A and B and then we add that with whatever carry we have right so the sum of a plus b in binary is a X or B right if you just want to get the sum bit right because if it's uh one you the sum bit becomes zero right because you carry over that one and so then when you have the new sum bit then we can just do that plus C right and for these two it will just basically be a X or B X or C right so for the sum bit we'll just xor everything and you can validate from this table that this formula holds true right so we'll just say ax or B X or c for the carry bit if you look you know when carry is zero right then the new carry is just only when A and B are 1 right so it's going to be a and b when carry is false but when we have a carry you know the next carry is only zero if both A and B are also zero right so it's good a or b or one then the next carry will also be one right so what we'll say is carry is equal to carry question mark A or B right because if carries one it's our next carries the or of A and B otherwise if carries zero It's A and B right and obviously this shouldn't be a new value because we have to update our carry and carry it on to the next Loop so yeah I believe this should do it let's comment out this part and see how this does oops I have some variable naming issues here so I'll just name this A and B and this okay this is named A and B so I'll just name this a num and B num and change all right I have updated the booleans let's run it this should be carry this needs a function all right accepted let's submit perfect 100 solution thanks so much for watching I'll see you in the next video cheers
Add Binary
add-binary
Given two binary strings `a` and `b`, return _their sum as a binary string_. **Example 1:** **Input:** a = "11", b = "1" **Output:** "100" **Example 2:** **Input:** a = "1010", b = "1011" **Output:** "10101" **Constraints:** * `1 <= a.length, b.length <= 104` * `a` and `b` consist only of `'0'` or `'1'` characters. * Each string does not contain leading zeros except for the zero itself.
null
Math,String,Bit Manipulation,Simulation
Easy
2,43,66,1031
374
Hello, my name is Suren and this is a solution with analysis of the literary code for task number 374 Yes Number Higher or lower, in fact, this is just an implementation in code of the children's problem Guess the number. For example, I guessed one number from one to a hundred. Guess what number if you randomly search for some- then Number two then 90 then 70 some- then Number two then 90 then 70 some- then Number two then 90 then 70 then 50 then 95 then you will guess for a very long time and in the worst case you will go through all the numbers and in the end you will guess that it was for example 13 but if you are familiar with binary search and guessing all of them gives you hints the number is greater or less then everything is very easy to solve here, you divide the entire list in half and look either on the left side or on the right side, depending on whether you were told a larger number or a smaller number Well, or you guessed it if you are not familiar with this yet Let's draw briefly and then write the code Let's imagine that I guessed a number not from one to a hundred, but only from one to children, this is the range Let's draw and here we have somewhere in the middle, we'll put here 2 3 4 5 6 7 8 9 and number 2 3 4 5 6 7 8 9 now I guess a number and in the problem the computer will guess the number, but I ’ll write here for example seven and in this ’ll write here for example seven and in this ’ll write here for example seven and in this case if I guess then I look in the middle, take the five and ask if five is greater than seven or not. If I get back greater than then I will search in the range from one to four And if I get less lower then I will search in the range from one to 10 and it turns out If five was guessed, we won’t five was guessed, we won’t five was guessed, we won’t find anything No, I can get back the answer correctly, this is the correct answer, then we say everything is ok and we return the result, but if we still don’t give this result yet and look further, then don’t give this result yet and look further, then don’t give this result yet and look further, then we look, since five will be less than seven, then we need to look in the range from 10 to 10, and therefore we are now not looking in the entire list A by so that what is left from STI to 10, we look where we have the middle. Let's say we hit the eight and look and the howl will be greater than greater then or less than lower then and if the howl is more than Seven then we need to look in the range from seven to seven And if eight is less than Seven then we are looking in the range from de to 10, again this is not equal to seven, so we are not returning the result yet, but we understand that we need to go to the range from 6 to seven, so we select from here and look, we can take six and check in the same way understand that this is not something to go to a larger range and stop only in the range of seven and then we will select this Seven and give it as the answer, that’s the whole Seven and give it as the answer, that’s the whole Seven and give it as the answer, that’s the whole binary search and the complexity of the logarithm here in time will be about from the logarithm of N because we will reduce each time twice and from memory we are not doing anything extra here. Therefore, it will be o from one, that’s all, now we can go to the code, that’s all, now we can go to the code, that’s all, now we can go to the code, since the number that the computer has guessed is unknown in advance, we need to use a special interface to test our hypothesis, so there is a GS function where we pass our number and it returns the same number in response and we need to understand if we received -1 from the need to understand if we received -1 from the need to understand if we received -1 from the GS function, it means that we need to look in the direction of decrease, if one then we need to look in the direction of increase. Well, if it’s zero, then we’ve definitely found the number and we if it’s zero, then we’ve definitely found the number and we if it’s zero, then we’ve definitely found the number and we just need it return Let's designate the boundaries of the range where we are looking and the left side will be zero and the right side will be N and N, including can be the answer, for example, the computer guessed 10 and we can have numbers up to 10, so we definitely take N into account and do not reduce it, for example, by -1 and Next we need to for example, by -1 and Next we need to for example, by -1 and Next we need to just do a while loop and we check that the left one is less than or equal to the right one because we can stop at the element under the same index and see what number will be On this index Mid we look for what index is in the middle Left and we can do plus Right and then that’s Left and we can do plus Right and then that’s Left and we can do plus Right and then that’s it divide by two together or so as not to overfill the memory. If you write, for example, on some pluses, then you need to do Right mine Left, divide this by 2 and then you will definitely get the middle and not overfill the memory. Well, this doesn’t not overfill the memory. Well, this doesn’t not overfill the memory. Well, this doesn’t apply to Pine, but it’s still better to take this into account apply to Pine, but it’s still better to take this into account apply to Pine, but it’s still better to take this into account because the problem is for the algorithm and this value Mid is the number that we want to check and is it suitable? As an answer, therefore, we use the GES function to check, I will declare the result variable and make a GS with passing Mid there, now let’s make a GS with passing Mid there, now let’s make a GS with passing Mid there, now let’s check what was returned to us if -1 was returned then we need to go to the smaller -1 was returned then we need to go to the smaller -1 was returned then we need to go to the smaller side If res equals -1 and to the smaller side If res equals -1 and to the smaller side If res equals -1 and to the smaller side we go by shifting the right pointer to the middle so we make Right equal to ID and -1 because we and -1 because we and -1 because we don’t want to check the same number, otherwise elif we don’t want to check the same number, otherwise elif we don’t want to check the same number, otherwise elif we check that it is equal to one and in this case, we need to go the other way around to the middle from the left edge, do Left equals ID + 1 Well, in the latter case, equals ID + 1 Well, in the latter case, equals ID + 1 Well, in the latter case, if not -1 and not one, then we definitely hit if not -1 and not one, then we definitely hit if not -1 and not one, then we definitely hit zero and that means this number is the answer, return from here Mid that is, that the number that the computer guessed Let's press the submit button and look at the result As you can see, in about 10 lines you can guess what number the computer guessed And that's all for today, thank you for your attention, leave reactions, write comments and see you again bye
Guess Number Higher or Lower
guess-number-higher-or-lower
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible results: * `-1`: Your guess is higher than the number I picked (i.e. `num > pick`). * `1`: Your guess is lower than the number I picked (i.e. `num < pick`). * `0`: your guess is equal to the number I picked (i.e. `num == pick`). Return _the number that I picked_. **Example 1:** **Input:** n = 10, pick = 6 **Output:** 6 **Example 2:** **Input:** n = 1, pick = 1 **Output:** 1 **Example 3:** **Input:** n = 2, pick = 1 **Output:** 1 **Constraints:** * `1 <= n <= 231 - 1` * `1 <= pick <= n`
null
Binary Search,Interactive
Easy
278,375,658
1,197
hey everyone welcome to my channel in this video i'm going to cover the solution to this question called minimum night moves so before we start the real content i would really appreciate that if you can help the squad's channel so first of all let's resolve this question in infinite chassboard with coordinates from minus infinity to positive infinity you have a knight s square 0 which is the original point so it not has eight possible move it can make so as illustrated below each move is two squares in the cardinal direction then one square in the oscillator direction so you turn the minimum number of the steps needed to move the knight to the square x and y so it's guaranteed the answer exists and here are some examples the constraint says the absolute value of x plus absolute value of y is smaller equal to 300 so currently there is no add case worth to think about so let's think about how to solve this problem so the solution is to use bfs but during the first time i tried to use bfs i always encounter some time let me exceed it let me cover how i try to avoid that one uh in the coding part so for coding we care about the speed so don't be too slow correctness and readability we both need to guarantee that so let's raise through this function first of all i turn x and y into the absolute value of x and y that is because we suppose x is equal to minus two and y is equal to minus one then it takes the same step for us to move from the original point to x as 2 and the y as 1. so similarly for others for other possibilities like x is equal to 2 y is equal to -1 x is equal to 2 y is equal to -1 x is equal to 2 y is equal to -1 something like that uh it is just the same steps we try to move from the original point to x equal to 2 y equal to 1. so that's why we try to turn the x and y into absolute value this can help us limit the scope for us to do the search in bfs which is the way i try to avoid which is the way i apply to try to avoid the time limit exceeded so then we defined moves so there are eight possibilities of moves so for bfs we have the q and the first of all we add the original point into the queue and also we have a visited we just keep recording which points we have already visited so uh we have the destination as this but actually we don't need this one because we already tell the destination using this one this way and then we have the steps uh defined here uh staff is s equal to zero at the very beginning so uh while the queue is not empty we are just going to keep doing the bfs and at the very beginning we keep uh the current the size of the current layer and at the end of the layer we're just going to plus the steps so we go through each of the position within the current layer so if the current position is the destination then we just return the steps otherwise we are going to try to move in the eight directions so during the move we will try to see if we have already visited or if the position is out of the range because we have already turned x and y into absolute value and then we are moving uh in the direction something like this in this area if you can see my mouse so uh we just so in this way we can try to limit the scope of our search and we can save some time for the bfs and this is the way i try to use to avoid time limit exceeded and we just add the new position to the queue and update the visited and finally we are just going to return steps so the run time suppose x is equal the absolute value of x is m absolute value of y is n so the runtime is about omn something like that so i for simplicity i just rely on this platform to help do testing but in the real interview you need to set up some test cases but perhaps you need to restore that manually as well so that's it for this coding question if you have any questions regarding the solution or regarding anything feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
Minimum Knight Moves
parsing-a-boolean-expression
In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`. A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Return _the minimum number of steps needed to move the knight to the square_ `[x, y]`. It is guaranteed the answer exists. **Example 1:** **Input:** x = 2, y = 1 **Output:** 1 **Explanation:** \[0, 0\] -> \[2, 1\] **Example 2:** **Input:** x = 5, y = 5 **Output:** 4 **Explanation:** \[0, 0\] -> \[2, 1\] -> \[4, 2\] -> \[3, 4\] -> \[5, 5\] **Constraints:** * `-300 <= x, y <= 300` * `0 <= |x| + |y| <= 300` "t", evaluating to True; "f", evaluating to False; "!(expression)", evaluating to the logical NOT of the expression inside the parentheses; "&(expression1,expression2,...)", evaluating to the logical AND of 2 or more expressions; "|(expression1,expression2,...)", evaluating to the logical OR of 2 or more expressions.
Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not".
String,Stack,Recursion
Hard
null
1,631
hey everyone welcome back and let's write some more neat code today so today I'll solve the problem path with minimum effort we are on a two-dimensional grid effort we are on a two-dimensional grid effort we are on a two-dimensional grid like this we're starting at the top left position and our goal is to get to the bottom right position but there is something we're trying to minimize on our way to this path to this position and it's a bit confusing so let's take this path as an example anytime we move from one cell to another like these two adjacent cells and then these two and adjacent cells and then these two adjacent cells whenever we do that we're going to calculate the absolute difference between the values in those positions and then this problem the context of this problem those are called Heights so when you take the absolute difference of those it's two now we're gonna do that for every pair of adjacent cells so for these it was two for these It's also two 2 for these it's two and for these It's also two now we're not going to accumulate all of them we're not going to aggregate all of them among all of these values one two three four we want to take the max of all of them and in this case it's two so for this path the maximum absolute difference in Heights between two consecutive cells of the routes is two and what we're trying to do is among all of the possible ways that there are to reach this position we want to return the minimum effort required among all of the paths and if we try doing it this way it seems like from starting here which choice would you rather make would you rather go to the three or would you rather go to the two well if you're being greedy you'd probably start with the two getting there it took like an absolute difference of one then you'd move to the right or move down like these are our two choices kind of if we're running like a breadth first search which is pretty natural when you're trying to minimize something or trying to get like the shortest path if you're familiar with like just regular BFS when there's no weights on the edges that's kind of how you can find the shortest path and when there are weights on the edges you can use dijkstra's algorithm if you don't know what dijkstra's algorithm is it's going to be pretty hard to solve this problem but you can kind of derive the logic and intuition and a very quick Shameless plug on neat code IO I recently added a Basics tab right now it has like nine data structures you can Implement I'm actually working on adding dextras or rather dijkstra's algorithm as well as a bunch of others they should be coming out in like the next couple days and I have a bunch of more ideas for like the types of things we can Implement here okay back to the problem so going along that train of thought are BFS thinking about this in terms of choices that we can make Which choice do you think now would be better should we go here and actually there is the other choice of just going here well if we go here the difference is zero so that seems minimum to me the difference here is six the difference here is two so let's try going over here okay and I might as well blow this up a little bit but now we also have three choices we can go here different so two here difference of six and here difference of zero again so of course we're going to want to take the minimum the reason we're doing it this way is think about it along this path well there's nothing really going on in that path but so far along this path the maximum absolute difference has been one and that one came from this first step here but if we were to go down here the maximum absolute difference would be six if we were to go down here maximum absolute difference would be two now keep in mind that even though along this path we're making jumps of zero we still have to keep in mind that for us to get here it did take an absolute difference of one here so we have to remember that we're not accumulating all of these but we have to remember the maximum among all of them now is when things get interesting from here we can actually go to the left but that's not going to be great that's going to be a difference of six or we can go down that's going to be a difference of three now yeah we're pretty close to the Target but we don't have to make a jump of three at least not yet like maybe going down this path we will find that yeah we'll have to make like a jump of three or more but for now going down here is actually only going to cost us two so let's try that out like we're just performing a BFS here with a little bit of prioritization we're prioritizing based on the minimum uh absolute difference so now we have some more choices we can go here that's going to be a difference of five we can go down that's a difference of two so of course let's go down even now that's a smaller difference than here so now we get here again we have a choice to go right that's again a difference of two and then once again we have two decisions well we have more than two decisions but these are like our two main decisions difference of three here difference of two here of course we're gonna go with the smaller one we're gonna go from here and along that entire path we were keeping track of what the maximum was and it happened to be two so two is what we're going to return that's the result for this problem and if you didn't notice that what we did right now this solution was a BFS with a bit of prioritization you know you could call it a priority queue or you could call it a Min Heap but if this is not looking like a variation of dijkstra's algorithm just yet just wait until we get into the code it's almost exactly like dijkstra's overall time complexity is just going to be the size of the graph because we are never going to visit the same node twice so I think it's going to be end time times M where those are the dimensions of the grid and that's also going to be the space complexity because we are going to keep track of visited positions because we don't want to end up visiting the same position twice so now let's code it up okay so the first thing I like to do with 2D grid problems is just get the dimensions of the grid we know we're going to need them eventually maybe not too much in this problem but we know that we're going to need them so I just like to get them up front and we can do that pretty easily okay it's called Heights not height don't want to make that mistake on the first line of code but next we're actually just going to initialize our Min Heap now with a lot of problems when you're given like a list of edges you have to create an adjacency list from that but this is a 2d grid so we definitely don't need an adjacency list we can just use the grid as our graph but the Min Heap remember we want to prioritize so we're going to add cells to this Min Heap and we're actually going to add three values I'll start with the second two the row and the column of course we're not going to actually add the height of a position because if we store the row in the column we can get the height easily we just you know get it from the heights grid so we don't need to store that you could if you want to but that's not even what we're prioritizing actually like the height itself is not what we're prioritizing the difference the maximum absolute difference I'm just writing diff for short but that's what we're starting with now remember when we're doing this BFS we're starting at the top left position AKA 0 but what's the maximum absolute difference of that position I mean there's not like two adjacent cells so we can put a default value here of zero we don't we're not really taking the difference with anything so as a default value we start at a difference of zero for this position it doesn't cost us anything to get to this position it's the starting position so now when we start our BFS we're going to say while the Min Heap is non-empty and in while the Min Heap is non-empty and in while the Min Heap is non-empty and in this problem actually we're guaranteed to be able to reach the bottom right cell so we're not even going to put a return statement out here we're going to keep our return statement in here every iteration we're going to say Heap Q dot Heap pop from the Min Heap and get those three values get the diff get the row and get the column now what if this position is already visited how do we know that well I'm gonna check is this row column in our visit hash set which we haven't even declared yet so better declare that I already knew we should but when you're in a real interview you're kind of nervous you're just going through things you might not remember that but by the time you get to this part of the code you should and so here we're going to declare a hash set and then we're going to continue to the next iteration of the loop if we've already visited a cell now if it's not been visited let's go ahead and add it to visit because we don't want to visit it multiple times make sure that you add it as visited after we pop it from the Min Heap not when we push it because it's actually possible to push the same coordinate multiple times to the Min Heap before we start continuing the BFS what if the coordinate we popped was actually the Target right like we're trying to get to the bottom right position the first time we get there we're gonna guarantee that took the minimum effort and that's because this is like a greedy BFS and you'll see why that's guaranteed to be the case when we write the rest of the code but for now I'll just say if this pair is equal to um rows minus one and columns minus one you could also do double comparisons like is this equal to this and is this equal to this but it's just a bit easier in Python now if that's the case what are we going to do we're going to return the difference that we popped and this difference is going to be the max difference it took to Reach This coordinate so let's keep that in mind now when we start doing the BFS portion when we go through every neighbor of the current row column position how do you do that in a two-dimensional grid well do that in a two-dimensional grid well do that in a two-dimensional grid well the easiest technique is to declare a array like this is not something I came up with by the way it's something I learned but basically the four directions are 0 1 and 0 negative one zero and negative one zero when we say these are the directions these are kind of the differences like if I took this and added it to the row column I would increment the column by one if I took this and added it to this pair I would decrement the column by one if I added this I'd increment the row if I added this I'd decrement the row so all four adjacent directions so now here we are going to iterate through that we're going to say Dr DC in directions and I'm going to create some variables the new row or the neighbor row and the new column is going to be the current row plus the difference and the current column plus the difference now what if this new row or new column is out of bounds how do we know if it's out of bounds well we check new row is less than zero or new column is less than zero or new row is equal to rows that means it's too large or the new column is equal to the number of columns you could also say greater than or equal but you don't really need to because it would only be equal to this it's not going to go like out of bounds by two and that's because when we move in directions we're only moving by one anyway that takes care of the out of bounds condition but what if this neighbor has already been visited should we add that to the Min Heap for us to come continue the BFS probably not so we can also say or if this pair new row new column is in the visit hash set then just continue to the next iteration of the loop at least that's the way I like to write it because now the rest of our code doesn't have to go in like another nested block I try to minimize the amount of like nesting that we're doing okay but now we're finally ready we're gonna say Heap Q dot Heap push this new or to the Min Heap this new pair which is going to be the coordinate is going to be new row new column but what are we going to put over here what's the difference that we put do we take the height of the current row column and subtract it from and by the way this is called Heights let's not make that mistake and subtract it from the heights of new row and new column yeah that's a part of it this tells us the difference between the neighbor position and the starting position not the starting position but the current position like these are the two adjacent spots and this tells us the difference and of course we want the absolute value so let's wrap that in an absolute value but remember we want to put the maximum absolute difference here so it's possible that this new difference that we're calculating is the maximum absolute difference but it's possible it's not how would we know if this is not the maximum absolute difference well we also have theoretically this diff tells us the maximum absolute difference it took to get here at least that's what we're assuming so to make that actually true what we can say is the new diff here is gonna be the max of what we just calculated and also the original diff that we popped from the men Heap so this basically tells us if maybe an older difference was actually greater than the current difference we want whatever is the maximum of these two and that new diff is what we're going to actually add to the Min Heap right here and believe it or not that's the entire code we don't need a return statement out here because we're guaranteed that this return statement is going to execute at some oh sorry my throat but we're guaranteed that this is going to execute at some point so now let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're praying for coding interviews check out neatcode.io thanks interviews check out neatcode.io thanks interviews check out neatcode.io thanks for watching and I'll see you soon
Path With Minimum Effort
number-of-sub-arrays-with-odd-sum
You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**). You can move **up**, **down**, **left**, or **right**, and you wish to find a route that requires the minimum **effort**. A route's **effort** is the **maximum absolute difference** in heights between two consecutive cells of the route. Return _the minimum **effort** required to travel from the top-left cell to the bottom-right cell._ **Example 1:** **Input:** heights = \[\[1,2,2\],\[3,8,2\],\[5,3,5\]\] **Output:** 2 **Explanation:** The route of \[1,3,5,3,5\] has a maximum absolute difference of 2 in consecutive cells. This is better than the route of \[1,2,2,2,5\], where the maximum absolute difference is 3. **Example 2:** **Input:** heights = \[\[1,2,3\],\[3,8,4\],\[5,3,5\]\] **Output:** 1 **Explanation:** The route of \[1,2,3,4,5\] has a maximum absolute difference of 1 in consecutive cells, which is better than route \[1,3,5,3,5\]. **Example 3:** **Input:** heights = \[\[1,2,1,1,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,1,1,2,1\]\] **Output:** 0 **Explanation:** This route does not require any effort. **Constraints:** * `rows == heights.length` * `columns == heights[i].length` * `1 <= rows, columns <= 100` * `1 <= heights[i][j] <= 106`
Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa.
Array,Math,Dynamic Programming,Prefix Sum
Medium
2242
1,748
okay so welcome guys so welcome to the my decode solving section so please uh be sure to subscribe to my channel okay so this is uh one seven four eight sum of unique element so basically you have integer arrays and a unique element of a royal element appears exactly once so return the sum of all unique elements so if you see one two three two you get one and three are unique so answer is four none of it is unique you get zero so all these are unique so you get 50. okay so the idea is that uh first we need to count what we need to count uh which one is unique okay right so the idea is that we use a dictionary we create dictionary and then we iterate the list if the number is not shown then we count one right we count oh it's showing what if the number is already shown then we add one right we just want to see that we just want to say that oh this is this guy is number zero uh it's not one right and then we create an eight so it's our answer a star one zero and then we iterate the key right we enter at least sorry the dictionary and for each for that one exactly shown at one times and we add that element so for either keys if the number of shown is one then we just add that number then return a okay so it's very easy we create a dictionary and use this dictionary to count how many uh how many times each element is shown and we check we iterate the dictionary and check that if that particular element shown is only shown only one time then we just add that element okay so we submit okay it's nice okay we solve it okay i will see you guys in the next videos
Sum of Unique Elements
best-team-with-no-conflicts
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Array,Dynamic Programming,Sorting
Medium
null
110
everyone welcome back to the channel i hope you guys are doing extremely well so today we will be solving the problem check for balanced binary tree from the free card tree series so what is a balanced binary tree so in any given binary tree there will be a lot of nodes okay so for every node the height of the left subtree and the height of the right subtree their difference should be lesser than equal to one like you cannot have a difference which is greater than one so for an example if i consider this a first binary tree you can see for this node three the left height is one and the right height is 2 so there is a difference of 1 for this there is no left subtree there is no right subtree right so you can say that the height of left right is 0. for this the left sub tree is a height one the right sub tree is a height one so the difference is again zero for this guy the left subtree is zero the height of right sub three is zero for this guy also the left is zero the right is zero so i can say this is a balanced binary tree but when i come to the second example if i stand over here and i look at the right's height is 1 whereas the left height is 1 2 3 so i can say the left height is 3 so the difference between them is 3 minus 1 2 so i want lesser than equal to 1 like i cannot have more than 1 as height so i can see i can say that this binary tree is not a balanced binary tree so you have to write a code which checks if a given binary tree is balanced or not balanced so if i talk about a naive solution the next solution is going to be very simple i go to every node and i figure out the left height the right height and i compare the difference and i just say if like if the difference is greater than 1 i'm gonna return a false so i just do traverse for every node so you can check out the pseudo code over here like i take a node like it's a pseudo code so i go to the left height i find the left height very simple you keep on going left if there is no left go right go left leg wherever you can go to the leaf node just keep on going and figure out the uh left height figure out the right height again very simple go right if there is no right go left if there is like again right go to the leaf node figure out the right height also so once you figure out the right height what you can do is if their absolute difference yes if their absolute difference is greater than one you're going to return false saying that they're not balanced is it this is not a balanced binary tree or else if this condition is uh not happening then you go to the next node and then you go to the next and then so on so you go to the left and then again to the right and you again follow the same procedure of checking left right and if any anyone from left right anyone gives you a false if anyone gives you a false you return a false like if any node in bottom anywhere gives says you that this is not a balanced binary tree you directly return a false and if no one like on left on right no one gives you're going to return it through again you have to be very good at recursion in order to solve this problem so what's the time complexity of this is very simple i can say a b go of n for traversal and in order to find the left height or in order to find the right height we're going to take a beak off and every time i reach every note because i at the end will traverse this much and if it's a skew tree just in case if it's a skew tree i'm gonna end up taking a big o of n complexity which is apparently a lot right so that's gonna take a big oven so i can definitely not uh try this solution because this is a big o of n square solution now the only problem in order to uh convert this we big of n to a b of n solution is since we have to write a boolean function like i want to write a boolean function which returns uh me a true if it's a balanced vanity tree and it returns me a false if it is not a balance many tree so how do i get the left height and right height because that's tough in order to get the left height and right height i have to do something else this if i can reduce this time because this is where i'm taking an extra big o of n so if i can omit this time i think i can convert my solution to a b go of n complexity so let's discuss the big of n complexity solution so in order to understand the big o of n solution there is a prerequisite you should be knowing how to find the height of a tree in we go of end time and if you don't know that i already have made a video on that you can find the link in the description go and check that video out how to find the height of a tree in we go off and this is the code that i did use in order to find the height of the tree in b go of n very simple what i do is i just do a simple recursive traversal where i say lh rh and i know for any node like if i'm standing at this node this might have a height l h and r h now what is the height of the tree so if this right subtree is longer can i say for this node the height will be rh plus the node itself so maximum of left subtree right subtree plus one so in order to understand in brief please go and watch my find the height of the tree video so you should definitely know find the height of a tree video now since this uh does this and we go of uh n this is height of tree but i won't uh i want this function to return me either a true or either a false right i won't i want this to be returned and how can i manage a function which returns the height as well as uh true and false so what i'll do is i'll just act smart instead of returning true and false what i will say is if my function like my tree is balanced binary tree i will return the height of the tree okay i'm going to return the height of the tree so if my this tree if i take this tree this function is going to return me the height of the tree and if it is not a balanced one then i will return a minus one so as of now my this functionality returns the height of any tree so i will try to implicate a functionality such that it returns a minus 1 if it is not a balanced binary tree so what i know is if the left height that's nothing but the left height subtree so if the absolute of left height and right height is greater than 1 i know one thing this is not a balance band tree so instead of returning any further height instead of returning this what i'll do is i will return a minus one so at any moment yes at any moment i find a height difference of left subtree and right subtree to be greater than one i am going to return a minus one okay now you might think that okay this is okay but how will this work very simple if you are calling the left height and this is giving you the height if this lh at any time is minus 1 if this is minus 1 or this rh like if you're calling the functions at any time you get a minus 1 you are definitely going to return a -1 definitely going to return a -1 definitely going to return a -1 so you can insert it over here if lh equal to minus 1 like if any of the left calls did give me this minus 1 or any of the right calls gave me minus 1 then also i can return a minus 1 stating that these two functions tell me that this is not a balanced mandatory and if it's a balance binary then these two lines will never be executed and it's definitely going to return me the height of the binary tree and if any moment it is executing it's going to return a minus one as a whole result so what i did was i just added two lines to the code of the height of the tree in order to find if a tree is a balanced binary tree or not so let's do a dry run on this particular tree and see how this code actually works so initially we are over here so if node is null no it's not so we'll go to the left so we come to the two again uh we go to the left we come here again we go to the left we come here so when we reach 9 there's no left there's no right so the left height and right height is not there basically when you call them you will get the left height as 0 you will get the right height as 0 so these two lines will not function so max of left height that says zero comma zero plus one so this is going to return you a one so from this side like when three called its left it got as one now three it's time for three to call it's right so when three call it's right it'll go to the right and it'll execute node is null and it will return a zero so it got a value zero so three from the left got a one from the right got a zero again the height difference is not that much so you have a one you have a zero which is permitted the difference is one so you got a one you got a zero again maximum of one comma zero that's one plus one two so this guy returned a height of two again makes sense because the height of the tree is two if you stand at three now you add two the two guy went to the left and got a height of two now when it goes to the right it gets a height of zero so this is the moment when you're at two you went to the left and you came up like when you had two the left height came out to be two and the moment you went to the right since two did not have a right you got a height as 0 so what happened was 2 and 0 have an absolute difference of greater than 1 so what this guy returned was minus 1 so the moment 1 saw that a minus 1 is returned it directly returned a minus one so if you're getting a minus one there's no need to visit the other part of the tree and you can say that if you have got a minus one the tree is indeed unbalanced binary tree so the c plus code is on the left and the java code is on the right very simple i call the dfs like i call the function and if it doesn't returns minus one then it's a balance of any tree if it returns a minus one it's not a balanced binary tree simple as that root is null left height if by chance left right is minus one return or minus one right height if by chance the right height is minus one return minus one else absolute is greater than one written minus one or else have the function computing the height simple as that added two lines and the function works and complexity big o of n because it's a recursive traversal space complexity auxiliary space uh stack space at the worst case b of n for a skew tree so i hope you've understood the entire explanation as well as the code just in case you did please make sure you like this video because it took a lot of efforts to make this entire tree series also if you wish you can definitely drop in a comment that will keep motivating me to make such further series also if you're new to the channel please do consider subscribing because i'm going to bring in such more series in the upcoming future as well with this uh let's wrap up this video let's speed in the next lecture bye take care don't ever forget
Balanced Binary Tree
balanced-binary-tree
Given a binary tree, determine if it is **height-balanced**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,3,3,null,null,4,4\] **Output:** false **Example 3:** **Input:** root = \[\] **Output:** true **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Binary Tree
Easy
104
236
hello everyone today I'm going to solve lead code problem number 236 lowest common ancestor of a binary tree uh now let's read the question I'll give it a binary tree find the lowest common ancestor LCA of two given nodes in the tree so what is LCA between two nodes p and Q is the lowest node in the tree that has both p and Q as descendants and it is allowed for a note to be a descendant of itself so now let's look at the example problem that makes it more clear um so here uh let's uh so here we have uh P5 and q1 right so it's five so here it is five and here is one right so here in this case the lowest common ancestor of both of this node is three right because uh D5 is descendant of three and one is also descendant of three here um the two nodes p and Q uh lies on the opposite side right lie on the opposite side so yes so five on the left and uh one on the right and um so now let's look at the another problem uh we have a P5 and Q4 right so let's see where yeah we have five here and four here right so um so here um so the both of this node uh lie in the uh left subtree so we would be able to find uh any of two nodes in the right subtree right so what could be the logic here um so since uh there is uh the another uh definition of LCA that uh if the node I mean like the node itself is uh allowed to be the result I mean the node is the descendant of itself right so yes uh here uh if instead of five if it was three here three and one then the lowest common resistor would be three rights so that means so if the root if either of P or a q is the root then we can written uh the root as the resistor right so yes so that is uh what conditions that we what one of the best case that we should actually look into and so if not then what we do we uh Traverse to the left right and then see if this node is either P or Q right so if it is uh one of these two nodes then we can return it to the to its parent right and this indicates that yes we have found the node in that path and yes and then we move to right and then search in the right sub tree and see if this node is what of P or Q right and if it is true then what we do we return it back to uh this is rereaded it back to it's parrot note right so if the parent node or the parent function receives uh not null them that means that we have found the node and it should be the LCA of those two nodes right so yeah that's the case L now let's look at the second problem here so here in this case what we do we have five and four right okay so we first check left and then we find here the node right okay then that means we return it to five so the left has already deleted from like I mean we have found one of the nodes from the left subtree right okay and we check into right here we have Q4 right so this does not belongs to Q uh so this is also not q and this is also not Q right so what we get from the right subtree we're going to received null from the right sub tree right because we couldn't find the node over there right so if either left or the right subtree becomes null then what would be our next task will have to search within this left subtree right because we did find it in the right subtree so uh it is that the another node lies within this subtree right so that means we will um search in this subtree so yeah so we will have to follow this logic um so be clear all of this yeah yes so now let's code so first thing what we need to do is first we need to check whether we have three or not so if the root is null we can written all right yes what else um so yeah if root dot well equals to P dot val or we'll need to check the value uh root dot well equals to Q that then what are you gonna do we're gonna return uh root right so yeah so as I said before so if the root is one of two nodes that we can simply return root right yes now what is our uh next task um so what we did we checked into the left subtree separately and then we check into right sub two separately right so yes tree node and the left so yeah so we'll have to check into the left subtree right so uh we will call the function will make a recursive call to the function so yeah root dot left so we will go to the left and uh and then we said p and Q as well so yes we first uh check in the left right and then we will do the same thing for right low EST common our sister root dot right P comma Q right yes so yeah so and what we did so for the first case if we receive not null from both left and right yes so if left does not equals to null and right does not equals to null then what we can do we can return root right so yes so here this case we found five from left and one from right I'll be written eight to the parent here uh the root is three so that means we can read in three yes what if like either of these is null um so that if that is the case so yeah so what we can do is like if um if right is null then we can send left as right but yeah in like if the both the right and left is anyway we are going to send all right so yeah that should be all right so now let's take our code oh okay let's let me tell our code here oh great so yeah we're done
Lowest Common Ancestor of a Binary Tree
lowest-common-ancestor-of-a-binary-tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the tree.
null
Tree,Depth-First Search,Binary Tree
Medium
235,1190,1354,1780,1790,1816,2217
1,567
hey guys what's up uh my name is steve today we're going to go through lead con problem 1567 maximum length of sub array with pro with positive product so let's take a look at the problem giving an array integers nums it's asking us to find the maximum length of the sample array where the product of all of its elements is positive a sub array is an array is a consecutive sequence of zero or more values taken out of that array return the maximum length of a sub array with positive product all right let's take a look at all of these examples the first one is given this array 1 minus 2 minus 3 and 4. so the maximum length is for y is because the entire given array has a length of four and we can sum all of them up and the product is still positive right because there are two negative numbers and they balanced out which makes sense easy to understand now let's take a look at the second example 0 1 minus 2 minus 3 minus 4. so for this one the longest sub array that we can get is the one that has two magnitude numbers which is this one minus two minus three we have to exclude zero right also because zero multiplies with any other numbers is going to give us a zero which is not a positive number right zero is not positive not negative so we need to exclude zero and also we cannot include all of these three magnetic numbers because three is an odd number which is going to render as a massive product so the longest subarray that we can get is this that is why it's returning three and this one the long the longest sub array that we can get is either minus one and minus two or minus three right so it's either this one or this one because if we can if we combine all of these it's going to give us zero if we combine all of these is going to give us an active number right so this is how this is going to work and this one example just shows that the maximum length is going to be 1 because this is just this number itself one single positive number because the positive number multiplies by multiplies with maximum number is going to give us an active number which is not meeting the condition so how do we approach this problem the solution that occurred to me during the contest last night is that i can just use a for loop to go through from the very beginning of the first element to go through this array and i have a nastic for loop another so again this solution is could be very efficient as it turns out i just quickly went to discuss what i saw many other interesting problems but i just want to discuss the original solution that occurred to me during the contest so just bear with me and comment down below and let me know how you guys approach this problem so continue to my solution i just used a for loop to start from the very beginning of this for loop of this array and then i have a nest before loop to continue to check and along this way whenever i encounter an element that is at zero i'm just going to stop and break out of this nasty for loop because i cannot just include a zero as part of this valid possible longest candidate sub array right because zero is going to multiply with any number is going to give me zero which is not a positive number so as long as i meet a zero i'm just going to break out and before i meet any zeros i'm going to keep track of the total number of elements or the max the possible maximum length of the separate rate and i'll keep incrementing the global max after i go through this entire subarray then i know what's the possible maximum length and while i'm doing this there is one important step which is to do the pruning whenever the max is already greater than or equal to the remainder of this array that i need to traverse i can just break out and return the current max this is one important pruning step that i need to add in order for my solution to be accepted otherwise i get time limited exceed the exception when the given test case is too long all right that's just my idea uh hopefully i have explained that very clearly if not let me just type in the code then you'll understand what my audio is all right now let me type the code so first we need a variable we just call it max which is the final result that we're going to return and then we'll have one uh one outer for loop smaller than nums length we might not go all the way there but we'll just put it here for now so this is the outer for loop inside the follow-up so the first inside the follow-up so the first inside the follow-up so the first thing that we want to check is that we want to make sure if this number that we're currently trying to iterate on as the first as the left side starting point we want to make sure that it is not a zero if it is a zero we just skip this one it doesn't make any sense for us to include this zero as the starting element of a possible valid sub array candidate right so if that is not the case we can have a account a count of the negative numbers negative so the negative number will just say if this one is greater than zero if that is the case then negative is zero otherwise it's one so we have excluded the possibility that numbs i is zero so it's going to be either negative or positive so if it's positive then negative is going to be zero otherwise it's going to be one that's the starting point and then we want to update max here just in case max so if this one is greater than zero that means we got one number so that is going to be one otherwise we'll put a zero here and then we'll have this in the for loop into j equals i plus 1 will start from the right the adjacent right number to the i and then j smaller than nums length j plus next what do we want to count the number of negative numbers right so if let's see if nums j is smaller than zero in this case we'll increment in actives count in this case we're just to increment the count of maximum numbers else if nums j equals zero in this case as i said previously we just break out of this in the for loop that means we have reached a zero we are not going to be able to include a zero in this sub array to make it possible longest sub array in that is just a break just to break otherwise it's a positive number we don't care so we don't do anything we just don't know that so after this what we want to do is that we want to check if the negatives is a is an even number that means the all of the negative numbers can be balanced out right negative times negative is going to give us a positive number so we want to check negatives divide by two equals to zero that means the number of negative numbers is an even number so what good we want to check so in this case we want to update if it's possible to update the max math max in this case the length the total length in between i and j that's going to give us the total number of elements so that is i minus j minus i plus 1 that is the total number of elements in this sub array all right after this the for loop should be concluded and then we can just return max so for here there is one more important pruning step that we can do is we can try to we can add if nums length minus i is smaller than or equal to max in this case there is no point to check further because the remainder the remaining elements combined is already smaller than the max that we have already achieved so there's no point to go through them right so in this case we'll just return max this is a very important pruning step for this solution otherwise it's going to be time limit except and time limit exceeded for some extreme corner cases all right now let me hit run code accept it all right so now let me just hit submit and see all right accept it uh 40 it's not super fast and not super amazing but at least this is one solution that could get the code accepted just comment down below and let me know how you guys approached how you guys solved this problem of course there are more optimal solutions but i just want to throw my idea here and just uh let people know this is one valid this is one bad possible solution so if you like this video please hit the like button that's going to help me out tremendously i really appreciate it and also don't forget to hit subscribe button as i have accumulated quite a few legal tutorials on talking about data structure or algorithms are talking about aws services so hopefully i'll just see you guys in just a few short seconds thanks very much for watching
Maximum Length of Subarray With Positive Product
maximum-number-of-vowels-in-a-substring-of-given-length
Given an array of integers `nums`, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return _the maximum length of a subarray with positive product_. **Example 1:** **Input:** nums = \[1,-2,-3,4\] **Output:** 4 **Explanation:** The array nums already has a positive product of 24. **Example 2:** **Input:** nums = \[0,1,-2,-3,-4\] **Output:** 3 **Explanation:** The longest subarray with positive product is \[1,-2,-3\] which has a product of 6. Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive. **Example 3:** **Input:** nums = \[-1,-2,-3,0,1\] **Output:** 2 **Explanation:** The longest subarray with positive product is \[-1,-2\] or \[-2,-3\]. **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
Keep a window of size k and maintain the number of vowels in it. Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window.
String,Sliding Window
Medium
null
501
hello everyone welcome to my channel here I solve the L code problems today I will try to find the solution of the problem number 501 find mode in binary search tree given the root of binary search tree BST with duplicates return all the modes the mo the most frequently occurred element in it if the tree has more than one mode return them in any order assume B is defined as follows the left sub tree of a note contains only notes with keys less than or equal to the no key the right sub tree of a node contains only nodes with keys greater than or equals to the nodes key both the left and right sub trees must El be binary search tree let's try to solve it I think we can create a dictionary and count number of occurrence of each value in this dictionary else we must count the max number in the separate variable and in final we will return the values from the dictionary with max number of occurrences so let's do it first thing I'll create a dictionary and to make it easier I will use function default dict with param int it will help me increment number of occurrences without any extra conditions and also I need a variable Max count and by default it's zero next I create a function name helper with one parameter is note in this method I will count urces of each value so increment number of each value and Ela update Max count to use Max count here we must mention it as non-local must mention it as non-local must mention it as non-local variable and update Max count so it's maximum of Max count and current number and do it recursively for left and right sub trees so check if current not have left sub three call it for it in the same way for right sub three and call the function helper for our root after it we have a dictionary with filled number of occurrence occurrences of each elements each nodes and we need to return a list of values which OCC course uh as many time as the max count so we will return I for I in Dictionary d for d i equals to Max count so that's it's all solution let's check the tests something wrong let's check if Ela one more Tyle test passed we can submit it all good and uh that's all solution thank you for watching see you tomorrow
Find Mode in Binary Search Tree
find-mode-in-binary-search-tree
Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_. If the tree has more than one mode, return them in **any order**. Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys **less than or equal to** the node's key. * The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[1,null,2,2\] **Output:** \[2\] **Example 2:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-105 <= Node.val <= 105` **Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
98
160
in this video we're going to take a look at a legal problem called intersection of two linked lists so write a program to find a node uh note at which the intersection of two link uh singularly linked lists begins so for example the following two link lists begins to intersect at no c1 so in this case c1 is right here and that's where they start to begin to merge right so in this case uh what we have to do is we just have to return the node that they intersect in this case is c1 so here you can see we have an example of um linked list so basically we have list a list b and then um in this case basically we're trying to find a note that where they intersect so in this case um the intersection is going to be no um yeah so it's going to be no 8 in this case so that's what we're returning so the explanation is that the intersected nodes value is 8. note that this must be this must not be a zero if the two linked lists intersect so from the head of a so this is the head of the a and it is read as four one a four five from the head of b is five six one a four five so there are two notes before the intersect sector node a and then there are three nodes before the intersect node in b so one way we can do this is um we can use a hash map to see to store all the node onto a hash set and then if there's a duplicate then we know that's the node that they start to intersect right but the um but the question at the bottom says that we want to do this in a constant uh space complexity so constant memory so let's take a look at a couple more examples um so here you can see we have another linked list and what we can do is we want to find the intersection point in this case is going to be two and what we can do is we can have a two pointers one pointers traversing starting from the head one the other one traversing starting from the head b and if they start to um like equal to each other or point to the same node we can just return that node but this is not the case because um like less sorry a head a and head b are starting the length in this case is not the same so you can see skip a is the length is three and skip b the length is one so in this case there is no way that they are going to um basically starting at the same length right so they're not going to meet at the same position if that's the case so um let's take a look at another example where we have a link list that doesn't have intersection so if there doesn't have intersection what's gonna happen is we're gonna return null so how can we do this problem and basically um you can see that right now um if we were to start traversing from head a all the way to the end of the list is gonna be the length is gonna be five so we're gonna traverse five notes and if we were to start from head b traversing to the end of the linked list it will be three so it will take three notes to traverse to the end of the linked list so in this way um there is very impossible to get head a uh or the head a pointer point to the intersecting node at the same time with head b right so in this case there is no way that head a is going to point to head b at the intersecting node at the same time so what we can do instead is we can basically um give them get them to traverse at the same length so in this case there are five nodes that we're traversing for if we were to start at um head a and if we were to start at head b we'll have to traverse three notes so what we can do instead is we can after we get head b finish traversing the link list we can get this head a as our head b start at head a to start traversing so in this case the head b will start traversing from here and this way we can ensure that they all start at the same so at the same basically meet at the same intersect node at the same time and we also have to get head b after head b traverse the entire linked list we also have to get head b start to traverse again at starting at head b okay so basically what's going to happen is we're going to so you can see that after we traverse three nodes we'll have to traverse one two three four so plus four to get to the intersect node which is seven and for head a you can see after we choose the entire linked list we have to start at head a sorry head b again so in this case um it's going to be one two so plus two basically it takes us seven to traverse seven notes to get to the intersecting node okay because here you can see this is the size of x and let's say this is the size of z i'm just calling this so basically here you can see this is the size x the size here is let's say a and then well actually let's make this a so let's say this is the size a and this is the size x and this is the size b so if we were to traverse uh if we were to go from a plus x plus b it will equal to b plus x plus a right so in this case they're at the same position okay there we basically travel the same length by just adding the other um other length so other list length in this case we can be able to traverse the same length and if we were to traverse at the same length we can still be able to meet at the intersector node so now you know how we can solve this problem let's take a look at how we can do this in code so to do this problem in code what we have to do is we have to start at creating some uh the pointers so in this case pointer a is equal to head a and pointer b is equal to head b and then if a is equal to normal or b is equal to null then there that means that we don't have a point we don't have an intersection we need to at least have two lists to have a intersection so in this case we can do is we can just return null because there is no intersection so what's going to happen is we're going to start traversing so while a does not equal to b what we have to do is we have to move them one to the right so a is equal to a dot nest and b is equal to b nest but there could be a situation where um where a is null so if a is null uh what's going to happen is so let's say a is null what we're going to happen is we're going to get a is equal to head b okay and if b is null what we're going to do is we're going to get b is equal to head b it's our head a okay this will basically um circle back not circle back but like point to the other uh length so the list to traverse and then if there is a situation where a is equal to b then what we can do is we can just return either a or b doesn't matter in this case because they all have the same they all pull into the same node so that will be the intersecting node so now if we were to run the code and now let's try to submit and here you can see we have our success so basically it's pretty simple um our goal is that if there is if they reach to the end of the list then we're going to get them to get either node point to the other node the other starting note or the head node starting or the yeah like the other head node and then we're gonna start traversing again until they equal to each other then we're gonna do is we're gonna return either node right so in this case um basically the time complexity in this case is gonna be uh a uh yeah a plus b where a is the length uh the length of the um the list sorry the head yeah the uh a link list or the head a all the way to the end of the linked list and plus b because we're traversing from here to here and then from here to here right so in this case they're all moving at the same time so basically it's going to be a plus b for the time complexity um so in this case the space complexity in this case is constant we're not using any hash set or anything to save it onto the memory um so in this case time complexity is big o of a plus b and the space complexity in this case is constant okay
Intersection of Two Linked Lists
intersection-of-two-linked-lists
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`. For example, the following two linked lists begin to intersect at node `c1`: The test cases are generated such that there are no cycles anywhere in the entire linked structure. **Note** that the linked lists must **retain their original structure** after the function returns. **Custom Judge:** The inputs to the **judge** are given as follows (your program is **not** given these inputs): * `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node. * `listA` - The first linked list. * `listB` - The second linked list. * `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node. * `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node. The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**. **Example 1:** **Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3 **Output:** Intersected at '8' **Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. **Example 2:** **Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1 **Output:** Intersected at '2' **Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. **Example 3:** **Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2 **Output:** No intersection **Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. **Constraints:** * The number of nodes of `listA` is in the `m`. * The number of nodes of `listB` is in the `n`. * `1 <= m, n <= 3 * 104` * `1 <= Node.val <= 105` * `0 <= skipA < m` * `0 <= skipB < n` * `intersectVal` is `0` if `listA` and `listB` do not intersect. * `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect. **Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
null
Hash Table,Linked List,Two Pointers
Easy
599
42
so today we're looking at leak code 42 trapping rainwater it says given n non-negative integers representing an non-negative integers representing an non-negative integers representing an elevation map or the width of each bar is 1 compute how much water is able to trap after raining so this has the array 0 1 0 2 1 0 1 3 2 1 which corresponds to these black squares and then there are six units of rainwater being trapped which corresponds to these blue squares 1 2 3 4 5 6 so here's the input there's the output let's go ahead and dive into it so for the trapping rainwater we need to consider a couple of things so if we are considering a height map like this where it's like 1 0 1 like the simplest thing possible where will the water go here it'll be a height of one but why is that well there's like this left edge and there's this right edge and the water can only go in the middle here up to a height of one but like what if this were height of two would that matter well in this case our formula we need to change because if the water fills up this area here like it's raining and it's filling up and then it keeps raining we've got one unit of water here and it keeps raining what's gonna happen this water is gonna flow over this edge here okay and if we had another spot here of height one that water is still gonna flow over that edge if we had another thing here of height one that water's still gonna flow over that edge but if we had something here of height let's just say like if we had something here of height three that water is not going to fill over that edge now it's going to happen that water is going to start going over here and it's going to collect in this whole area right here until it gets up to this point where its height to and then what's going to happen it's going to flow over this edge and so that's why we do minimum of left edge and right edge and so for the left edge in this example we have three one zero and two we need to calculate the left edge so the way we can do that is I'll put this for the left edge you well we start here and we say okay what is the tallest thing we've seen thus far we haven't seen anything thus far right we can't look at the previous item in this left edge array because there are zero elements here we're on the 0th index so the tallest thing we've seen thus far is the spot we're at which is 3 and then we're looking here the index one in the array and we say what is the tallest thing we've seen thus far well tallest thing we've seen thus far is the three right because three is greater than one and then we're looking here and we're like what's the tallest thing we've seen thus far three and then here well the previous item in the left edge array is 3 and this is 0 of 3 is greater than 0 so still 3 here well still 3 is greater than then 2 so that's the left edge array and then for the right edge array and so what's important to note is we went this way when we built up the left edge array for the right edge array we're gonna go this way and so we're starting at the last element which is two and so there is no previous thing to the right here we're already in the last spot of this array so we just use with that value two and then here at zero the when we're looking at this spot right here the second-to-last spot the height of it the second-to-last spot the height of it the second-to-last spot the height of it is zero and the previous item in the right edge array which is the item after this index is 2 so it's 2 right because we're going this way so when we want to look at the previous thing we have to go to the right or plus one so it's what comes after in the array is actually the previous thing we looked at because we're going in reverse order and then here it's 1 so still the greatest is 2 you so the greatest is two and then here it's actually three and then for the water we look at the minimum of these things - we look at the minimum of these things - we look at the minimum of these things - the height here right so the minimum of the left and right edge would be three but the height of the water here is not three it's zero right you so we need to subtract all the height here which is three which then gives us zero so we need to modify our formula here we say - whatever is in the map at that we say - whatever is in the map at that we say - whatever is in the map at that index and then I'll go ahead and fill this in so this is the left edge for some given index and the right edge for some given index and this gives us the water at some given index so if we want to know how much water is at spot zero it's the minimum of three and three which is three - was in the map at 0th index three - was in the map at 0th index three - was in the map at 0th index which is three it gives us zero you and then here the minimum of 3 &amp; 2 is 2 and then here the minimum of 3 &amp; 2 is 2 and then here the minimum of 3 &amp; 2 is 2 minus the height of what is at that spot which is 1 will give us 1 which corresponds to the amount of water here in this spot 1 likewise 1 then here the minimum of 3 &amp; 2 is still 2 but when the minimum of 3 &amp; 2 is still 2 but when the minimum of 3 &amp; 2 is still 2 but when we subtract the height of the ground which is at 0 2 minus 0 it was us two that gives us two so we have two units of water here and then here we can just visually see that there's zero but the way we mathematically do that is we compare 3 and 2 the minimum of those two things is 2 and then subtract the height of the ground at that spot which is 2 gives us 0 okay so we need to do 2 passes through the map one from right to left and then the other from left to right so we're gonna have const l equals some array and const r equals some array and we're going to do for let i from 0 up to map dot length non-inclusive and we're gonna build up non-inclusive and we're gonna build up non-inclusive and we're gonna build up the left array here left edge array and then likewise we're in have another pass that's going from right to left so we're going to start out at map dot length minus 1 and go into and go while I is greater or equal to 0 so count all the way down to 0 and this one's going to be I minus - and we're gonna do we're gonna I minus - and we're gonna do we're gonna I minus - and we're gonna do we're gonna build up the right edge array and then we're gonna do another pass here and we're gonna do the math dot min of the left edge and the right edge - the left edge and the right edge - the left edge and the right edge - the ground elevation so what we're saying is the largest thing to the left and the largest thing to the right are the things that bound to the maximum amount of water and out of those the water can only go up to the lowest one and then it'll start overflowing over either the left edge or the right edge and then the water is obviously only going to start filling up at whatever the ground is at so I'll have some variable W to track the amount of water that gets returned at the end and then for this left edge here what we need to do is if we're at index zero there's nothing further to the left so we can only consider what's at map of I whoops with that map of I and that's if I is at zero otherwise it's the largest thing we've seen up to this point or with that map of I and so the largest thing we've seen up to this point would be whatever the previous item is in the left edge array and then for the right edge array in this case if we're all the way on the right it's the you know the first iteration of this loop I is going to be mapped out length minus one and so in that case we hit we want to just look at the height at that point and that's the tallest thing otherwise we do math dot max of map I and the previous item in the right edge array which is going to be at our I plus one because we're going in the other direction from before so we'll submit that and that is how you do the trapping rainwater on leak code using javascript thank you
Trapping Rain Water
trapping-rain-water
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining. **Example 1:** **Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\] **Output:** 6 **Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped. **Example 2:** **Input:** height = \[4,2,0,3,2,5\] **Output:** 9 **Constraints:** * `n == height.length` * `1 <= n <= 2 * 104` * `0 <= height[i] <= 105`
null
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
11,238,407,756
115
Hello Everyone Let's Start Discussing About Today Lead Code by Kakali Contest 11 So, first of all, I liked this contest a little less because the language of the problems was a little, I felt that after reading it once, I could not understand it. Like In the first question too and in the fourth problem, the constraints were very strange. I will tell further when I am discussing about the fourth one, why I found it strange. Let's start with the problem. So this problem is something like this, I would tell. In easy language, what is the problem, so the problem is something like this, we have an array of words, given is an array of words, now what can be in that word, there can be two types of things, so your There will be integers like no tooth, is this method ok or what will you have given, you will have a string given Q, there will be some integers like this, some may be 'P', then 'Y' some may be 'P', then 'Y' some may be 'P', then 'Y' may come again 'P' is something ok in this way may come again 'P' is something ok in this way may come again 'P' is something ok in this way What do you have to tell me, you just have to tell me that whenever you have a test, all the injuries you have got so far, like how many injuries have you got on this four and this is the problem, you have to see ] ] ] That is how many Continuous Prives have come to us till now, we have to consider that too, so understand how many Continuous Prives have come here till now, only one and only one Continuous Prive has come here, so do you know that this is the number of all the continuous Prives till now. Integer numbers have come, their array has to be directly reversed, okay, and if this is how many continuous prefs have come, one and if you have come one, then you have to tell the element with one position, then what will be four in this case, okay? Now as we move ahead, what will come after 1 2 3 4 Then this proof, the answer to this proof has come, how many four, we have to tell the answer to each proof, then you have 12, then what has come to you, 13 now you Which one is this continuous priv? This continuous means if we look at it then how many continuous privs have come till now, there is still only one because this and this one have been broken. It is okay in the round of 12 and 13, so now reverse this also. And check which is the first element, is it the first pref? Okay, if we look at it in continuous manner, then what will be its answer? 13 Now what will happen if we look at this pref, then which one is it in continuous manner? The one with number two is the first one, so you have to reverse it, whatever number of numbers you have in the array, and by doing reverse, what do you have to do, meaning by reverse, you have to tell the second element, what will be the element, okay? 4 3 2 1 So what will be the answer of this one 12 Let me tell you one more example like the one given in this yes there was one more thing if you understand that you have the first given in this way one proof then the answer of this proof will be one this one How much will the answer of the proof be - 1 because till now how many of How much will the answer of the proof be - 1 because till now how many of How much will the answer of the proof be - 1 because till now how many of our integers have not come, so many, this is the second numbered proof, but two of the integers have not come, so if our answer is not present then that What to do in case of return my ok so let's take another example quickly like one two proof what will be the answer of this one proof one ok what will be the answer of this one proof this one will be two because Two will come and when we reverse it and the first one is proof, then this one is the proof, what will be the answer of this one will be our one, okay, why did we reverse two and which is the second one, so the second one, then what is our final answer? Will be to 1, so I wanted to tell it like this, so the question is simple, so what we have to do in this is that whenever we have any M and I take this example, pref, then we just have to check that whenever we have Some integer will be coming, what will I do with it, I will create a new array, I will create a new vector, I will store it in that vector, I am fine with it, like if my one comes, then I will create a new vector and in it only I keep storing all the private elements that I have, then as soon as my priv comes or I have to pick up the elements from behind, then I will keep maintaining that this one is the priv and which number is the continuous priv. For that, you do nothing, just maintain a counter, like a counter, whenever you have an integer, how much should you do with that counter, reset that counter and make it at one, sorry, zero, and whenever your priority comes, what should you do with the counter? If you do plus then what will happen if you see the value of the counter here, it will be reset here, it will become zero here too, if you see here, then in the pref of the counter, if you are doing plus then one here. But if you look, you will see 2 here, 3. Now if there was an integer here, then we would have made it zero here also, we would have made P here also zero and then again here, we will keep changing the value of the counter to one in this manner, it is okay. So this is done, now what can we do after this, now we have to see that whenever I come to our proof, what is my counter, understand that I am creating a temporary vector, okay, I keep storing the temp in it. Whatever integer I am talking about, if the counter is greater than the temp dot size then it is a simple matter that the answer can never exist in that case, the answer will always be -1 in that case answer will always be -1 in that case answer will always be -1 in that case because the reverse. Even after doing this, you will not be able to reach that position. Otherwise, what do you have to do? Otherwise, you have to pick up the element from the back. Right means reverse and pick up the element. At some position, that is what it means. This is what is meant. Exactly, you look from the back. So at which index do we have to look at the temp. item dot size minus counter. Whatever element is there at this position, just pick it and print it, like when you look here, what is the value of proof? Here one came. So in this you will see that if we have stored one in the tam, then what is the tam dot size? Here pay two is 2 minus what is the counter for us, so we have got it printed with the index. If the question comes again then what will happen to our counter? Yes, it will be our zero, and Q. Sorry, and the size of the stamp is, so minus zero, how much will it become? Okay, so we have printed this one, so let's just print it, that is, let's store it, so now we have to return it. If I show you its code, then like I told you that Tapri is vector, in answer we will be storing all of them and returning the answer of Priv. Okay, so this is what I just checked. If Priv is there, then basically what it means is that it will start from P. My string so in that case what I am doing is counter plus okay in else I am resetting my counter to zero and what do I store in the temporary vector I am storing my integer okay Meaning, if the string is given then what does the ST function do? String to integer. Okay, so if the counter is non-zero, what does it Okay, so if the counter is non-zero, what does it Okay, so if the counter is non-zero, what does it mean that your integer is the priv which is your priv must have come yes the string which is if your because If your integer has come then in that case the count will be zero. So if your counter is non-zero So if your counter is non-zero So if your counter is non-zero then you have to check the counter. If the counter is greater than the dot size then in that case your answer will not exist. Ok answer dot push. What do you have to do in Back-1 Else? Ok answer dot push. What do you have to do in Back-1 Else? Ok answer dot push. What do you have to do in Back-1 Else? Answer dot push back from behind the tum, just store it. Time dot size minus counter datchi. Okay, now the problem with B was a very easy problem, it was according to its position. I was not finding it suitable, let me tell you what is the problem, so simple, what is given to us, just one second, let me explain what is the problem, so is it simple, he has given us two, understand the meaning, he has given us. One of words and one of group, so what are the words? Like us, understand that words can be anything is strings, okay like let's take the example of our E A B, okay understand that one is string and the other is string. This is the third string, so the words should be kept in groups like this. Now this is a group, everyone 's group will be either zero or one, it will 's group will be either zero or one, it will 's group will be either zero or one, it will be zero or one. Okay, so in the example like ours, we have given it. 001 Now what you have to do is to select the longest sub sequence from which every alternate, if you look at every alternate group, they are never equal, meaning that if we have zero, we have to select such a sub sequence that if we have zero, okay. If the value of the first one is then the value of the next one should be one, it cannot be zero, it is okay, it means that the group of every alternate should be changed, such a sub-sequence has to be selected, if the is okay, it means that the group of every alternate should be changed, such a sub-sequence has to be selected, if the sub-sequence is not known, then let us do something one by one, sub-sequence is not known, then let us do something one by one, sub-sequence is not known, then let us do something one by one, meaning in increasing order only. Elements have to be taken only from off indexes, we call it subsequence, if our group comes then we can take one, then after that we can take zero, then we can take one. Okay, if our one comes then zero after one. Then one, then zero, we can create groups like this, so you have to tell which sequence you can select is the longest, just tell that and what you have to do is to pick the strings and just return the meaning of picking the strings like if Here we are taking zero, so then I cannot take zero, then I can take one. Okay, so what is the longest sequence of these two and we just have to string them and store them, e of the first one is b of the second one, so we just have to What to return? E and b are stored in a vector. That's fine. Then you can't take one, so just store their strings too. Let's go to a b c. So what to return in the end. A b c is to return its vector. Okay, so see this question yourself, that means how easy it is that if we have any number of groups, the vector of the group can be anything, okay if I first pick one from here, okay then I can pick zero, then I can pick one. Then I can pick up zero, okay, by doing this, I can pick up all the groups every time, all the numbers of mine, they should be alternate, so in this case, I can pick up all the groups, store their string and return it. I will give but if it had happened like this then what could you have done. If you want to make the longest then you start from the starting one, now you look at the alternate, it has come to zero, now you have gone to zero, you cannot take it, then you have gone to zero. You ca n't take zero, then you go to one, take one, then what is yours? One is equal to the last one, so you can't take it, then you come to zero, then you take zero, then you can't take zero, then 10 of them. Just store the string and return it, there is nothing in it, we just have to see that the last one should be unequal, whatever we picked in the last and we will keep picking that and now we will just store the answer of all, okay so I will do this. I will not explain much because it is a very easy question, so understand what we mean in the last, what group I have picked in the last, I maintain this element in the last, it is okay and in the answer, I maintain that which I am doing final return so right now I look at my current group if it is not equal to the last then what will I do to the last equal to my current group and answer dot push backward ahi finish return answer like my last is also upgraded It will keep happening and my answer will also keep getting pushed. Okay, now the third question is basically the same question as the second question, it is just what to do in it when you consider the words. Now we were looking only on the basis of groups. Now we will also see on the basis of words that your group must be different, that is, it is okay from the last one, you give me one second, I am seeing that the group here can only be zero and one, yes here. P can be zero and here and cannot be zero and here. The groups here can be anything. Integer is fine like one is given here so your groups should be different and also what should be yours. As soon as you are looking at the words, it means as if you picked the last word and whoever was your group, when you are coming to the next one, you will be considering all the sequences, then the next one is not the same group as the previous one. There must be a change from the group of words, along with that your current string of words is not the same as your previous string of words, what should be the string of the word that you have picked, meaning the Hamming distance between them should be one. I will help in the example. Let me tell you this, it will be much easier to understand, like you have given words like B, A, B, C, B, it is okay and the group of yours should be like, you pick it first, like you have picked up B, you understand, it is fine. Now I saw that I can pick up D. Mandy with BB only when my group is different, we were seeing that earlier too, one is different from two, absolutely picked up. I can and at the same time they are together, what should be the Hamming distance between them should be one? Hamming distance basically means that at whatever places the two strings are unequal, that is, at whatever intersections the two strings are equal. The length should be equal, like this is three, this is also three and also it should be that the number of unequal inces, number of unequal, the number of unequal inces, which should be the characters on the unequal inces, sorry, I am saying it a little wrongly, number of. You have to tell me the position where the characters of these two are not matching, then there should always be one, then look at D, B and R, here only this one is in that position and the characters are not equal, the rest. If both sides are equal then what is the Hamming distance between these two is one What is the Hamming distance between these two is one Then you can select any subsequence if you have selected only B is chosen, then D is chosen, B is okay, this one is done, now you pick up the check, C is okay, this is one, this is two, if you want to pick up C, B, then you can never do both of these because these What is the group of both, if the group is the same, then the Hamming distance between these two has become the same, meaning it has become one. Sorry, you can pick both of these, you cannot pick this one because the Hamming distance is one, but will the group be the same? Even if you pick B A C A, what will be your length? What can be your maximum answer? It can be only two. Just tell us the answer. Add B A and either d or B A and C. You can give any answer. You can give one of length two, okay, let's pick another example, let's take example A B CD, okay 1 2 3 4 What is the Hamming distance between these two? Everything, what is the distance between everyone, there is only one because all the groups are unequal, all the groups are also unequal, so what can we do in this we can select all the sub-sequences, okay, so it has become can select all the sub-sequences, okay, so it has become can select all the sub-sequences, okay, so it has become easy, now understand that now its Let's move directly to the solution to see what the solution will be. Understand this way. Ray pass word w12 w34 When you are on any word na you are on any word then first yes one before that let me tell you the constraints which is n which is to the power of 10. It can go up to 3, meaning the length of words and groups and the length of string can only go up to 10. Okay, so now understand one thing that if you are on any word then what would you be thinking that friend or So I am coming after this word, meaning understand that whatever your sub sequence is, it is in this manner, first w1 came, w3 came, then w4 came. Okay, so when you check w4. If you are doing this then you will check whether I can put it after w3, is the group of these two words different and also the Hamming distance between these two, if it is one. w4 can be placed before w3, similarly, we will check w4, w2, w4 will check w1, then what will happen is that whoever is coming from my longest subsequence, I will just put w4 there, meaning. Whichever w1 w2 w3 has the maximum subsequence till now, I will add w4 behind it, okay now a, for example, I tell it once, like b, this is the same example, d c, okay, so this is w4, like this. Then I will come to w5, here I have a subsequence of w4, I will create such a subsequence which has w4 at the end, similarly I will maintain for every index w3 which is at the end, in which w2 is at the end. Now as soon as I come to w5, I will check, can I go after the sub sequence which ends at w4, w3 like this, can I go after w2, can I go after w1? Whoever I can chase behind, if you think its length would be three, it would only be two, if it were two, if it had one, then what can I say in this that I would like to chase w5, why always behind the one with three lengths, because if If you put it behind the two, your length will be shorter. In which w5 is small, that is, in which w5 is at the end, then which one will you put, you will always put it behind the three, and what will be the length of w5, it will be four. Okay, so as I consider BB. Initially, what will be its length? Because there is no one behind it, I checked whether its group is different from this one at all, can it be attached to it, can it be attached at all, so this sub-sequence which was being made till now, is B.A. Now sub-sequence which was being made till now, is B.A. Now sub-sequence which was being made till now, is B.A. Now how much has it become, the groups of b and d are also different and what we mean is that the Hamming distance between these two is also one, then I checked on this and checked on this that the one on this ends and the one on this. The subsequence that ends at the end is B. I am talking about the longest subsequence. What is the meaning of this one that ends at the end? BD means at the end, so do these two have different groups? If not, then in that case. I can't connect with this, is the group of these two different, is it different? Yes, is the Hamming distance between these two equal? ​​Yes, Hamming distance between these two equal? ​​Yes, Hamming distance between these two equal? ​​Yes, of course, then what will come in this case, B and C? So in this way, I can find the longest sequence of all. I can and I have to return the same, then how much will it be in this case, return any of these two, it is ok and what will be our length, I hope you have understood the question and its meaning, its approach, let's move on to the solution. Sorry code page, so look at its code. First of all, what I did in this is that as soon as I told you that I will maintain the longest sequence of everyone, then I created a new one in it, created an array of vectors. So in this, I will be maintaining my vector on every index, what will be my he will be telling me, whatever my longest sub sequence will be till now, then what can you do if either you or Which you now subsequence one second let me tell you with the help of this that if you think that there is no one behind you i.e. understand that there is no one behind you i.e. understand that there is no one behind you i.e. understand that there is no one behind B A B D A B then what is the option for you that you yourself Make a sub-sequence of length such as yourself Make a sub-sequence of length such as yourself Make a sub-sequence of length such as BB. If you think like this, I can consider this of DB. If there is no one of DB, then here it is happening BB. If it was there then consider that BB would be BD of that one. This doesn't have anything to do with that case, so in that case, we also make it of length, that is, we make it of one length, which is all the sequence, so this is just this part of the code that I have written to tell the same thing. What I did initially is that I thought there was no one behind me, whose aiming distance was one, I made a vector sub sequence equal to my current word, then I went back from here, okay. I put the loop in off n square and I checked that if the size of dl is equal to the size of da, then what does it mean that this as well as the group of these two are unequal. If yes, then I check at how many positions these two are not equal, then I check at these positions, store the value in counter one. If the value of counter one is one, that means the Hamming distance between these two is one, then I check. That is, what is the size of my AJ? What does it mean? What is the size of my previous sub-sequence on which the index of J is going to end, that means I What is the size of my previous sub-sequence on which the index of J is going to end, that means I What is the size of my previous sub-sequence on which the index of J is going to end, that means I store the maximum in answer one, that means whatever number of my Previous sub-sequences must have come, whatever number of my Previous sub-sequences must have come, whatever number of my Previous sub-sequences must have come, what will be their answer maximum, because if I add right only with the maximum one, then I have stored that in answer one, okay and I have also stored the index of that particular position and the position of J, like How much is the index here? If in this condition, then at the end, I just check the value of the index, which I initially initialized to -1, that is, if I find any one to -1, that is, if I find any one to -1, that is, if I find any one which has Hamming distance of one, with which I can add. Whose group is different, then what will I do in that case, I keep my current sub sequence equal to my previous one with whom it has just appeared on the index and the longest sub sequence that has come along with it. What do you do in it, insert your current word, then now our answer one, how much will it become, will increase by one, obviously meaning if the length of the previous sub sequence was x, then how much will it become now x + 1 answer plus was x, then how much will it become now x + 1 answer plus was x, then how much will it become now x + 1 answer plus answer What were we storing in one, which is the subsequence with maximum length, the previous one was answer one, now what will be the length of the subsequence of our current one, answer plus and what I do is that I took one more answer out and a final index. I have maintained it, okay, so I checked if my answer is right, which is my answer one, which is my current answer which is coming now, which has been increased from my answer, what is the answer which is mine in the very final end, which we are coming out with the answer. And this is the final index of that particular subsequence beyond which the end will be happening. Basically the right index on which the end will be happening and the answer. So what will we do that if on which if you understand that answer one is my subsequence which is Right now my current index is going to end if it is greater than answer then I make answer equal to answer one and make the final index I final index will basically be showing that the subsequence that is going to end at this index Mine is the eldest so I am just maintaining its length in the answer and its index in the final index and what will we do in the return in the end. Final index is ok, so now coming to this question is not good to me at all. I thought I would also tell the reason for it, why was it so in this question, I will tell you in easy language, first of all, what is the meaning of the question and what do we have to do, then the question is something like this that you have No, you are given an air. Okay, an air is given. There can be many numbers in it. 2 3 4 5 Now you are there, think from this, you pick any elements from it, any number as per your wish. Pick up the element, whatever you pick up, you picked up two, picked up one three, okay and you picked up one four, so this is whatever element you picked up, find its sum doti cha pa 6 sa 89 10 11 12 you have so many you just have to tell how many you have like this You can pick the set, how many such wedges are there in which you can pick the element, your elements that your sum is coming between L to R. Okay, we are given an L R and I am coming between it from L to R. Our even in the middle is okay, so how many such ways can we take it and one thing is going to be noted in this like understand here is our here p is our 12, think about how many such ways it means to get my k of 12 only. There are wedges in which my sum is becoming 12, so in this it is said that if you have picked three like this, think 1 2 3 4, you have picked it okay, now it can be that you have picked this three, now one way is this. Also it is possible that 1 2 is picked and then three is picked and not this one, in that case also 1 2 3 4 will be formed, but we have to deal with both these cases separately, that means they should be dealt with only one. We have to follow the same case value, what are these two, it is the same case, it means there are not two methods, only how much is one, both of them have to be considered the same because when you sort them, 2, 3, 4, then what is this, they are equal among themselves. If we are coming, then in this way you have to tell the different ways so that your sum falls between A and R. Okay, so we had to tell this, now the constraint of this question is 2 * 10 power 4, okay. So you 2 * 10 power 4, okay. So you 2 * 10 power 4, okay. So you can think that you can apply the approach up to A and A. It is okay, meaning off is equal to A and A, meaning max to max of A and can be done. The answer was A and A, so we know what to do. You can see that if you have the initial pass which is er, it is given in this manner, tooth 4, elements are there in this manner, there is fine hair in it, there is jism and meaning, there are ingers in it is given in this manner, first one is coming then two is coming. Then three is coming, then four is coming, so what can you do, if you do not pick up anything, understand, if you do not pick up any element, then what will be your sum, zero, so how many ways to make zero, only one, you can do anything. If you come to a forest then how many ways are there to make a forest? You have only one simple way to make a forest, then I will write it here. Neither did I know the ways to make a forest nor have I come to know about it. If I consider 1, then it may be that the sum which I have till now is zero, or if it gets added to it, then how much will it become two, or if the amount of two gets added to one, then how much will be my sum in this case? It will become three. If you understand this much then how many ways are there to make two? Now I have one or it can come alone. What does this mean? You can see from here, you can also see here that pairs with zero can come and make zero. There are so many ways to make a forest. One and two are here. Whom should he come with and join with the forest? If the one who is equal comes and joins it, then how many ways are there to make a forest? Neither 1, 2, 3. This is also a simple way, there will be only one and you will be from here because if the one which is the same, then whatever is being formed by me, then it is adding further after that, if there is a method then it means that now you can see from here also. 1 P 2 How much is th till now if you don't consider th and four and you are considering two there is only one way to make th then 1 p 2 now you are ok on three when you consider three then th You look at it in this way that what is there now, what could it be that my previous level which was coming or not, should come and join with it, simple, okay, then what will become of me in that case, will it become six or not, it will become absolutely. In how many ways can six and six be formed? Just give one second and in how many ways can six be formed. Right now I am only considering till thi, so six can be formed in only one way and we can see that here also. Because till now our three could have been formed with only one method, so here six has come and you can also see like this, 1 + 2 + 3, 6 and you can also see like this, 1 + 2 + 3, 6 and you can also see like this, 1 + 2 + 3, 6 and you are not able to see any other way of making it till three, then you can see three. It is possible that if you add it to two, then it will be 3 + 2. you add it to two, then it will be 3 + 2. you add it to two, then it will be 3 + 2. In that case, it will be five. How many ways will there be to make five? Only and only, do we have one or not because there is one way to make two and three. How much will it become by adding it with two? Okay and you can see here also 3 P 2 5 And someone else is visible but there is no way to get it. Now you see four, three, whatever is there, four is yours. Meaning, how will it be formed, if your three is joined with one, then how much will yours become, four? So, how many ways are there to make one, then one, how many ways will there be to make one variable, because one will be joined only in front of even and you are one. Once I show from here also 3 P one, I don't see any other way, no till three, if I am looking then do n't consider four, now consider Y one like this, then you connect three with zero which is your So if you add three with zero then how much will be equal Three then three I have to see how many ways are there to make zero One then I have a new way of making three That means if I add three with zero If I tell you, how many ways have there been to make three, here if I am considering three and three was already being made as one, then how was the 2 + 1 one being made, now the three which is there is 2 + 1 one being made, now the three which is there is 2 + 1 one being made, now the three which is there is with zero, meaning if we do something. If we are not taking even, then with that root one our three is being formed. Okay, so the base of zero was one and three and it got added to it, then how much is our three, so now I have come up with a new way to make three and I will just add that to this, how much will 3 be 1, meaning 1 is how much will one be two, so what do we know from that 0 1 2 3 4 5 6 Zero to one to make one, two to make one three. To make 2, we have two, four, one, five, one, six, one. Okay, now we consider four, the one who is four, can add it to six, that means, the sum that came to me as six, has now come to 10. How many of its numbers will be off? We have one, four, five. We can add it with the even number. How many of its numbers will be there? One, four, which can be added with the four, in that case, the sum will be eight. Its number is off. Ways will be one, four can be added to three, then seven will come, then how many will be the number of ways of seven, we will have two, because we had two. Ways to make three, if four will be added behind them, then two will be as many as will be to make three. There are only four of them, if four come and join then the waste will remain the same, then your four can come with two, then how many will be his number of wedges, your one will be added and six will be there if you already had one. Meaning, if there is one and add to it, then two is fine and if four can be added to your one, then in that case, what will become of you, five means one, how many ways were there to make one, they were the same. So simply that 4 + 1 will become five, so So simply that 4 + 1 will become five, so So simply that 4 + 1 will become five, so add it here, 1 p one, how many will it become two because there will be only one here also to make five and there was already one, so by adding it becomes two and your zero. What will happen in that case, your even means the earlier even is becoming zero and you come and add four to it, then our way of making a new four has become right, it will become one because it is becoming zero. How many ways are there of one, if you add one more to it, then one means 1 = you add one more to it, then one means 1 = you add one more to it, then one means 1 = 2, let's write it down as 1 2 1 Ok 0 1 2 3 4 5 6 7 8 9 10 Now you write this See also, what we have written is correct or not, okay, how many ways are there to make zero, there is only one, do not pick anything, there are how many ways to make one rise, there is only one, we can see, pick one, make two. How many ways to make it, there is only one, only two, pick two, how many ways to make three, only one, pick three, okay, one way, that's it, okay, one way, it's done, only three, pick one, two, and one more than that Three will also come, how many ways do we have to make four? Two, pick four alone or what can you do, three and one, mix these two together, so here we come, ways to make four, two, five. What is the way to make three cards, pick two or four and one, then there are two ways to make it, so you can see that we have found out the ways of all of them from this one, how many numbers of wedges can come in the time of making. Okay, so that's all there was in the question and there was nothing else, find out the wedges of all of you, how many wedges you can use to make all these numbers, what can you make even, and what were the wedges to make the sum, and that's it. Come to L2 and compute it, its sum cannot go more than 2 * 10 to the power of 4. This is given to us cannot go more than 2 * 10 to the power of 4. This is given to us cannot go more than 2 * 10 to the power of 4. This is given to us in the constraints and that's it and all the elements are also obviously not going to go more than 2 * 10 4, so obviously not going to go more than 2 * 10 4, so obviously not going to go more than 2 * 10 4, so in this That's it, now I show the code, what is its code is like this, here I have counted the frequency of all in H, how many frequencies are there and this is the number of ways, each one. I am just calculating the number of ways. Here in the deep, h is the frequency and in the deep, there is the number of ways. It is okay for each number. Now it is a simple thing. I have gone to each element. Okay, what do I do here? I go to each element and count its frequency in h. I basically counted the frequency of everything in h. How many ways do you have of making zero? Maybe you are getting five zeros, so what can you do? Either you pick one zero or two zeros or three or four or five or if you don't pick any then still zero will come so h is off 0 p so there are so many ways to make zero this is just a special case otherwise your I am calculating in the answer in the pass total number of wedges. Okay, so we went exactly from the end, meaning we started exactly from 2 * 10 pa 4 we started exactly from 2 * 10 pa 4 we started exactly from 2 * 10 pa 4 and I checked that if my h of aa means my frequency must be equal to if I My element will be present in this array, so what are the ways I can have that I see what my new elements can become, so it's a simple thing, what I did here is that the phone E 0 Here I mean J E 2 n 10 power 4 and J take E 0 J minus I had got even numbers in all my previous DPs, meaning the number of wedges of each value had come in all my DPs. I checked, first of all, what is my if deep of What will you do by adding to it, I mean, if you want to add five and J is four and your value on four is not existing, meaning there is no way to make four, then how do you add five to it? You will only do that, this is the condition and then my frequency can be whatever it is, till HI, so I went to each value, I checked the frequency, how much frequency it has, meaning either I will pick one element or I will pick two or I will pick up three or I will pick up four or five so you pick up as many as you want, it's okay out of element HI means think aa the frequency is five so you can pick up one or two or three or four or five and What kind of ads are you adding? What is yours showing? I am showing the values ​​that have come in my DP till now, so I am showing the values ​​that have come in my DP till now, so I am showing the values ​​that have come in my DP till now, so whatever values ​​have come in my DP, it means basically whatever values ​​have come in my DP, it means basically whatever values ​​have come in my DP, it means basically consider it as deep off. What is that on each value, we are telling how many number of wedges have been formed. Okay, so if you add anything by five, then you are adding by the time, meaning if you are picking one, then you If you are doing simple addition of five, you are adding two times, then you are adding 10, then j p k, whatever you think, the value which was on four, now it will be 4 + 5, 9, 4 + 10 will be 14, now it will be 4 + 5, 9, 4 + 10 will be 14, now it will be 4 + 5, 9, 4 + 10 will be 14, so just tell me this. What will be the value of JPK? Do you add the depth of J? Why did we add the depth of J? If you have to make j p k then you will be adding k to j and what is k aa, the element you are considering is the number of times k. Okay, you will just keep adding this and you will get at aa. We have to find the sum at the end and just keep taking its mode because it says that the mode has to be given as 10 9 and a return answer will be given by finding out L2 A and it will be passed. Now what I was saying, this question should be asked. I was confused because all my time was wasted because of this little thing. If you do just one thing, take it as vector, okay instead of int, that is, instead of array and submit, then it will give you t, should give t. It was absolutely simple and what do you do to make it simple, just pass it in an array manner and it will be passed, that's why I did not like the question because earlier I was using NDP InTouch. And my solution was failing
Distinct Subsequences
distinct-subsequences
Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`. The test cases are generated so that the answer fits on a 32-bit signed integer. **Example 1:** **Input:** s = "rabbbit ", t = "rabbit " **Output:** 3 **Explanation:** As shown below, there are 3 ways you can generate "rabbit " from s. `**rabb**b**it**` `**ra**b**bbit**` `**rab**b**bit**` **Example 2:** **Input:** s = "babgbag ", t = "bag " **Output:** 5 **Explanation:** As shown below, there are 5 ways you can generate "bag " from s. `**ba**b**g**bag` `**ba**bgba**g**` `**b**abgb**ag**` `ba**b**gb**ag**` `babg**bag**` **Constraints:** * `1 <= s.length, t.length <= 1000` * `s` and `t` consist of English letters.
null
String,Dynamic Programming
Hard
2115