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
867
hello friends so today we are discuss this question from leet code problem number 867 transpose matrix in this question you are given a matrix as an input you have to find the transpose of matrix is actually the matrix which is clipped over its main diagonals or you can say is switching the rows and columns of the indices of the matrix this is clearly depicted in this picture as you can see the first row becomes the first column the second row becomes the second column the third will become the third column but because in this the dimensions are our 3 is 2 3 cos 3 this is not only for 3 cos T it can happen in any matrix so the code is very simple we first inputted the dimensions of this original add matrix and then we make a new vector matrix we have to just flip the dimensions because now the rules becomes the column and the column become the rows as you can see then we traverse over the whole the matrix of a from n to M and in the pneumatics answer matrix what we do is we just flip their little in which we want to store as in this example as you can see the indices of this is 0 comma 0 and this is also 0 comma 0 so it will not get affected but there are indices of this in the original matrix is 0 comma 1 now it becomes 1 comma 0 so as you can see we had inputted from 1 comma 0 comma 1 and it becomes 1 comma 0 same if we can take any mad indices in the original matrix like this the indices of this is 1 comma 2 and this is 2 comma what so yeah it's just flipped then you have to just return or the new matrix then you answer matrix and yes that's it I hope you descend a logic thank you for watching and I'll see you in the next video
Transpose Matrix
new-21-game
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **Example 2:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\]\] **Output:** \[\[1,4\],\[2,5\],\[3,6\]\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 1000` * `1 <= m * n <= 105` * `-109 <= matrix[i][j] <= 109`
null
Math,Dynamic Programming,Sliding Window,Probability and Statistics
Medium
null
15
hey everyone welcome to Tech wired in this video we are going to solve the problem number 15 threesome athlete code so in this problem we are going to uh find three triplets that sum to zero and those triplets should not be duplicate values okay so we will see the solution using the first example so this is the first example given in the lead code website so what is the Brute Force way of thinking about this particular problem we can have three for loops and we can just iterate through and you can just find out the particular sum particular three values that sum to zero if I do that first I will keep this as I and another one as J and I will take another variable another loop as K and I will just iterate through each of the thing and I'm I will be getting that particular values right but here is a problem of duplicate elements we will again we'll get this same uh triplets in the next iterations so this is not the optimum optimal solution because it's going to take order of n Square I order of n Cube and it's going to have duplicate triplets so we will see the optimal solution in a second so now I've sorted the array it's so I've said in the previous video that you before solving three sum we need to solve the two sum which is uh the input array is sorted if you guys have done that particular problem then this problem would be much more easier to solve so here I've sorted the array I'm going to solve this problem in order of n Square okay so how you are going to do it first I will keep one for loop as I and then I'm going to have another loop of left and the right pointer okay we know our input array is sorted and what I'm going to do is if my sum is greater than zero then I'm going to push my r in this direction so I'm going to reduce my r and if sum is less than zero I'm going to push my left pointer to the right so I'm going to increase my left point okay so the her sum is nothing but num of I plus num of L plus num of r okay this is what sum and if I see a duplicate for example here so if I have the same element I will check whether I have seen the element previously using another loop okay then I'm going to eliminate the duplicate elements here and this particular solution will take n log n since we sorted an order of n Square since we use two loops now we will see the code so first I will sort the array now we are having a result then I'm going to have a look I'm going to get the index and value using enumerate function from an array and I'm going to here I'm going to check whether I've seen the element previously or not in the first element ith element okay nums I minus 1 the previous image then I'm going to continue yes I'm going to take G and K okay I plus 1 length of nouns minus one the last element okay now while G and K now I'm going to have the sum I'm taking the three elements okay now I'm going to check if s greater than 0 is greater than zero I'm going to decrease my kit okay yeah if it is Less Than Zero I am going to increase my chain yes if I found the value then I'm going to append if it is 0 if the sum sums to zero then I'm going to append those where triplets here we can check whether in order to avoid the duplicate values I'm going to check here as well if J less than k and numbs of J is equal to the previous value if it is equal this particular Loop will execute now I'm going to return my result array after appending it to the result now you here again we will check the duplicates by increasing the left pointer I'm again going to check to make it much more efficient previous duplicate values now I'm going to return the research it worked and looks much more efficient now yeah so if you like my Channel please like And subscribe and share my YouTube links um also see my previous videos if you are not able to understand this uh particular Solution please put a comment in the comment section I will be happy to answer your questions also check out my previous videos which will be much more helpful before solving this particular problem thank you for watching happy learning have a good night take care cheers
3Sum
3sum
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. Notice that the solution set must not contain duplicate triplets. **Example 1:** **Input:** nums = \[-1,0,1,2,-1,-4\] **Output:** \[\[-1,-1,2\],\[-1,0,1\]\] **Explanation:** nums\[0\] + nums\[1\] + nums\[2\] = (-1) + 0 + 1 = 0. nums\[1\] + nums\[2\] + nums\[4\] = 0 + 1 + (-1) = 0. nums\[0\] + nums\[3\] + nums\[4\] = (-1) + 2 + (-1) = 0. The distinct triplets are \[-1,0,1\] and \[-1,-1,2\]. Notice that the order of the output and the order of the triplets does not matter. **Example 2:** **Input:** nums = \[0,1,1\] **Output:** \[\] **Explanation:** The only possible triplet does not sum up to 0. **Example 3:** **Input:** nums = \[0,0,0\] **Output:** \[\[0,0,0\]\] **Explanation:** The only possible triplet sums up to 0. **Constraints:** * `3 <= nums.length <= 3000` * `-105 <= nums[i] <= 105`
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Two Pointers,Sorting
Medium
1,16,18,259
1,262
hello everyone i hope you're having a great day uh today we're gonna go over the lead code problem greatest sum divisible by three including white boarding approaches and solutions greatest sum divisible by three is a dynamic programming problem with the little number theory sprinkled on top so hopefully you've attempted a solution to the problem if not don't worry the description reads given an array named nums of integers we need to find the maximum possible sum of elements such that it is divisible by three in other words we're looking for the largest sum divisible by three using the numbers in the given array although it's tempting to use nested for loops a solution to this problem is possible using a single for loop hence we can achieve a big o of n worst case asymptotic complexity which is pretty good considering the problem has as check combinations of sums which can easily amount to a large quantity as the size of the list increases the solution isn't apparent at first glance since it involves the divisibility of three so we can think of numbers as the sum of primes in this instance two and one so which is zero so okay and so on and so forth the pattern continues you'll notice there's a pattern involving the numbers at the end of each sum right here there's a one two and then one and the next one will have two we can also express multiples of three like this so the straight number that i've written at the end of the sum is the remainder when that number is divided by 3. depending on which two numbers you sum the divisibility may change or stay the same so we want to keep track of that for instance summing a number that has a straight 2 and it's some representation with a number that has a straight 1 and it's sum representation will result in a number divisible by 3. similarly summing a number that has a stray one in its sum representation with another number that has a straight one in its representation will result in a number that has a straight two and this continues for each pair of numbers with different divisibilities we don't necessarily care about the groups of terms that sum up to an individual number but rather the stray number or remainder since it determines the divisibility of the result when summed with another number this logic is what will drive the propagation of the resultant sum in other words the maximum number divisible by 3 through to the end of the table and depending on which direction the iteration is taking place so considering this test case i'm gonna go ahead and force it to run right here it contains five integers the array may have unique numbers or it may contain repetitions counting the total number of arrangements of this list can be accomplished using this expression 5 factorial divided by 1 factorial times one factorial right here is essentially equal to five factorial uh this is because there's one eight one five one six and one three uh if the test case looks something like this then our arrangements would be five factorial over two factorial times three factorial it should be obvious that this yields a relatively large number the problem constraints also specify that the list may be at a maximum of 40 000 elements so attempting to check every combination will result in a time limit exceeded the calculation of 40 000 factorial will take an innate amount of time in itself so since we want the optimal sum of numbers that will result in an integer that is divisible by 3 the approach will involve defining the subproblems as sums of two consecutive numbers and retaining the maximum sum for each divisibility in order to accomplish this the table will be structured like this where the rows correspond to the ith number in the array and the columns correspond to the divisibility of that result it is important to note that for each iteration the resultant number in the divisibility column will always be greater than or equal to the previous iteration this is what determines the optimal path now that the approach is determined i will go ahead and write the pseudo code and then we will move on to implementation so first we want to go ahead and define our table you will see later on why not add a one uh to the size of the array the table will have dimensions n plus 1 by 3 to correspond with the numbers in the given array so next we want to initialize the table for iteration since it currently contains only 0 values this also covers the case that the size of a given numbers array is less than three notice how i use the modulus operator here i want to make sure that the first number that is set on that first row is set to the proper column if we get under a given array of either size one or size two this will go ahead and exit properly now we can begin the iteration as stated earlier the asymptotic complexity of the solution is big o of n so nesting loops isn't necessary since the current iteration of the table will contain the maximum result for each divisibility the relation depends on the previous value for each divisibility each iteration will calculate the sum of the current number with the previous result for each divisibility so we will begin iterating at the next one for each column or divisibility the sum in the corresponding column are calculated the logic will look like this oh actually we don't need that yet and here's the column now that the sum and the corresponding column are calculated we want to set the result to its corresponding column in the current iteration so then we go ahead and we repeat this for the next two numbers the only thing that changes here is the index of the previous row that we're accessing since this is a little repetitive i'm just gonna go ahead and leave a comment at this point the columns for the current iteration are set to the maximum or optimal result one of the caveats of summing each pair of numbers is that the divisibility may or may not change and there are instances where two different results with the same divisibility may be calculated this implies that one result may be replaced so in order to retain what we've calculated we copy the values over to the next row before the next iteration so maybe you notice that i have written row um that's just her index foreign so i'm going to go ahead and leave it there so you can properly examine so this loop will iterate end times over the size of the given array so finally we want to return the result since we iterated from the beginning to the end of the table the result will be in the zeroth column of the last row so note that if for whatever reason we never received or we never calculated a value that was divisible by three then the zeroth column will be zero and the function will return zero it's right there this is our algorithm now that the approach is written down we will implement this in code so i'm going to start by defining my table next i'm going to go ahead and initialize the vector since it is guaranteed that the given array will always have at least one digit we can do this so you may have noticed that i have something right here that's a little cryptic or arcane uh essentially what this is doing is that it's making sure that this evaluation is one so this first not operator flips this number to zero and the second one flips it just to one so i could have easily probably just written or typed down dp of one but there's a few edge cases that kind of rely on this so i leave it in there right next is our loop there we go so first we calculate our sum next we determine if that row or column in our current iteration is going to be replaced with the result of the sum so next we do the same thing for the next two columns so yeah it is as simple as changing the index in which we are accessing our previous iteration now i probably could have written a for loop and it would still give me constant time for each iteration but i chose to keep it like this because it was giving me slightly better performance so now we go ahead and we copy over the values to the next row okay and finally we make sure that we return the correct value from the zeroth column now notice that i'm using nums at size and not nums that size minus one this is because i've declared this to be one more row greater than the size of the given array uh there's several reasons for this or at least one really good one we want to make sure that we retain this logic without having to perform additional comparisons so i go ahead and i do this right here so i can copy over to the next one without the program segmentation faulting okay so now we go ahead and run there we go the tests are accepted i'm going to go ahead and submit and there we go 34.03 so before we finish can we do this better and the answer is yes the solution can be further optimized we can reduce the size of the table to a single array like this i can go ahead and just get rid of this business right here now there is one problem with going ahead and doing this since it's possible that two results may have the same divisibility we want to store the results elsewhere in order to avoid over calculating and to allow us to compare them against each other so we calculate and store the sums first since our table is one dimensional i can just go ahead and get rid of the row axis and we just do it by the column go ahead and remove this so in this case copying over the value over to the next row is not necessary so we can just go ahead and do away with this finally since the table is no longer two-dimensional we just return the two-dimensional we just return the two-dimensional we just return the column and we end up with this which is a lot more concise i actually like this a lot better so now let's go ahead and test this program oh what did i do wrong oh forgot we actually can start at the zero with index i just forgot to flip that right there accepted so we can go ahead and run this and there we go 89 um i actually ended up getting 99 at some point but still a better and a lot better than uh 34 percent so to conclude the solution will still iterate through the given list of numbers and store the optimal result in the table based on the divisibility of the results uh nothing really has changed except for that we're not consuming as much memory as we were before um technically i could probably turn this into array um i tried a vector before but that kind of slowed the program down a little bit since it was doing it each it was uh creating a new vector each iteration i found this to be the best result since it's possible that the compiler is actually placing these at the beginning of the method or function anyway i hope this helped you guys out um i hope you enjoyed the video uh i'll i guess i'll see you guys later
Greatest Sum Divisible by Three
online-majority-element-in-subarray
Given an integer array `nums`, return _the **maximum possible sum** of elements of the array such that it is divisible by three_. **Example 1:** **Input:** nums = \[3,6,5,1,8\] **Output:** 18 **Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3). **Example 2:** **Input:** nums = \[4\] **Output:** 0 **Explanation:** Since 4 is not divisible by 3, do not pick any number. **Example 3:** **Input:** nums = \[1,2,3,4,4\] **Output:** 12 **Explanation:** Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3). **Constraints:** * `1 <= nums.length <= 4 * 104` * `1 <= nums[i] <= 104`
What's special about a majority element ? A majority element appears more than half the length of the array number of times. If we tried a random index of the array, what's the probability that this index has a majority element ? It's more than 50% if that array has a majority element. Try a random index for a proper number of times so that the probability of not finding the answer tends to zero.
Array,Binary Search,Design,Binary Indexed Tree,Segment Tree
Hard
null
74
Hello friends today I'm going to solve liquid problem number 74 search a 2d Matrix in this problem we are given an M by an integer Matrix and two properties each row is sorted in non-decreasing each row is sorted in non-decreasing each row is sorted in non-decreasing order and the first integer of each row is greater than the last integer of the previous row so what does that mean let's look at this example and try to figure out so the first property each row is sorted in non-decreasing order which means that in non-decreasing order which means that in non-decreasing order which means that here we have three different row and each of these three rows are sorted in non decreasing order so each of the values keeps on increasing as we move across each of the columns in the row right now the next property the first integer of each row is greater than the last integer of previous row so if we take this row look at this Row the first integer of this row is stain is greater than last integer of its previous row so 10 is greater than 7 similarly 23 is greater than 20 and so on so if that is the case and we note that each row is increasing so that would mean that each column wise also it is increasing right starting from this right it is increasing this way as over a column and it's increasing over a row to right so that is what we are given here now what we need to find is given an integer Target return true if Target is in Matrix or return false otherwise and solve it in logarithmic time complexity so we are given a Target and we need to find if Target exists in this Matrix or not and solve it in logarithmic time complexity so given these three few things that is this Matrix is sorted across both the rows and column and the second thing is that solving it logarithmic time complexity we can know that we need to use binary search to solve this problem so what is binary so it's basically in binary search we divide our search space into half based on which part which portion our Target lies in if at Target lies in this portion we just divide it into half and look over this portion and then again divide into half and look over the portion with the target axis and divide into half and look over so stat portion and so on until we find our Target okay so that's basically binary search in Pre Eve now let's see how we can actually solve this problem using binary search so we are given the target of three we need to find first of all which Row the target can exist right so we have three different rows so in which row can three exist well obviously three will exist in this row because 3 is greater than 10 and 3 is I mean 3 is greater than 1 and 3 is less than 10 right so less than 10 means it cannot exist in this value because all the values in this row are greater than or equals to 10 and so on for the rest of the rows so that would mean that 3 can exist in this row because the starting value is 1 and all the values in a given row is greater than it's I mean it's is in increasing order right so 3 is obviously greater than one so it will exist in this row so that's how basically that's the intuition we are going to use so to actually find the row we are going to use binary search so for that we take the first element of each row and now we check three where does three where can 3 lie so we take our left pointer our right pointer so this becomes our middle value and middle value is greater than the value which is 3. so we know that 3 cannot lie on row starting at Value 10. so what we do is we decrease the row 2.2 hour left so row becomes equals to 2.2 hour left so row becomes equals to 2.2 hour left so row becomes equals to Mid minus one now here our middle value is also equals to the same which is row right so in that case uh since both left and right are equal we return these row which is our left value right because this Row in this row we know that 3 exists now if our Target was equals to the um 10 so what would we do in that case if our Target was equals to 10 this will be our left right and this would be our middle value right so we know that 10 is equals to 10 but we are just finding the row for now so since we know that 10 will lie in the row starting at this value which is equals to 10 so 10 lies at this row right so that is when we return middle value so that is one thing and what if we are looking for a 11 so if you are looking for a Target value of 11 so in that case also our middle value is here is equals to 10 so we know that 11 would lie at could lie at this row but it there could be a chance that it could not lie it could lie at this row If This Were to start at some other values so if that is the case so what we do is to check if to check that we are going to check two things the middle value that is 11 is greater than equals to the middle value and 11 is less than mid plus 1 okay so what is meat plus one here meat plus 1 is 23 so 11 is less than 23 and 11 is greater than equals to 10 right so since this condition is valid we know that 11 lies between these two values so definitely 11 would lie in this row y because 11 is greater than equals to 10 so 11 is greater than equals to 10 and 11 is less than 23 so it cannot lie in this row as well it will only lie in this row right now similarly if we were given a value equals to uh let's say 30. so if you are given a value equals to 30 so in that case a middle value here H is equals to 10 is less than 30 right so of course it won't lie in this row so what we do is we increment our value of left so left is now equals to right in that case we return this row because now we know that 30 would lie in this row right and so on now that once we have found our row okay now that we found okay we found our row which is equals to this row now to find the position I mean to check if the value exists or not we're just going to use binary search the normal binary search and find the value so if we found the value we are going to return to if we are not able to find the value return false and if in case middle value is less than Target then what do we need to do is we shift our um left pointer towards meet plus one and if mid is greater than Target we know that we need to go towards the left so our right will be equals to meet minus 1 okay so in that way we are going to solve this problem so now we understand this problem let's try to solve it so let us first Define m which is Matrix slant and let N equals to Matrix Dot land okay Matrix at index zero that line which is the number of columns now let's find row equals to function so create a function and search for the row so let left is equal to zero right is equals to M minus 1 that is the last index of the Rope okay and also we need the mid value so make value let us now create a while loop y left is less than right first we check if Target is less than Matrix meet and we are checking the first value right so we check if your our Target is 3 then we are checking with the middle value which is equals to 10 and since 3 is less than 10 so what we need is we need our right pointer to decrease right so write equals to Mid minus one else if Target is greater than equals to Matrix meet value if it is greater than equal okay now let us if we are looking for Target value 11 then in that case our Target is greater than this right so will it Line This it should line this if it is less than the next first value right so and Target is less than Matrix mid plus 1 and 0. so if that is the case then we return our row because we have found it else what we do is left equals to me plus one okay and we also need to finally return left okay now that we have found our row let us find our Target so here we are going to pass the row and let left equal zero write equals to n minus one and we find our maintenance now while left is less than equals to right what we do is if okay we need to find our mean value first here also we need to find our mean value equals to math floor a left plus right divided by two okay I'm just going to copy and paste it over here and now if Target is equals to Matrix uh mid value at that given row and you're going to return true because we found our mid our Target is if Target is less than Matrix row mean so if Target is less that would mean that our mid value is greater right so you want a mid value to become less so for that we are going to shift right to Mid minus one else left equals to meet plus one okay if we are not able to find our Target then we return false and now let us call our functions so first of all we need to find row equals to find row and now once that we have found our row we are going to find Target and pass the row and this will return our final result now let's try to run our code okay so we got an error cannot access row before initialization okay return r I'm gonna return meet we are returned the Mid Valley awesome let's submit this great so our submission is also accepted now let's look at the time complexity and the space complexity as we have been asked to solve it in logarithmic time complexity we are able to do that so here we are iterate I mean performing binary search over rows right and there are M number of rows so this is solving of M time complexity I mean of log M time complexity and here we are performing binary search across each of the columns in each row right so that is total of n columns so these can be solved in oau of log n time complexity so overall we are able to solve it in of log M times n time complexity I hope you liked my solution let me know in the comments down below thank you
Search a 2D Matrix
search-a-2d-matrix
You are given an `m x n` integer matrix `matrix` with the following two properties: * Each row is sorted in non-decreasing order. * The first integer of each row is greater than the last integer of the previous row. Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_. You must write a solution in `O(log(m * n))` time complexity. **Example 1:** **Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3 **Output:** true **Example 2:** **Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13 **Output:** false **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 100` * `-104 <= matrix[i][j], target <= 104`
null
Array,Binary Search,Matrix
Medium
240
3
That's a hello hi guys welcome back to my video english video will get another date problem yes-yes long statement with fitting characters which yes-yes long statement with fitting characters which yes-yes long statement with fitting characters which states the given string find the length of the longest substring without fitting characters example half inch is pe that substring of these parties Will Be Idea BCD And CVD Show The Length Of The Longest Sub Screen That Shivling Example2 Contents 520 That Meanwhile Comment Character Rates On This Subject Length In One That Security Forces Algorithm Grind This Particular Problem Consider Porn DSA BCCI Two Initial Pimps Lumax 2012 0 Switzerland Updated Second Grade Declare Now Tractor Bhi 150 Rate Sohalpur Amazing Distance From Physical 202 Learning And Knowledge Traversal To Vishwa Tak Particular Character Is Present In Between Tits Not Present And Reports Director 231 Increment Tarf Current Na Rector Of This Video Is Present In Every One Also perform the following operations my heart witch billiard one profit for the example of torch start initially i points 220 12 arch did not present in fact 21show book sector-21a book sector-21a book sector-21a depress increment loop control system of cards greater than a also depress increment and Max 212 hua tha i point to that next character which itself is a proven this is not present in the push up to be one increment california jewelers marks hai to aaye muzaffarnagar and points pe also not present in this to where one increment belief current lumax 200 g points to be easy not present in the given som pushya b2 b1 increment value of corruption has various matters a similar deposit ask any c21 increment trouble current land and maths ki ec points 216 dowry present in the given which is supported by the liberator It Up 288 Dal Jaggery And Pinjar Wicket Anu Entries Aware Name Account Is Vansh Previous 181 Which To Winning Director Is A Hu Hai FD Account The Number Of Element 181 And It Means To Develop In Comment That In Final Also Juice Element 18180 Ascorbic Acid 125 Video Single Character with great character of the characters which lies between boys istri aur difficult kar do ki bihar election real life basi torch start navdeep increase the value of that character 221 kudos to the entertainer auspicious template animal of current affair current length - account to volume of - account to volume of - account to volume of account Clothing EES 6 - Female account Clothing EES 6 - Female account Clothing EES 6 - Female British Journal Of Current Length Suno Increments Point To B C Hua Tha Sindhu Character B Positive Present In Between When Will Be Appointed By Twitter ID No One Minute Up For The Volume Two States Declare And Variable Account Vansh Create Unlimited 81.2 The Meaning of Unlimited 81.2 The Meaning of Unlimited 81.2 The Meaning of Stress Contact Number of Elements Which Is Present When It and It One Should Apply for This One To That Safe Become On A Superior Left With Sine Se That Hanif Bandh That Increment California In Maximum Notice For - 15023 Suli Content With Three Notice For - 15023 Suli Content With Three Notice For - 15023 Suli Content With Three and Beaten Maths Latest Paanch Election Width Kunwar Ajay Singh Explanation Point Mintoo Declare Variables Lumax in Current Rate Loot Lo Main Deobandi Will Contain the Land of District Strada1 Length and Current 202 Ka Pyaar Cigarette Now Actor Given on My Tablet Letter to the Same Twitter hua hai aur sanao vikram betaal actual algorithm notice traversing distance from physical 202 length hua hai ajay ko ki a hua hai ajay ko loot hua hai on karo e agri traversal which is weather the character spoils is present in the back 21st Used in the industrial average different function with arguments phir bhi 125 water and character which will be final Jai Hind is condition checks changing character this is present in the best now also one and support that this is this character this is not present in Vyaktavya one main Suraj seen in The Election Part-2 Who Is Suraj seen in The Election Part-2 Who Is Suraj seen in The Election Part-2 Who Is The Character Is Not Present Interactive Opposition Director 221 Instrumental For Nipr Loot Lo Hai Ki Aur Sunao Loot Lo Ki Anil Da Recipes For Depression In Adheen Declare New Pimples Account In Excel Sheet Shri Nandishwar Declare The Greater 81.2 The Shri Nandishwar Declare The Greater 81.2 The Shri Nandishwar Declare The Greater 81.2 The Meaning Of The Chapter 9 Is There No Option Open Tasty Value Of Account By Comparing Returns With IT On Ajay Ko Loot MP3 ePaper Daily Office Volume Is Vacancy Is A Number Of Characters And Elements Present When IT And IT Works On Loot Ajay Ko Hua Hai Loot Lo On Karo That This Picture Brother That The Character Single Character And Group Characters 80 Characters Day 30.21 David Characters 80 Characters Day 30.21 David Characters 80 Characters Day 30.21 David Particular Character Not Being All The Characters From 9 To 12 A Position Where It Points Vidmate Function Of The Real Madrid C Key On behalf of Zinc and Actor and Characters [ __ ] 0.2 Sector-21A [ __ ] 0.2 Sector-21A [ __ ] 0.2 Sector-21A Loot Lo Hua Hai Ko Increment Teacher Current Samsung Ka In Finally Find Value of Kar Explained by Subject Daily of Account from Current Affairs 1 Hua Hai Ki Unauthorized Bhi Ashok Chakradhar Laga Leaf Current Trend IS GREATER THAN MAX TIPS OBVIOUS AND MAX CURRENT LENGTH IS NEW DELHI Ajay ko hai ki in final chapter traversing dust string beetles valley of maths of good golden police complaint bhi andar na code hai jeth the intention to control the father and submitted a yesterday morning Don't submit successfully from this video help ou don't like button and subscribe my YouTube channel for my upcoming videos thank you
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
329
welcome to my channel so in this video i'm going to cover the solution to this question and do some live coding at the same time i'm going to go through the general process in the real quick interview so before we start the real content for today i would really appreciate that if you can help subscribe this channel so let's get started in every interview first you try to understand the question if there's anything unclear clear clarify with the interior and at the same time think about some lash cases so let's go through this question so longest increase in paths in the matrix so given n by m by an integer matrix return the length of the longest increase in pass in the matrix so from each cell you can either move in four directions left right or up or down so you may not move diagonally or move outside of the boundary so let's see example one you have the matrix something like this and the output is going to be four because the longest path is from one to two to six and then the nine so something like that um let's see how to solve this problem so the next part is about finding a solution so of course what we could do is we could do some profile solution uh like from each cell we do a dfs on top of each one and then uh we do it's something like we use bfs plus recursion uh we use the recursion plus backtracking to solve this problem but that's going to be like a exponential solution which is where it profiles so instead what we could do is um usually for this kind of question it is looking for some dynamic programming solution so what we could do is for each of the cell of the matrix so we could um it could have a corresponding uh we have a corresponding matrix which is a dynamic programming matrix try to record uh for each of the cell what is the longest path we can have uh starting from this cell so something like that so in this case we don't need to do like uh recomputation of uh we can save a lot of the recomputation which is going to be time saving um at this moment so essentially if we go to the dp solution we are going to have we are looking around the runtime as o m n and also at the same time the space it is going to be the same so let's take a look at the uh um the next part which is about coding so for coding take care about the speed uh the and don't also don't be so don't be too slow and also at the same time think about the correctness of the code and the readability of the code so um let's go through this uh solution at this moment so essentially all we would do is we have a dp array i'll say all right so let's say you have the dpi something like uh this is matrix.s and this is matrix.s and this is matrix.s and this is matrix zero because it says that the matrix is never going to be empty so we don't need to worry about like uh there is zero within this matrix so we could start to define this dp matrix uh something like this and then what we could do is um for each of the cell 0 and smaller than matrix balance the plus psi it's like you use a two layer of the for loop to iterate through the matrix um and uh well we iterate through this matrix so we call dfs and also at the same time you use the dp array to memorize the sub problem you currently have so what you could do is uh we could call it let's say dfs on top of each of the cell for i j and matrix and also this says dp array pass into it and finally um let's see what we should do yeah so actually we should have like a return value for this dfs which is uh so you're going to have like the longest pass as equal to zero so longest pass is equal to massdot max um something like this and finally we are going to return the longest pass um then it leaves us to implement the helper function which is a dfs function so dfs function is defined as a return using the return value as the integer and it has four different things the row this is the column and this is the matrix and this is the dp array so um first of all if we have already computed this problem which means um if you are have already computed the dp row and column then we just don't need to do the recomputation so it is something like if um this is not equal to uh if this is if it is larger than zero then you're just going to return uh itself without doing any further compilation otherwise we have like uh the uh we are going to go four directions like for each of the cell we try to extend in four directions to see how far we could go so this is going to be something like um four this is minus one zero this is one zero minus one and zero and one but something like this so it goes through each of the direction we have the new row and the new column something like uh this is a new row is equal to row plus direction zero this is new column that's equal to um one so um if the new row is uh smaller than zero so i'm just trying to see if it is out of the range so if it is or the new column is smaller than zero or newer is larger than letter or equal to matrix dollars or the new column is larger or equal to matrix 0 less or something like we have the corresponding next cell which is smaller than the current one so if you have a matrix neural new column if it is smaller or equal to the current one then you're just going to not visit the new cell then you're just going to continue otherwise what we could do is we could uh leverage the current result so let's see what uh it is it should be all right so it should be something like dp new uh dp row and the column is equal to efs on top of the new row new column matrix and dp so something like this and then finally we are just going to return uh dp0 column so that's essentially how this piece of code is something like and then the next part is about to do some testing so for testing we just for the simplicity of this one we just rely on this platform to help us do it let's see all right so it's one answer let's see why it is wrong so it is outputting three but we are expecting a four something like this so let's see why it could be something wrong um well if we all right so some all right so if there's no forward direction of it okay so i think i understand what is wrong here so essentially you should do something like this that's because if we are at a corner um or some color we have no way to extend uh we are going to return zero there but so for example we had one there's no way for us to extend in for directions so if we do the plus one here we are just going to return zero linear uh when we are doing computation for the cell but essentially you should do uh you should actually plus pause this cell actually to make sure that this cell returns one all right so um let's run it again so okay so i think it's fine here all right so uh that's pretty much it by the solution for this uh question uh if you have any questions about the solution or whatever feel free to leave some comments below if you like this video please help us on this channel i'll see you next time thanks for watching
Longest Increasing Path in a Matrix
longest-increasing-path-in-a-matrix
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`. From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed). **Example 1:** **Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[1, 2, 6, 9]`. **Example 2:** **Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed. **Example 3:** **Input:** matrix = \[\[1\]\] **Output:** 1 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `0 <= matrix[i][j] <= 231 - 1`
null
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
Hard
null
7
hi there to solve this challenge we're going to be using the ternary operator the module operator a while loop and the javascript global function parsing if any of these are unfamiliar to you please watch the cars that appear above during the video so if this sounds interesting to you let's do it all right you are still here so let's do it before you lose interest okay now if you don't already have the opponent if you already didn't read the description please follow the link in the description read the description of the challenge and then come back here so uh i already copied the starting function i'm going to go in visuals to the code and let's just explain what it takes to reverse a number because this is what we need to do to reverse a number so basically if the number is 123 then we need to um find the reverse of it and to find the reverse we basically have to get all digits one by one we get three then we add two to the end of it then we get one and so on and how do we do that we start a reverse from 0 right and basically keep multiplying the reverse by 10 and then adding the last digit of x and then dividing x by 10 and removing everything after the comma so it would be reverse or reverse multiply by 10 and then multiply and then adding 3 is 0 multiplied by 10 zero other three then we multiply three by ten and then we add two and we get 32 and then we multiply 32 by 10 and we get 321 but we always have to get the last digit of whatever we remain from x so basically every time after we add the last digit here multiply this by 10 and add the last digit we have to remove the last digits from here so let's see how that looks in code right because that will make it even more explaining basically we first want to start a reverse and we're going to make it a let because we're going to have to modify it during the function and then we use a while loop and we say that we you we basically keep running this loop as long as x is different than zero because we're gonna keep um dividing by 10 x dividing by 10 and at some point is going to be zero and once is zero it means we have used all the digits of it in the reverse and then we will stop so we say y x is different than zero what we want to do is what we said in the explanation we're going to say reverse equals reverse multiply by 10 and then we want to add the last digit of the current x the current value of x because we keep taking the last value right so we add basically x modulo 10 because that's how you get the last digit of a number in javascript you just use the reminder of the division by 10 right so you add that and after that you want to remove that number from uh from x so you say x equals plus in of x divided by 10 right divided not a question mark right okay so basically this is gonna happen until x is zero it's gonna take the last digit add it to the end of reverse and then remove it from the x right so at the end we just have to return reverse okay you just return the reverse because that's what the function asks so now this is not going to work from the first time because if you read the description there is a cover there and we'll see what it is it's going to work here right you can see it's working and it should be working right but when we submit we get an error and what's the error it's expecting zero here but how can zero be the reverse of this well let's read the description say assume we are dealing with an environment so we're basically on environment where we can only store integers within the 32-bit the 32-bit the 32-bit signed integer integrand minus 2 to the power of 31 and um and 2 to the power of 31 minus 1 right for the performance of this problem assume that your function returns zero when the reverse integral overflows so what because this uh when we submitting because this reverse integral overflows that environment that way we should return zero so this is a simple fix we just need to go into the problem and here at the end we're going to be using a ternary operator and we're going to say every verse is higher than mat pow and it seems we're using matte power as well and i didn't mention it in the introduction but that's okay much power is basically um finding the uh the value of a number other at uh at the power of another number so if you say math power of 2 and 2 you get 2 at the power of 2 out of the power of 3 2 out of power of 4 and so on so you want to say if reverse is higher than math power to the power of 31 right or so if this is true or this is true which we will say reverse and i have this um let's not do this let's do this i have this extension that gives me some suggestion right so if this is true we're going to use the ternary operator here and say if this is true then we want to return 0 because it means we are outside the environment if not we're going to use the reverse that we have found right reverse let's copy this and try it out submit all right and it's working all right hope you enjoyed this one i'll see you next time bye hey i just wanted to mention if you enjoyed this video and you want to see more content like it smash that subscribe button click the notification bell and youtube will send more of my content your way see you next time
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
1,046
foreign problem and the problem's name is last stone weight in this question we are given an integer array called Stones where each element in the array represents the weight of the stone so we perform a operation where we select the two heaviest stones in the available array and smash them together suppose if this two stones weight are X and Y if x is equal to Y then both the stones are destroyed If X is not equal to Y then the difference between the stones that is y minus X will be the new weight of the stone and finally at the end of the game there is at most one stone left and since they mentioned it is at most it means that there might be a case where no stones are left if no stones are left then we return 0 as out there are two hints given inside the problem statement to decide which data structure you have to use it is mentioned that you have to select two heaviest stones in one operation and also it is mentioned that you will be left with at most one stone so you can implement this question as a Max Heap using a priority queue where the elements inside the queue are sorted in decreasing order that is descending order from heaviest to lightest and then using the pole method you can get the top two heavier stones and smash them together and if there is a weight remaining you can put the difference inside back inside the queue and finally you will be left with at most one stone right so you can use the pole method to get the last remaining element inside the priority queue which will be our output now let's take a look at this example and see how we are getting the output I've taken the same example given to us the stones array now we need to add this elements inside the priority queue to access the two heaviest Stones so by default a priority queue in Java is a Min here but we need to implement the priority queue as a Max Heap so let's create a maxi so we'll iterate through the Stone's array from left to right and we access one element at a time starting from 0 till 5 so this is the Maxi now we are going to access the max here until the priority queue size is greater than 1 as soon as you find one element or less than one element that is empty priority queue you can end the iteration so we take the first element and the second element we check if the first element is Right which is greater than 7 so find its difference is 1 over using the pole method you get the top two elements and it will also remove those elements from the priority queue so a times 7 will be removed and now you add this one which is the new weight of the stone into the priority queue but this is a maxi bright so it will be sorted now go for the next iteration we take the top two elements again 4 into 4 is greater than 2 so the difference is 4 minus 2 which is 2 so add this 2 back into the priority queue so using pole method you access them so these two will be removed 4 and 2 are removed and this new 2 is added to the priority queue now go for the next elements this is Stone one and this is Stone two is greater than one so difference is one so add this one back into the priority queue remove these two existing elements and one will be added Now using pole method access the top two elements one and one is equal to one so there is no need to add a new weight so using pole method these two accessed and also removed from the priority queue and now you see the size of the priority queue is equal to 1 so you can end the iteration and using the pole method you access that element the leftover element which is one so this will be written as output now let's Implement these steps in a Java program coming to the function given to us this is the function name and this is the input array Stones given to us and the return type is an integer representing the last remaining Stone so let's start off by creating a priority queue where the queue will contain integers by default in Java the priority queue is implemented as a Min Heap but we need a maxi bright so I'm creating a comparator and overriding the compare method by returning the heaviest tone first then the lighter Stone you can also use the collections.reverse order also use the collections.reverse order also use the collections.reverse order method to implement the max Heap or you can also use the Lambda method but this is the default way how you can overwrite the compare method using the comparator and now we are iterating through the input array stones and adding the stones into the priority queue now the priority queue will sort them as Max Heap that is from Maximum to minimum weight and then using a while loop I'm going to perform operations on the priority queue until the size of the priority queue is greater than 1 which means there should be at least two elements as soon as there is one element or less inside the priority queue we end the while loop so inside this while loop I am getting the heavier Stone and the second heavier Stone and then I am checking if Stone 1 is greater than stone 2 then I'm adding the difference Stone 1 minus stone 2 into the priority queue if Stone 1 is equal to Stone 2 then you can ignore it there is no need to write the else block and once you come out of the while loop you are going to check if the priority queue is empty you have to return 0 because it is mentioned that if no stones are present return 0 if there is one stone present inside the priority queue which is our answer then I'm using the pole method to get the topmost element from the queue and return it as the output now let's run the code the test cases are running let's submit the code and a solution has been accepted so the time complexity of this approach is of n log n and the space complexity is of n because you're using a priority queue to solve this equation where n is the length of the Stone's Arrow given to us that's it guys thank you for watching and I'll see you in the next video foreign
Last Stone Weight
max-consecutive-ones-iii
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: * If `x == y`, both stones are destroyed, and * If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. At the end of the game, there is **at most one** stone left. Return _the weight of the last remaining stone_. If there are no stones left, return `0`. **Example 1:** **Input:** stones = \[2,7,4,1,8,1\] **Output:** 1 **Explanation:** We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then, we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then, we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then, we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone. **Example 2:** **Input:** stones = \[1\] **Output:** 1 **Constraints:** * `1 <= stones.length <= 30` * `1 <= stones[i] <= 1000`
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
Array,Binary Search,Sliding Window,Prefix Sum
Medium
340,424,485,487,2134
345
hello everyone welcome back here is Vanessa today we are going to dive into a fun and interesting cutting challenge uh reverse vowels of a string so this is a fantastic problem for those of you uh who are trying to improve your string manipulation and pointer skill so let's get started our task is to reverse only the vowels in the given string so if we have the word hello we swap the E and O to get uh poly similarly for elite code we swap e but remember we only swap about so uh consonants stay exactly where they are so how do we approach this well we will employ a technique called the two pointer technique where we use two pointer pointing at the start and the end of the string so we will move this pointers inward reversing the vowels along the way so let's start our python code and I will explain everything right away so vowels will be set of all vowels and S will be a list of s start and will be zero Len of s minus one and while starts less than and if s start in vowels and S and in vowels then s start as end will be S and S start and stores plus one and minus 1. and else if s start not in vowels start will be plus one else s and not in vowels then and will be -1 s and not in vowels then and will be -1 s and not in vowels then and will be -1 and return join of s so we can run it and I will explain everything right away so yes okay so it's passed a basic test case so what we did so first we Define a function called a reverse vowel inside a class solution so we will use the building set function to create a set of vowels for quickly lookup so we will also convert the string to a list because python string are immutable and cannot be changed in place so now the iterating part so the while loop as long as the start pointer is less than end pointer we will check if both characters at the start and pointer are vowels if so we will swap them and move both pointers but what if the character at the start is not available perfect we beat 97 with respect to runtime and 71 with respect to memory so uh working as expected and that's it for today coding challenge I hope you enjoy this problem as much as I did so the two pointer technique is a powerful tool to have in your Arsenal and is especially useful for problems like this and remember practice is key when it comes to mastering this concept so try to solve more problems that involves strength manipulation and pointers and if you found this video helpful don't forget to smash the like button and subscribe to the channel for more programming content and tutorials if you have any question leave them down in the comment section below so see you in the next video Happy coding
Reverse Vowels of a String
reverse-vowels-of-a-string
Given a string `s`, reverse only all the vowels in the string and return it. The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once. **Example 1:** **Input:** s = "hello" **Output:** "holle" **Example 2:** **Input:** s = "leetcode" **Output:** "leotcede" **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consist of **printable ASCII** characters.
null
Two Pointers,String
Easy
344,1089
83
hello everybody welcome to another video on problem solving so in this video we're going to take up another problem from lead code which is to remove duplicates from a sorted list so let's quickly go through the description once so it says we've been given the head of a sorted linked list and we need to delete all duplicates such that each element appears once and we need to return the linked list sorted that so let's look at the first example it says one two so you can clearly see one is being repeated and we remove this node and we get one two so it's a quite simple problem let's just look at one more example in this one and three both are being repeated so we remove both of them once as they're being repeated twice so we get one pointing to two to three as the result and let's go through the constraints which says the number of nodes in the list are ranging from zero to three hundred their values are from -100 to 100 their values are from -100 to 100 their values are from -100 to 100 and it's guaranteed that the list would be sorted in ascending order so now let's talk about the approach that we're going to take we'll start from the head pointer and if we see that the value at our current node is same as the value at the next node then we simply modify the next pointer of our current node to point to the next node of our next node so it may seem uh you may not be able to comprehend this at once but let's say that our headphone that our current pointer is at the first node in this example so we see that our next node's value is equal to is same as the value at our current node so we modify this value we modify the pointer of our current node and make it point to two instead of one so this is what uh this is the process we're going to take to solve this problem now i'm just going to code it and i hope you'll be able to understand it better so i'm going to declare a pointer struct list node star curve and before i do that i'll just check if not head let's just return the head and now we've defined our pointer let's initialize it to head and let's say while curve of next we'll say if cur of val is equal to curve next now if we do this our node which is left in the middle of these two is left without being freed so we need to free it we need to free that memory although it's not necessary but it's a good practice to do so i'm just going to declare define another pointer over here which says struck list note star to free equal to curve next then we say cut off next is equal to curve next and then we simply say free to free and then i'm going to say a continue and as a default thing i'm going to put cur is equal to curve next so after the execution of this loop all our duplicates would be removed and freed so after this we just need to return our head and that should work about right i'm just going to run it let's see oops i forgot the d over here let's run it again it says we've attempted to run our code too soon let's wait for a few seconds and let's run it now works fine for the sample test cases let's go ahead and submit it and there you have it works fine for all test cases 4 milliseconds 92 faster memory usage it keeps fluctuating i've submitted it submitted the same code uh two or three times just to make sure and the memory uses keeps fluctuating so even though the runtime makes up for it so there you have it that brings us to the end of this video thank you everybody for watching and do like and subscribe if you found it helpful
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
1,403
hey yo what's up my little coders what's up today delete hold question 1403 minimum subsequence in non-increasing minimum subsequence in non-increasing minimum subsequence in non-increasing order here's an example if there's the input array we need to return this subsequence of elements which in sum will make a sum which is slightly greater than the sum of the elements which are not included in this array however for example if we have the sum of 14 in the subsequence like here and the remaining elements are making the sum of 14 as well we need to encode the largest possible element in from the array which is remaining after we add the first greatest elements all right let's do that first of all let's create a list to store the result values that's the one point to notice the nums will never be that any numb will never be greater than hundred so we can use that properly let's create the counter to calculate how many of each num we have inside the inventory because we know that there will be only 100 possible numbers now let's use that and we also need to calculate the total sum of all the elements so let's iterate through all the numbers let's call up with our total sum and let's also increment our counter after that let's calculate the minimum subsequent sum which we want to get to do that we just simply want to divide the total sum by two and add one so that's the minimum possible sum and we also want to check our current sum now let's iterate to our nums counter starting from the largest possible element it might look a bit wasteful for example if you have i don't know an array such as that or such as that but believe me if it will be like a very huge array which will contain i don't know let's say 500 elements it will become very efficient so we start from the largest elements and while the current counter is greater than zero the nums current counter so here we will have the base case for example if we reach this sum for which we are aiming so the current subsequent sum use creator or equal then our desired sum in this case we just simply return the result otherwise first of all we want to decrement our knobs counter if we get inside this file and also if you want to change our current subsequent sum and of course we want to store everything as well and in the end of course we won't return result let's check if it works so what's wrong here oh sorry newton brilliant let's submit perfect it was delete called question 1403 please subscribe to this channel guys to not miss a lot of content which is going to come soon thank you
Minimum Subsequence in Non-Increasing Order
palindrome-partitioning-iii
Given the array `nums`, obtain a subsequence of the array whose sum of elements is **strictly greater** than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with **minimum size** and if there still exist multiple solutions, return the subsequence with the **maximum total sum** of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be **unique**. Also return the answer sorted in **non-increasing** order. **Example 1:** **Input:** nums = \[4,3,10,9,8\] **Output:** \[10,9\] **Explanation:** The subsequences \[10,9\] and \[10,8\] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence \[10,9\] has the maximum total sum of its elements. **Example 2:** **Input:** nums = \[4,4,7,6,7\] **Output:** \[7,7,6\] **Explanation:** The subsequence \[7,7\] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence \[7,6,7\] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order. **Constraints:** * `1 <= nums.length <= 500` * `1 <= nums[i] <= 100`
For each substring calculate the minimum number of steps to make it palindrome and store it in a table. Create a dp(pos, cnt) which means the minimum number of characters changed for the suffix of s starting on pos splitting the suffix on cnt chunks.
String,Dynamic Programming
Hard
1871
1,700
hey everybody this is larry this is me going over the biweekly contest 42 q1 the number of students unable to eat lunch um so this one i thought about doing it in a clever way during the contest um so hit the like button hit the subscribe and join me on discord all that stuff um but yeah but during the contest i definitely thought about doing in a tricky way and this is why for me relatively speaking four minutes is just really slow easy i think i was just really want to make sure that i read it correctly and i got a little bit confused of the stack and the cues and stuff like that all that was just like a little bit red herring at the end of the day though once you finish reading correctly you can just simulate it and the reason you can actually be a little bit smarter about it and there's private and you can observe it to be overland but noting that you know you should solve the problem that you're given which is that the number of students and the number of sandwiches are 100 and what that means is that um for my thing it could be at worst uh a hundred square which is fine because 100 squares ten thousand computers are fast these days and i just simulated uh let me know what you think that sprays in my thought process you can watch me solve the this problem live during the contest uh next thanks go what okay top of the stack which one is the top of the stack obviously it was top of the stack okay fine um there's a way reading problem but it's not even a real stack um that's not right i don't know how this works well i got slow part right oh whoops silly mistake okay hey uh thanks for watching thanks for the support remember to hit the like button and subscribe and join me just go ask me questions i love questions uh let me know what you think and i will see you next problem bye-bye
Number of Students Unable to Eat Lunch
minimum-time-to-make-rope-colorful
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a **stack**. At each step: * If the student at the front of the queue **prefers** the sandwich on the top of the stack, they will **take it** and leave the queue. * Otherwise, they will **leave it** and go to the queue's end. This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays `students` and `sandwiches` where `sandwiches[i]` is the type of the `i​​​​​​th` sandwich in the stack (`i = 0` is the top of the stack) and `students[j]` is the preference of the `j​​​​​​th` student in the initial queue (`j = 0` is the front of the queue). Return _the number of students that are unable to eat._ **Example 1:** **Input:** students = \[1,1,0,0\], sandwiches = \[0,1,0,1\] **Output:** 0 **Explanation:** - Front student leaves the top sandwich and returns to the end of the line making students = \[1,0,0,1\]. - Front student leaves the top sandwich and returns to the end of the line making students = \[0,0,1,1\]. - Front student takes the top sandwich and leaves the line making students = \[0,1,1\] and sandwiches = \[1,0,1\]. - Front student leaves the top sandwich and returns to the end of the line making students = \[1,1,0\]. - Front student takes the top sandwich and leaves the line making students = \[1,0\] and sandwiches = \[0,1\]. - Front student leaves the top sandwich and returns to the end of the line making students = \[0,1\]. - Front student takes the top sandwich and leaves the line making students = \[1\] and sandwiches = \[1\]. - Front student takes the top sandwich and leaves the line making students = \[\] and sandwiches = \[\]. Hence all students are able to eat. **Example 2:** **Input:** students = \[1,1,1,0,0,1\], sandwiches = \[1,0,0,0,1,1\] **Output:** 3 **Constraints:** * `1 <= students.length, sandwiches.length <= 100` * `students.length == sandwiches.length` * `sandwiches[i]` is `0` or `1`. * `students[i]` is `0` or `1`.
Maintain the running sum and max value for repeated letters.
Array,String,Dynamic Programming,Greedy
Medium
null
1,704
Hi gas welcome and welcome back to my channel so in this problem statement what have you given me here Na give us a string okay with the name S and whatever it is and the length of it okay so here all the number of these you It can be of length four, it can be of six length, it can be of length 8, that is, it can be of length, okay, what you have to do is, you have to split this string in half and check that your string is in both the halves. Is there equal number of vowels or not? If there is equal number of vowels then we will start attending, if it is vice it and false then this is our problem and this is a very easy problem. Okay, many people must have solved it, if not then We will see if it is okay for them, so what is your first example book given here, okay, so how many lines is it is of 4 length, I have also given you the statement that what will be the visiting length, okay so What you have to do is split it up, you have done it among yourselves, now you have to check how many vowels are there in this half, there is only one vowels, van count, its count is van and this count is van, if both are equal, then what in this condition? It will be i10 will be true, okay and second example, what is your text book, so how much is it and what is its length, what will we do, we will divide it in half and what is this yours, in this, A is your vowel i.e. van this, A is your vowel i.e. van this, A is your vowel i.e. van and here Pay book is double O, now you are cut, both are from length, both are from count, and if not, then if you file return here, then how can you solve this problem, then why do you have to meet, right? You will know the size and the length. If you know this, then what will you do now. Whatever N size you get, N L, whatever you take, if you find N size, what will you do with it? You will make it N/2, what will happen, it will be half. Okay, so what will you do with it? You will make it N/2, what will happen, it will be half. Okay, so what will you do with it? You will make it N/2, what will happen, it will be half. Okay, so what you have to do is to do the iteration once from zero to the end Y2, here you have to find the total number of wavels, how many total wavels are there here, then what you have to do is from N / 2 then what you have to do is from N / 2 then what you have to do is from N / 2 to N. Give right lace inside then what will happen here what will you do here again find a count here supposition is C1 this is C2 you have done fine now what will you do by comparing here people if C1 = comparing here people if C1 = comparing here people if C1 = C2 then return true respect Vice will return false, so now we give it on the code itself, let's see the court, what have we done, we have taken a l function, what will it do with this vowel name, it will check any character whether it is a vowel or not. So what will it do here will check in both of them you have to see neither so here what will you do here in case also people in case people also here is sara your punch is verb so here we have if whenever this condition is our fill So here the turn will be true because the vowel will be right and vice versa and will fall. This is a function of yours. Now what will we do with this vowel? I have found its length i.e. the length of the string. I have found its length i.e. the length of the string. I have found its length i.e. the length of the string. What have we taken here? C1 and C2. Okay, so what will we do? First iterate right from zero to L/2. We will check if it to L/2. We will check if it to L/2. We will check if it is a vowel. Then we will make C1 plus, that is, we will keep incrementing its count. Okay, then we will take the second loop, this is L /2. From where will it go, let's write till L, /2. From where will it go, let's write till L, /2. From where will it go, let's write till L, then here also we will check whether there is any vowel on any index, if so, then we will keep incrementing the count of C2, then here you will get the account of C1, the account of C2. Lastly, what will you do, Sigma? = If it is not there then it will fall here. Okay so I hope you have understood. If you liked the video then please like, share and subscribe. Thank you.
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
1,900
hey everybody this is larry this is me going over q4 of the weekly contest 245. the earliest and latest roundware players compete so well before my rant hit the like button to subscribe and join me on discord where we talk about this and every other contest forum right after the contest uh and just hang out and just you know nerd our problems as we do um that's the only reason why i keep doing this because i find it fun and enjoyable but in any case um so yeah for this one uh my rent is that i feel really sad about it because so i you could watch me look at it during the video but i had 36 minutes and three time limited exceeded in penalties so that's what that's like 50 minutes and in penalties because i did everything in c sharp um and then as soon as i changed the language to java everything just worked in the first go and i don't know what so i didn't so basically i spent 50 minutes um yeah so well not in this time on this time so 50 minutes i would have finished in let's i can't do math was it 45 yeah and that would have been pretty good well i still would have had maybe more penalties but uh but still i basically had most of the idea right so if you watch the video uh you can check that out so you know there so the way that i think about this problem is that um and if you did it in a java and also one more thing is that um from what i am told on my discord channel is that people who did it in python they actually got it to run in good time in python so because i was trying to i was like oh python is a little bit too slow so i'm going to try to do in c sharp because c sharp is better than python at least in execution time but i guess maybe they didn't change the limits and i should have done it in java but i was like ah maybe there's some c-sharp libraries that i want to use but c-sharp libraries that i want to use but c-sharp libraries that i want to use but i didn't even use them so mistakes were very much made and it cost me a lot of rank but it is what it is sometimes in these things and in life you know it's better lucky than good and today i feel like i was okay on the goodness but not lucky enough on some of these decisions you know conceptually um you know i mean and don't worry i know that i went a bit but it's okay my confidence is still pretty good because for me i know i knew how to solve it's just sometimes like i said in life you just get a little unlucky or whatever on things that you know you didn't think might matter or you know i mean who knows anyway you could watch me solve it live during the contest next so you could kind of see all the things that i was trying to get to not get tle before switching to java and i was like well i have like 20 minutes left let's just try java and then it got worked like i literally copy and paste the code into java and it worked except i had to change minor things with uh library functions but anyway let's go over that first so the first thing to notice is that n is equal to 28 uh that is a hint that you can do something funky and for me that was a little bit weird because obviously if you just say 2 to the 28 that's going to be too slow um so then the key thing to notice is what ask yourself how many games are there right so okay let's say they're 28 and obviously 28 is the most number of players so then 28 they're gonna be 14 games right and at most um 12 of them will be four uh unforced um or free maybe and what i mean by that is that at most two games are forced well it's because one of the players is you know first player or second player right and what i mean by that is that um because if first place does not meet well i mean obviously if the first player meets the second player then you're done in the first round but and otherwise if they're in different games then they have to win right so if they're 14 games they're only 12 games that where you know you can boot force on uh and they're free and you could go left and right okay and then now in the next round they're 14 um 14 players left and that means that there's seven games and seven games when there's five free for the same logic and then next they're seven teams or players so that means that they're three games oops and only one of them free right uh and then next they're four players that means that they're two games and none of them are free so keeping that in mind unless i made an off by one on the math but right did i mess this up is this three games or four games no it's i mean okay you get the point um i think i might have done it off by one i um plus what i actually when i did this during the contest i had some off by one issues but by the way you notice that here that means that they're only 12 plus 5 plus 1 is equal to 18 free games total and that means that these 18 free games you can go 2 to 18 of them because it can be in any possibility um that's base yeah and 2 to 18 of course is you go to uh was it 250 000 something like that ish right because 2 320 is a million of course and from that's pretty much the idea you do a simulation based off every possible game and then you just return the result based on every possibility and that's basically what i did but the hard part of course is done here where you um when you do the analysis uh and i did this i dug pretty quickly like i said uh if you took away about 36 minutes from this i end up solving this in how long did i solve this then so i'm going to add 36 here that's 53 so i stopped this in like 17 minutes roughly which i thought is which is pretty okay um but like i said i had timeout issues because they were even going since c sharp but um but yeah um so let's go over the code so yeah so initially we set f a is equal to just you know this is setting up all the numbers up all the players up and then we do a simulation of one round the first player and the second player and then here's the simulation for run round and we do this recursively here we just count the number of possible games and as we talked about it the number of possible games is that okay well if they play each other and of course this is sorted keep in mind that a is sorted if they play each other then that means that they have to play each other so it's one round one on the winning and the losing uh or max and the min sorry or min and the max um otherwise if a game does not contain at least one of the players then you return you know you do a count and then after that you just do a brute force on every possible game i did it with um with a bit mask and what happens with a bit mask is just that oops uh what happens in a bit mask is that okay let's say you have this number right um and i did it kind of backwards but it doesn't matter you could flip it uh but you look at one index of a time z you can just say that for example let's say i generated this bit mask um the zero means that the left player one and then the one means the right player one um yeah and then of course you know the first index means the first game the second index means the second game and so forth so that's basically the idea um and you know you could kind of run through the code now uh where okay so i've set the mask seed uh that's equal to kern um i actually even made some additional optimizations because i was getting time limited as i said though looking at other solutions that wasn't even necessary um it's just that i did it in c sharp and that was silly but basically yeah um you know i set the left and the right and then i put you know this is basically for if it's the middle we just put it in uh if this is the left and the right um you know if they play each other they should never be reached because this is you know obviously it would be returned here but i just kept it for symmetry reasons if uh you know if first is in it you know we just put it into the next round if right is in it we put in the next round otherwise we look at this bit mask and yeah i mean i think i might have swapped what i said about left and right but either way uh you get the idea of okay either the left goes to the next round the right goes to the next round depending on the bit mask and then i just kind of shift it by one so we do it then we bind and then recursively we simulate the next round um and that's pretty much it we you know we set the min and the max accordingly and then we return the min and the max plus one because for simulating one round which is this current round um that's pretty much all i have um i'm a little bit sad for a couple of reasons because apparently python would have worked so i didn't need to switch language and apparently i switched language to uh to c sharp which is maybe the only language that didn't work because you could watch me do this but i literally copy and paste my c-sharp literally copy and paste my c-sharp literally copy and paste my c-sharp uh code into java and then changed like a few things like length and math.min or a few things like length and math.min or a few things like length and math.min or something like that uh and it worked directly so i'm a little bit a lot sad um if you want to see a python solution i actually have one by uh n tissue i hope i'm saying that correctly that i liked i think yeah so this is basically the same idea but in python um maybe even more and like i said i even did some sorting so that is a little bit sad because apparently i didn't even have to do make additional optimizations but uh but yeah so check that out um yeah uh that's all i have uh like i said so what is the complexity of this well the compression of this is just two to the number of games times roughly and ish say um because each and you can also say that you there will be at most five rounds so you could hand wave a little bit but it's gonna be uh exponential so let's just say n times 2 to the n may be bigger but that's the rough idea um yeah that's all i have for this one let me know what you think uh hit the like button to subscribe and join me in discord you can watch me solve it live next and definitely yeah uh yeah i don't really have anything left on this one let me make it smaller so you can see but a lot of it is just me writing things in a funky way because i had to make some uh optimizations in c sharp which i would i didn't have like i feel like my original code was a lot tighter and you could debate it but yeah that's all i have and i will see you later bye silly i missed with the constraints that was just dumb okay let's see what a stupid five minutes wasn't even that hard maybe greedy is always tough to prove okay let's start 28 this is where having a pen and paper is handy i guess but 21 24 has to win this is a hard problem maybe how bad did i do oh well someone finished it nice well done uh what a silly mistake eight minutes wow i am slower today than i thought that's what happens when you go drinking i guess okay i don't even know how to simulate this it's not this tree it goes okay i don't know and is 28 that's to can we exploit that means this how many games are there after one game so the 14 results that's not true right because you have to force to win so there's only 12 results and then there's 12 games after that well the 14 games welcome 14 games in the first round at most um but two of them at most so you only have 12 choice and in the second round you have seven games so in the second game seven of them so at most only five of them are choiced and the third you have um you have four of them i guess but at most two of them you get to choose and then the fourth you have two and then that's the two numbers anyway that means that there are most four rounds and the number of decisions are 19 so that's before isabel i think yeah that's a crazy analysis can i simulate this fast enough to in python anyway so i know how to solve this now i think but i'm just trying to think where the python is fast enough because it should be fast enough it is just yeah should be fast enough okay but i'm still going to do it in java because i don't want to think about it okay so for 28 is 20. so let's just say to uh let's say men of 20 and uh okay what do we turn into it so don't get us wrong oh yeah this is java so it's dead and this is okay that should be only 17 19 okay but that's fine okay people should be solving this i don't if i could solve it i feel like a lot of people could solve it so yeah so this has only at most four rounds of simulation so that's only like 50 operations okay let's do it um yeah i forget java shipped on the input in c-sharp maybe i forget how to avail this is that fine is that right add to two it's a way list the one with the director ah i should have done it in c sharp this way someone's gonna leave a comment on how i how to do it in job with it's fine i'm gonna solve this and it's fine as soon as i solve this it would be a little bit slow but that's okay so this is one index for some reason yep okay so that works i wasn't sure about auto boxing and stuff it's been a long time okay one attack actually do i just have to keep on checking and this is something that's uh what happens is i'm unfamiliar with java so okay hmm okay oh right oh java why did i choose java and stuff platform is it too late maybe i should have just done c plus but it's fine hmm this is gonna be slow but that's fine that's why that's my thing about choosing a different language oh no one button ah i cannot do anything right today this is what happens when you use the browser thing what is the okay fine eight or five minute penalty i mean i'm already gonna use penalties but that's just a silly one that's what happens when you need to click a lot yikes it's fine if i should not have been drinking okay first it's smaller than second okay um so first and left wins do otherwise we took a bit oops this should be enough okay i think this is it roughly maybe i have some issues with things but in concept this is it so bad today just missed clicking okay let's give it a submit maybe i missed some edge case but i think this is okay i should try the 28 case or whatever yeah i should try this one why does that why is that too slow well i guess i do a lot of operations here but no that should shouldn't be that many operations i don't know why let's see if this gives me a this should be a million right hmm i should have tested this though because this is such an obvious test case why is that too slow it's not that it is wrong it is that it's too slow or maybe it's just it never converges um is that true hmm i guess not this should still be right it's just i need to figure out how to code it in a smart way also i oh because i know why because i don't add the remaining number um and it might be the number that i'm thinking about so i don't know it should be conceptually right but i'm missing some silly things yeah because this is just not you know it still gives me time and exceeded but it shouldn't go over five rounds so that means that my simulation as well uh let's see so this is five because no that should be right what is wrong with my code okay let's so this is right this is also annoying to debug hmm so i'm surprised that it doesn't go that deep now do um sword is a function hmm bye i don't know the answer for this one actually that sounds about it but that's not quite right why would that be right it uses a seed for no reason so i think this is wrong for i think that's why this is still pretty slow but at least it's working again i don't know this is really slow i might need to figure out how to do the simulation faster oh that's good at yolo though it doesn't look so good i mean the actual thing doesn't matter right because by itself it is fine but hmm i feel like this is it but my constants are too high so well i need to be maybe smarter about it to be honest because right now i do a lot of possibilities that are not necessary um so can i put this in a smarter way what if i don't sort i know that this changes the solution and it's not right but let's see the timing much faster so maybe i need to not sort by definition this is not possible i guess well i guess it is just not in that way so it's that way let's give it a try it was still too slow then i had to do a little bit better maybe this more mathematical way of doing it i thought this would be fast enough to be honest the other thing is that maybe i could do this a little bit faster this the annoying thing is that if it's not just some execution time this should run fast enough but and even then this is not that slow this is only doing i don't know why this is too slow maybe 50 million i guess that adds up hmm the thing is i'm doing a lot of branching that i don't need to that's the problem i think this could be we cursed and this is just proof force but maybe i tried to be too clever with this thing let's try again okay fine do that's so annoying how do i do this in a smart way um let me keep this point for now hmm so um so do i know this isn't what i'm just trying to see i mean this shouldn't have shouldn't happen anymore but yeah huh this is just very frustrating day like i feel like i know how to do everything but everything is just a little bit too slow um yeah okay so the men is take a double um yep i think this is still right i mean none of the inputs really matter it's just a summation of executing time execution time so it's just about ready this is fast enough i don't even know if this is right though i should have kept my old solution just to kind of see if this is right but let's just give yolo come on please if it's still too slow then yeah maybe i need to do something smarter and now it doesn't even give me a test case because it is fast enough but just barely not that's really annoying though because they made the constraints such that uh people got it pretty quickly too a lot of people got it wow i mean it's probably some divide and conquering that as well but so the earliest is there some additional pruning that i can do no i don't know i guess this is not needed anymore but shouldn't change performance hmm still pretty fast uh pretty slow like i feel like this is almost random now like it gets a little bit faster but hmm i don't get it this is only two to the 20 times i don't know times 100 at most maybe 100 million is actually too big maybe that's fair but not by that much hmm i'm really tempted to just have a whole table of this to be honest because how many possible answers are there how many possible questions are there so is 28 choose two now i wish i did in python because i don't have a c-sharp compiler ready to don't have a c-sharp compiler ready to don't have a c-sharp compiler ready to run this offline and 10 000 values i have to generate it so i'm gonna use an online compiler not gonna lie just wanna see this works so i'm basically running it here on this online c-sharp compiler online c-sharp compiler online c-sharp compiler and now i can generate a python dictionary i'm desperate joe all right i hope this is fast enough to run in this compiler thing though i actually don't know if it runs into anything let's not even print it out let's just see if it went fast enough it might timeout because i don't know how much quota they give you um okay let's just do 28. still too slow can i do this backwards yeah i guess so now 2 to the 28 is too slow i'm doing 2.8 billion operations so i'm doing 2.8 billion operations so i'm doing 2.8 billion operations so that's probably gonna be too slow too maybe i just don't know how to do this one maybe this is just one of those days where i feel like i'm close but and i the math seems to be okay but maybe not because this does 28 to 14 it's like 50 operations like i said it's like 50 million but maybe a slow 50 million um does this work for five is fast or 20 is pretty fast too is that true still pretty slow in here wow that's the power of a real fast computer i guess i wonder if there's any way of backing this out like given this pattern can i figure out another pattern that's faster i haven't thought about it too much it seems like it's just half for i think you just do a strategy for earliest and then do a strategy for latest but i don't know now because 2 is 3 for everybody can my simulation be faster i mean the funny thing is that on here it takes really fast but it tells you how fast the coach computers are but no 25 does 25 start getting slow probably i mean if this is too slow it's not going to be fast enough for my computer to run and then we start to do something smarter what am i doing wrong it would be funny if java is or i need it drivers or i need 352 let's give it a go i don't know what else to try so let's try java actually probably don't have to change that much let's see what i have to change uh oh that length let's start length slower case i'm really sure 80 is this are you kidding me this is like so much faster if this works in java i will be not happy but i mean maybe i'll be slightly happy but all right let's give it a spin oh my i don't know what to tell you i mean you saw i did the work hey uh yeah thanks for watching hit the like button hit the subscribe button if you like it join the uh join the discord uh to talk about this and other problems so i usually go over uh me and my channel my discord channel talk about problems after the contest like right afterwards so come hang out and share ideas and love and learning and all that stuff i'll see you later um have a great week hope you had a good contest and stay cool bye
The Earliest and Latest Rounds Where Players Compete
closest-dessert-cost
There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number `1`). In each round, the `ith` player from the front of the row competes against the `ith` player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. * For example, if the row consists of players `1, 2, 4, 6, 7` * Player `1` competes against player `7`. * Player `2` competes against player `6`. * Player `4` automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the **original ordering** assigned to them initially (ascending order). The players numbered `firstPlayer` and `secondPlayer` are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may **choose** the outcome of this round. Given the integers `n`, `firstPlayer`, and `secondPlayer`, return _an integer array containing two values, the **earliest** possible round number and the **latest** possible round number in which these two players will compete against each other, respectively_. **Example 1:** **Input:** n = 11, firstPlayer = 2, secondPlayer = 4 **Output:** \[3,4\] **Explanation:** One possible scenario which leads to the earliest round number: First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Second round: 2, 3, 4, 5, 6, 11 Third round: 2, 3, 4 One possible scenario which leads to the latest round number: First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Second round: 1, 2, 3, 4, 5, 6 Third round: 1, 2, 4 Fourth round: 2, 4 **Example 2:** **Input:** n = 5, firstPlayer = 1, secondPlayer = 5 **Output:** \[1,1\] **Explanation:** The players numbered 1 and 5 compete in the first round. There is no way to make them compete in any other round. **Constraints:** * `2 <= n <= 28` * `1 <= firstPlayer < secondPlayer <= n`
As the constraints are not large, you can brute force and enumerate all the possibilities.
Array,Dynamic Programming,Backtracking
Medium
null
43
so let's finally code problem number 43 multiply strings so we are getting two non-negrative so we are getting two non-negrative so we are getting two non-negrative integers and numbers one and num2 for example here and we are going to return the multiplication of these two numbers and convert it to string but we cannot use the building big integer or converted the input to integer directly for python we cannot use it directly yeah except for INT with we're gonna use a summer like three to integer method or in integer two to three methods to get the result so I want to Define it to functions to solve this problem so I will Define a string to int so this means yeah if you give me a string I will get a int outside so this is a one function for this function I can turn these two strings to the integers yeah respectively and I will Define another function into to the dream because this is for getting the result if I turn this number like here one two three to eight and this number four five six two inch and times the limit gets this end after that I want to get this end to the string so here I will put a so follow strain and here this one is the integer I will still use this n to return my result so here are two functions now I want to get my result yeah so the result should equals to string to int ense one so this is a integer and number two and the num2 after I got the integer I would to have my yeah surgery result so the result should be into two string yeah I would too put my int so the result is it so its result is here so this result is converted to string after that I need to return the result so this is basically what I'm going to do so first of all let's turn the screen like one two three to a integer in Python we can use a odd method to turn the surgery to eat yeah we're gonna first Define a variable result this is the inside it is still okay this is outside the global variable it doesn't matter because this is a the local variable result and we are going to tackle this uh this is a string while yeah because we are going to turn this string to a integer so while let me talk we are going to use the let me use a four method because we're basically gonna Loop through one by one and get the result so here I want to use Alpha method for I in Greens so inside here I will use a s variable as strain s and result through the plus the number so as I said I will use the odd this number so I don't need to use foreign for example this is a order one it is the sumness some integer and manners odd zerlo yeah we don't care what is the number of this order set like order one two we just needed to use this formula to catch the result for example this is a stream one all three minus or zero it is a still integer one and before that the readout through the equals result times 10 plus here yeah because for example this one if we only have one number it is one it is okay but what about we have a number like one two three we first get the one after one we got a two one times the ten so we get the result 12. when it goes to 3 it is 120 times this number three because this is a integer yeah now I think we can return the result so this is basically how to convert a string to integer it's a similar like reverse integer for the previous lead code problems yeah and now let's convert an integer like this one if this is a integer we will convert this integer to a stream yes it's still the same so while so as we are going to convert integer to strain so here the result will be an empty string so this is for easy calculation I can also Define a result as a zero first but that doesn't matter I will use a empty string yeah so the layout will be empty three and the while there is a still number that means this is not equal to zero while still N is a positive number I think yeah so the numbers in inside consist of digitally yeah I think it's always be positive integers I didn't say yeah non-negative it means always be positive non-negative it means always be positive non-negative it means always be positive and zero yeah so this is why we can use it yeah use it easily to solve the problem so why else so every result Plus so the equals to something for example I would to get the number eight first because here it is a integer and then another 8 and then zero because I would to get this integer yeah normally so I would to get the First Data from the right to the left and then the second yeah so it means finally I need to plus the result but before that I need to use some calculations as I said before here we will use the character calculators yeah so this is another python method first you can use this method to convert yeah to convert a integer to what convert that integer to the character yeah so for example here is eight uh what about we use the character yeah here is a we need to use this character and modular test so if this modular 10 it means here is 8. yeah right so this is eight and we wanted to convert this 8 to a screen eight so how to convert because here is only a number eight yeah we the value is not enough we have to add something so how to add something um we needed to add another odd what about another odd we needed to add the odd zero yeah R zero means some number is big enough and plus this number went converted to string it means it's just doing eight yeah I didn't remember what's the result of all that zero it is like 57 or something 57 plus 8 it means 65 and then converted this integer to counter it is a character eight yeah first one we got the character eight and plus the result is empty so we get a 8. yeah so what about to the next one the N should be divided by 10 yeah and divided by 10 we got this result yeah and then we got another eight when we got another 8 episode plus the previous result yeah so it is 88 what about another one yeah with us to plus all of them one way through the return is which that's needed to return the result so this is another string so here we need to consider if the result is zero yeah what if the result is zero when you convert it yeah when you convert it to a zero what you will return so this is a zero so you will return an empty split but for the calculation as we know even it is an integer value for math we need to convert it to yeah convert it to a character Zero but not an empty it's between yeah so how should we do that we just need to talk yeah the third result is a result else if it is an empty string we need to with her a character Zero yeah now let me run it to tag if there are any mistakes so here I did something wrong um yeah so this odd should be a strain I cannot use the inher directly if I design the dryer why do I need to use odd yeah so here should be the same let me delete it and try again yeah as you can see it works now let me submitted to tag if it can pass all the testing places and to prove everything is right yeah as you can see it's pretty fast and it passed all the testing cases so for solving this kind of math problem basically we want to put the yeah complex problem into a simple ones like we needed to write some simple functions these functions are similar as a reverse integer yeah first here is the string to integer and the integer to three there's no difference and for the time complexity it's also easy to yeah analyze because it is just the length of the member less of the screen so the less of the screen is 100 yeah 200 so the time complexity is just oh yeah because for this numbers calculation it is just similar to o1 we don't need to consider yeah and here is just a multiplication it doesn't matter so the time complexity is 0.1 thank you if you time complexity is 0.1 thank you if you time complexity is 0.1 thank you if you think this is helpful please like And subscribe
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
1,443
Hey everyone, I hope people will be well, have fun, be healthy. Today we will solve the questions in minimum time. You collect all appleside. Look, this type of questions is nothing new for us, there are just some mod modifications if you like BFS well. If you understand, then you will definitely be able to solve the question. People who do not know what BFS is and how to solve it, I have made very good graphics and if you go to the channel, I am of the truth, you will definitely understand. Till now I think that I am the most popular game on YouTube on playstacraft. If you want to learn it, brother, it's okay, then let's understand the question. Like every time, I always tell you, first of all, please read the question yourself. Make an attempt to see whether you understand the question or not. Match what is given in the list question with the input output and see if your understanding is matching. When your ability to read the question increases, then you will get the question. It starts happening friend, then the question of not taking so much load was what I was or not, gradually I will understand the thing of samjhaunga, I am demanding that you must have read your questions and not be deceitful, you must have tried the actress, then no delay- This was the question coming in the daily challenge of Cott, delay- This was the question coming in the daily challenge of Cott, delay- This was the question coming in the daily challenge of Cott, ok I thought that it should be told, many people think that brother DFS was thinking but still the question was not asked, why is it not important? Look, when you know the basic, then it is just like this. By practicing the questions, your basic core concepts become stronger. It's okay, but don't be afraid that logic gets formed slowly, but you should know the basic and concepts and I have done that very well. I had finished it, this is neither a question of tree nor this is a question of graph, basically the question is how to call DFS, this is the question of how to call DFS, I am talking like a man, you know DFS, okay and understand what is the question in this question. If you have minimum time then collect all app opportunity, look at the meaningless question, I have increased the complexity, friend, look what is there to be said in the question, what I have marked in red color is not the date of the thing, apples are present there, okay basically. You have been given a lot of trees, the radius is connected to each other, it has been given to you further, like zero note is connected to van, zero note is connected to none, van note is connected to four, here is okay, you van is connected to not five, this is It is okay, 2 3 are connected like this, they are giving you the ageless information about which notes, there is a further present between which two notes. It is okay, it is min's there, it can be used by drivers on different paths, this is also given in the question. It is bi- this is also given in the question. It is bi- this is also given in the question. It is bi- directional, bi-directional means directional, bi-directional means directional, bi-directional means no direction has been given to you can go from zero to van, you can also go from van to zero, okay, the third question is that we are starting from zero, vertex is this zero. We are starting from zero and we have to reach back at zero. If this is the start then we should have the end also. Okay and we have to start from here and whenever we start, we have to reach back from zero. If you go to the second note, it takes 1 second. We have to tell that we all the red apple people mean basically we touch where there are apples and basically look at the apples, come up with any concept, you can make anything as a concept, son. Theme of Mins: We have to touch the place marked red, of Mins: We have to touch the place marked red, of Mins: We have to touch the place marked red, go there and come back, tell the time, see how much time it took, let's first go from zero to 2, one second to come back. Second So here we went to A then we went to the van One second firm People went from 1 to 4 One second then we went back to four Then one second again 5 is fake One second Again we went back One second then the van We went back to zero and then went back to zero for one second, which means that we all will go here on three, we will also go on six, we will go to the offcourt and check somewhere below, and then it is not present. If you suppose, here it is a red note and present. Okay, so we consider that it is okay, we also consider this path, but when there is not even an apple tree, there is no point in going down, so minimum it will take you 8 seconds, in 8 seconds we All Apple's tricks can be directly asked by touching, i.e. you can go to Apple store, you can do whatever it is but D thing. Have you touching, i.e. you can go to Apple store, you can do whatever it is but D thing. Have you touching, i.e. you can go to Apple store, you can do whatever it is but D thing. Have you understood how the time of arrival and departure is important? We are fine on one note, if your Where we are going, there are apples, there are red apples, so we are coming back too, so this time second only, always think in multiplex of you, answers because now wherever we are going, we are coming back also, this is also here, you have the concept here. You will have to pay attention, okay, so a light hand here, if we are going from one note to another note, okay, from A note to B note, there is only one second for the origin and there will be a second for the arrival also because From the place we go, we will return to the same place. Reaching zero does not make it very easy to reach home, but we have to reach there. Dates is a problem, so we talk like we used to read the adjacency matrix when I used to read paste of graphs. Please friend, I do n't know about graphs, I am guaranteeing that you will definitely understand. You can trust me and see. Now ask the people whom you want to ask. I have read the graph playlist thoroughly for a long time. I trust you because people like Play Store, it is a thing. Okay, after reading this, you know how to make an adsensive list and make a matrix. Okay, basically we take the factor of vector A in this. What we did is take an index from zero to six lines, now take the unloaded dot map as well. It is possible that many people take those ordered maps and vectors. Okay, but for the year, it is simply that now there are not many maps, all this should be understood by you, hence we have to deal with space complexity, it was not different, thoughts are the same, let's do this. Okay, so now look, now as zero and van are present, so we will mark zero and van. Now we have to look back also, we marked van from zero, we can go from zero to van. Okay, we can go from van to zero also. Yes, we can go from van to zero also, like I have changed the color here for your understanding, it will come here from 1 to 0 2, so we can also go from zero, so you can also go from zero, right. This is also done, this is also done, I am explaining the forecency matrix from van, if we can go from van to four, then what will we do after going to the van index, if we mark it as four, then we can also go to 47, so we will mark it from four to van. That's right, 5 can go from a van, Hanji, 5 can go from a van, So 5 can also go from a van, And 5 can also go, Yes, 2 can go from 3, Han ji, 2 can also go from 3, you Okay, you can go to three, right, you can go to six, Han Ji, you can go to six, so here you can go to 62, so here you go, this is our total adjusted NC matrix. Whatever is there, Banke is ready, let's call, like what we did, when we called for zero, we came to know how many notes are there to connect to zero, van and tu, which is clearly visible to us, okay, if we talk about van then How many notes are connected to the van, zero four five from the van, we have one become, three notes are connected to the van, so what we did for D SEC of simplicity, again and again, we do not driver in it, we transformed it into this, okay adjustment. We call vector and vector, it is very easy for us. What is the benefit of this? Let's suppose that someone asked you to tell us how many notes are connected with 3S. So, where can we go with 3S? We can go only on you with 3S. Okay, so here it is, so what we had was one, three indexing, we got that we just got the list of tech, where we can go from our brace and note, it became easy for us, asked where we can go from 0 to where we are. You can go from zero, you can go, ok, so where can you go with a van, brother, you can go from 1 to 0, you can go from a van to four, you can go from a van to five, don't go, you will decide yourself, but where can you go? If we have the path cleared, then this is a very good step. The first is fine and many people would have been able to think till this point. Those who saw my graph, the code in general, what is its logic. It is fine to understand the thing from a common point like on our zero. It's okay, we started from zero, let's say, there is nothing below, okay, so we are at 0. At zero, if we get the red apple, then we will go to 0, which means we will not get any place. There was no need for a driver, the time of driversal is 1 second, if one note is going to another note then it is taking us one second. Keep in mind that when one will go and then another will come, that means whenever any two notes do a transaction with each other, then in that The lagna time of two units of second means it is fixed, okay, if we talk about zero, if we are at zero state, if we are at zero, then we are writing the cost, my cost is okay. DFS, basically in DFS function there are only two costs, note and mike. The note will play the most role, meaning from where are we starting? Cost means how much cost is it costing us on the note. It is zero because when it is at zero, there will be zero adjustment. How many adjacent vans and you are there, so if we reach till this point. This note is telling us which note we are on. Okay, understanding Hindi, a little concept gets shaken here. Okay, this note is telling us which note we are on and it is telling us how much time it took, meaning how many units we got. It will take one second to come and go from our parents, then the parent is ours, it will take zero to come and go, if you are here then the van is fine and here is its note, this is the note and you are because of parents, then tell us something of common sense, except vertex, it is fine. If you leave it then it's a matter of wherever you go, if it takes two seconds to transfer, it takes two seconds to drive it takes two seconds, it's okay, you tower it takes two seconds to drive it takes two seconds to color, if you drive it here, then from here to here. If you are thinking that it takes two seconds, then how much is the total, 4 seconds, so in total, whenever you go from one note to another, then what will be the total transaction, not 2 seconds, 1 second, for one second going, one second coming also has to be accounted for. So this is what we have to keep in mind, so for every time, for D first time, we will pass zero which will be my cost because call it from D vertex but after consecutive, for all the DFS calls, we will go to the cost note for two seconds. And it is taking 2 seconds to arrive, till now there is no problem, please stay in sync friend, don't go wrong like this, you will not understand, watch the video by reminding, the concepts come from here, okay, now as soon as I said, let's assume all the first. There will be a charge from the driver but let's explain to you in the form of understanding, I am going here, okay so from my zero to zero, I am going to your place, so how much is the cost here, brother, I am telling you whose index is telling. Is your node, this one is fine and its cost, did you understand why you are very good? Let's go to your three. Okay, now see what are the routes from you. If you have zero, three, six, three routes then 0, yours will not go. Why is it because zero is already visited? We will maintain a bullion named visited where we have already visited it, so there is no point in visiting it again and again. Okay, we just have to check whether it is there with the note and where else. We can go, we have to have this concept, so what did we say that if we are on three, we will come on three, then 3 2 3, what is this note telling and to come to three from you, we need tu unit of time, but what three is ours? I don't have Apple. Three, we don't have Apple. Everyone will return zero. Okay, if you come on six, then earn six on six. You six, what are you telling me, this note and what are you telling me, tell me. We are wondering how much is it taking to come here from our parents, it is taking 2 seconds, but we don't have Apple on Six, we don't have Apple and we can't know ours below, are we blocked somewhere because of this, why only edit on Six? If you check here, then only you were added on six, okay, that means only you can go till you, thought it, so what did we do, we blocked here, then returned ours to zero, okay, it's very good, now your Pay comes from zero, apan yahan pe hai to tu van kama tu very right apan four pe hai ok four pe hai to four kama tu again because for, here's 4 and 2 1 to 4 aana's costume, my cost is looking right Now what four, we have an apple. Han ji, this is an apple, we will return this one, now we can't go down anywhere, now we will return this one, you will return this one, the cost is fine for us and with 5, you will return the profit. Okay, the total return is 4 and it also has its own cost already. Aldo, it does not have Apple. Okay but discuss, it has its own cost and why is it considering this cost because our parents are the children who we have. Isn't that a cost to us with the child? There is something or the other cost to us. If there is a cost to the child, it means that Apple was present somewhere in the bottom, then we have to consider this cost, so what have we done? Said 4 + 2, we done? Said 4 + 2, we done? Said 4 + 2, scored 6 from here and from here you returned us the total, I understand this is a little big, I understand this, we will code and collect, you will understand, I would like to explain just one thing to you, C our. What is less, we called it zero, we called it WAN index, meaning WAN is its child and this is our child, what is less, isn't it its cost, which is our mic cost, this is our answer, we know it, okay then we What do we do with the child cost? If we make a child cost, then basically what we have done is that we already know the cost of the current note, what will happen because we are passing the function, but whatever call will come to the child, we both will know. We will add and add to it, if the cost of the child is something and we do not have anything in the current note, we will note like look, I understand the code, it is very clear, it will be understood slowly, but it will be like what we said first. We passed a note, we passed a mic cost and that's how to call DFS for the first one DFS of zero earn Hayes Apple Okay this one will pass zero here we got vertex this one got zero we have mic cost Because first, we do not need to pay any cost for starting, we are standing in our starting itself, okay, it is very good, what will happen in the second step, we will have that if it is visited, it is already visited, then we will return zero. So, we are not going to pay any cost, we will return it directly, whatever path and time we have, we will not go there at all, and if we leave it outside the floor and if the main floor is not invited, then we will return it as a guest note. We will mark it true till now, there is no problem, what do we have to do, we have to calculate a child cost, okay, so what we said is that we make child cost, brother of this note, whatever number of children are there, its cost is calculated. Like zero A will go one by one, child A will go which children are there and if we call them for all sides then DFS child tomato why did you pass, tell me who because this is my cost, after that whatever cost will be. Why would it be you? Do you understand? Because for the first one we need zero cost, but the rest of the matter is that whichever note we go to, we need two costs. What is this cost telling? From this note to this child. This is the cost of going, you will definitely do Hajj, whatever function comes, we will add it to the child cost, no problem, now let's come to what it means, below this note of ours, all the children we have are okay somewhere. There is no Apple, if there was an Apple then definitely there was some cost for the child because we go there but we did not get the Apple and at the same time this node is the current one, there is nothing in it either, we have a President in it too. Also, Apple is not present, so what did we do, the current child cost is zero and also we checked whether this is the current note, does it have Apple or not, returned it as zero, else in whatever case, what will we return? Child's cost plus my cost, whatever cost of this note, plus whatever cost of the child, I returned and did not have to do anything extra. Now I am telling you the message when you answer the questions. You break down and solve it slowly, you start understanding how the thing is moving, I will also do the court and tell you will understand the call button, but gradually we come to know what we have to do, lemon way. We can also solve it with but we will know how to break in the court, friends, don't worry that how it wo n't happen, we are not able to do all kinds of things. Okay, let's do the court, let's make it quick immediately. First of all, what did I say about a widgeted named widgeted name? So vector of Boolean widget is okay, if we keep zero then pass 0 - 1, keep zero then we keep zero then pass 0 - 1, keep zero then we keep zero then pass 0 - 1, meaning it is not creating anything, meaning basically empty factor has been created and vector has been created, okay what are we doing now Han, the time will be right Okay, and this one came to us, no problem, now let's call it simple, if I take the guest, if you have a note, then return it to zero, okay, else hit the guest off road first. We will pass the DFS function, so what we have done is that one by one we have called all its edition C notes, called it in child and are adding child cost, which will pass its child matrix, what will we have in the road. X will be my cost, what will be you, end will be Apple, okay, then we will return zero characters, we will return child cost plus, how do we run by dividing the things on padway, according to the logic that we understand, I am very true to the truth. No, you just had to be patient and breakdown it a little. Please subscribe the channel, like the video and comment. If anyone still has doubts, you are fine till then next bye
Minimum Time to Collect All Apples in a Tree
minimum-distance-to-type-a-word-using-two-fingers
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex._ The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`. Additionally, there is a boolean array `hasApple`, where `hasApple[i] = true` means that vertex `i` has an apple; otherwise, it does not have any apple. **Example 1:** **Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,true,false,true,true,false\] **Output:** 8 **Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. **Example 2:** **Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,true,false,false,true,false\] **Output:** 6 **Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. **Example 3:** **Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,false,false,false,false,false\] **Output:** 0 **Constraints:** * `1 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai < bi <= n - 1` * `hasApple.length == n`
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
String,Dynamic Programming
Hard
2088
274
hello everyone today we are going to solve the problem 274 H index given an array of integers citations we will citation of I is the number of citation a research is received a for their eighth paper return the research is H index the syntax is Define X to maximum value of H such that the given researcher has published at this H paper that has each been cited at this Edge times in the given example citation array 30615 its output is 3. which means that researchers as published by purpose and each of them have received three zero six one five citations respectively if the researcher has three papers with at least three citation each and the remaining two with no more than three citation each you can see that three steps index to understand how to calculate H index you can open this Wikipedia page in the calculation section how we can calculate that index is given here we can see how to calculate the H index if they face the function that correspond to the number of Citation for each publication we can compute H index as suppose first we want to order the value of f from the largest to the lowest value this is the first step we want to do you want to order the citations from largest to the lowest value then we Loop the last position in which f is greater than or equal to that position so what the given citations in the previous order then iterating from the first to the last if the index is greater than the citation value then return the index and given here for index 3 the index is greater than that of the citation value so we want to return the index value 3. okay let's start coding first we want to create a reverse function that xfc integer array foreign first we want to sort the citation array so we use the arrays sort method to sort the method sort the citation array arrays dot sort then we want to call the reverse method okay now we want to iterate over the array and check if I is greater than or equal to the citation value oh if index is greater than the citation of I then return that index if the method is not returned then its Edge index will be the size of the citation okay let's run this program okay thank you for watching this video
H-Index
h-index
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper, return _the researcher's h-index_. According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times. **Example 1:** **Input:** citations = \[3,0,6,1,5\] **Output:** 3 **Explanation:** \[3,0,6,1,5\] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. **Example 2:** **Input:** citations = \[1,3,1\] **Output:** 1 **Constraints:** * `n == citations.length` * `1 <= n <= 5000` * `0 <= citations[i] <= 1000`
An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space.
Array,Sorting,Counting Sort
Medium
275
441
hey everyone welcome back and today we'll be doing another leave code 441 arranging coins an easy one you have n coins and you want to build a staircase with these coins the staircase consists of K rows where I throw has exactly I coins the last row of the staircase may be incomplete so if we have coins given five we can only fill like two staircases and the last staircase will be empty and if we are given eight we can only fill three staircase and the last will be you can say incomplete if we had given 10 then 4 would uh yes our output would have been 4 because 4 would have been a completed staircase so we can do this by just subtracting our n by a counter which is going to increase at each step till our n becomes equal to 0 basically no coins left or we can just do binary search so we'll be making doing this by binary search which is just simple and you know how this works so by making a right pointer and a left pointer left will be starting from one right from the very end so while but before that let's make a result variable while left is less than or equal to right our right and calculating our mid if left plus right and then ground dividing it by two we will be using a formula here calculate our coins like we made dividing it by two and then multiplying it by mid plus 1 and if coins are greater than that coins are greater than the number which we are given the basically the number of points we are given we will just update our uh right and in the else case we will update our lab which will be mid plus one in this is how binary search works and result will be Max Plus result made not ID made okay after doing all of this we can just return result and this should work let's see if this works or not yeah this works and let's submit it and that's it
Arranging Coins
arranging-coins
You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete. Given the integer `n`, return _the number of **complete rows** of the staircase you will build_. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation:** Because the 3rd row is incomplete, we return 2. **Example 2:** **Input:** n = 8 **Output:** 3 **Explanation:** Because the 4th row is incomplete, we return 3. **Constraints:** * `1 <= n <= 231 - 1`
null
Math,Binary Search
Easy
null
256
hey so welcome back in this another daily Guild problem so today it's called Paint house and it's a medium level dynamic programming problem so basically what you're given here is just a two-dimensional array called just a two-dimensional array called just a two-dimensional array called costs now the number of columns here is always a fixed size so there's always going to be three columns but there can be basically n number of rows and so what these columns represent is basically the cost of a particular paint or color of painting a house and so essentially you can either paint the house red blue or green and so each house basically and so we basically have these rows here right and each row is going to represent like some particular house so this could be like house one for example I guess it's zero index so house zero this would then be house one and so forth right and then the columns Within these arrays are the cost of painting them a particular color so basically red blue and green and so the first house here to paint it red would cost 17 the second house uh two and the third house would be 17. all right and so essentially what we want to do is we want to paint them such that it's the minimum cost to paint all the houses and the only constraint here that we have is just that okay well you can't actually paint adjacent houses the same color I can't really find that here yeah cost yet no two adjacent houses can be the same color all right and so that's what kind of makes this challenging it's okay it's a minimization problem and there's this constraint here and typically when you see mineralization uh that kind of Screams a dynamic programming problem and so what I did and I'm initially going to show you the top Dam memoization approach and then we'll do just the iterative kind of true dynamic programming way of doing it but basically at every step say we're at house one here we can have like three different paths we can paint it red we can paint it blue or you can paint it green and then when we're after you've chose what color we want to paint it we're now at house two right so this house two and host two and so then their choices are kind of minimized where they have now two paths so house two can either be painted then if you previously chose red it can either be painted blue or it can be painted green if you painted house one blue previously it can be painted red or green and as you can imagine if you painted it green you can either choose red or blue and so forth so then you go on to house three and then it would be then minus and you can kind of imagine what comes next okay and so if we want to do that top down approach I'll show you it and then I'll show you more optimal way but it's important that you understand how to do it this way first and so if you want to translate that recursive relationship um into an actual algorithm we first want to Define our DP array or our DP function sorry and this is kind of templated code that you typically write so we want to write our recursive function I is going to represent like which house you're currently at and then we'll also say okay what was the previous color that we just used now initially the previous kill would just be negative one to represent um we haven't painted anything previously and we want to add our base case here so our base case will be okay if we're kind of going out of range let's just return zero and that kind of propagates the answer back up and so if we're if I is greater than or equal to the length of our cost array let's just return zero because you don't get anything extra or there's no extra cost for painting nothing and then you just want to say okay we want to return some Min cost here and so let's go ahead and Define that variable and initially this is kind of another templated or a common pattern is you just set it to infinity and so that just make sure that we minimize it and so then we just want to iterate so for I or really for every color in the range of our three different colors here and so they range uh between like 0 1 and 2 to represent the columns and so for every color or column I guess in that range let's go ahead and get the new minimum costs which is just the minimum of itself and we're going to recursively call this function but at the next level and we're going to set the new previous to the color that we just chose which is C but then to actually be adding the new cost or the color the cost of the color that we're just using let's just do plus and then basically grab from our costs array um what am I thinking here this particular cost of that color all right so let's go ahead and try running that oh looks like there's something wrong ah so this yeah sorry so this is a two-dimensional race we need to specify two-dimensional race we need to specify two-dimensional race we need to specify the current level that we're at which is I all right and let's go ahead and run that any time now it's taking a little bit of time ah wrong answer let's think here so that is I we definitely want to return zero on our base case this is the range that we're operating in and this is our Min cost which we minimize each iteration we call our function recursively iterate to the next level this is the cost of the color ah so we just want to make sure that one check here that one constraint that we're not using the previous color so if the current color does not equal the previous color then that should be good let's go ahead and run that try it again if the current color does not equal the previous color then we should be fine time would have exceeded oh let's go ahead and cache it and success so sorry about that I forgot to Cache it that's just because we'll naturally you would be able to follow them multiple different paths that you've already pre-computed before and you've already pre-computed before and you've already pre-computed before and so we just want to make sure that we cache any pre-existing work so that's cache any pre-existing work so that's cache any pre-existing work so that's the memoization approach this but this runs in a worse time complexity than we could so because the way we're doing it's going to run in basically um three times o of n or n times 3 basically which is really just uh o of n because you don't need this constant and so that's going to be both the time and space complexity for this but we can do better and we can reduce it down to an O of n time complexity but then in O of 1 a space complexity okay so let's go ahead and do that so the way you can kind of convert this into more of a bottom-up approach into more of a bottom-up approach into more of a bottom-up approach is we're going to use this existing array and modify it but what we're going to expect is we want to return at the end of this some minimum and so basically we're going to propagate forward from the left to right or from beginning to the end the minimum answer and this is kind of a common pattern that you would see and as you do more problems you'll recognize this pattern so essentially what you're going to want to return at the end of this is the minimum of the three possible paths that you could choose at the very last house so the last house is basically going to contain the minimum cost to paint that house a particular color for all the previous houses as well and so we just want to have the minimum of those three different possible paths once we've aggregated it at the end here and so in order to do that all that we want to do is we want to iterate through all the houses here so say 4i in the range of well the length of the houses or the length of the cost or really the number of houses so and essentially we just want for every iteration to be kind of computing the new um minimum costs at this particular house and so it's going to start from one onwards and basically it's just another common pattern where you just start at the next house and walk backwards so we just say okay the cost at this particular house and we're basically going to repeat this three times here so the cost at this house with this color is going to be equal to essentially just the minimum of the costs of the previous house at the other colors so that's going to be basically color one as well as color two because we're using zero and let's go ahead and we're just going to repeat this three times and I'll just further explain this in a second in case you have any other questions so let's replace oh this was Zero and then this one you can choose one because you're using two and this one yeah you want to use two because using one let's go ahead and run that oh we have a problem here what could that be so ah we're not actually aggregating that answer as we move along here and so what that's going to be is we want to add that as we move along here there we go so let's go ahead and run that and there it would be a much better time complexity because we're using or much better space complexity because we're using old one space but it'll be the same a Time complexity but so essentially once again what we're doing here is as we move from left to right we're going to be starting with basically once again we have rows of houses and we're always going to be looking at the current house and the previous house here and we're basically saying okay at this current house that we're at with three different paths let's look at what's the cost of adding this color plus the aggregated kind of running sum of what was costed here and so then we take the minimum of those two other possible paths and place it here and this kind of gets updated right and so then we update this one by looking at these two fossil paths and same thing here and the way this kind of Aggregates forward is then when you get to the next row this aggregation that we just did of the previous row can then be aggregated here by this uh color considering these two which once again these have the aggregated costs of not only this row but also this row and so then it gets aggregated forward and so forth and so once you kind of reach the final house here it'll have three possible Paths of the red blue and green with the aggregated costs and so you just want to choose the minimum of these three kind of possible paths but yeah I hope this helped a little bit and uh good luck with the rest your algorithms thanks for watching
Paint House
paint-house
There is a row of `n` houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by an `n x 3` cost matrix `costs`. * For example, `costs[0][0]` is the cost of painting house `0` with the color red; `costs[1][2]` is the cost of painting house 1 with color green, and so on... Return _the minimum cost to paint all houses_. **Example 1:** **Input:** costs = \[\[17,2,17\],\[16,16,5\],\[14,3,19\]\] **Output:** 10 **Explanation:** Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10. **Example 2:** **Input:** costs = \[\[7,6,2\]\] **Output:** 2 **Constraints:** * `costs.length == n` * `costs[i].length == 3` * `1 <= n <= 100` * `1 <= costs[i][j] <= 20`
null
Array,Dynamic Programming
Medium
198,213,265,276
403
hey everyone in this video let's take a look at question 403 frog jump only code this is part of our blind 75 playlist only code where we go through the blind 75 questions let us begin in this question a frog is crossing a river and the river is divided into some number of units at each unit there may or may not exist a stone the Frog can jump on a stone but it must not jump into the water given a list of Stone's positions in units which is sorted in ascending order we want to determine if the Frog can cross the river by landing on the last Stone initially the frog is on the first stone and assumes the first jump must be one unit if the Frog's last jump was K units then the next jump must be either K minus 1 a or K plus 1 units Rock can only jump in the forward Direction okay let's take a look at the examples here to see if we can quantify what they're saying here so looks like what we have is we have a bunch of stones here and I would just label these Stone one two three four five six seven and then Stone eight and we can see this is kind of like the distance right this is like the distance away so for example here we have like the start and then you have stone one and then you don't have anything and then like you have the third Stone and then you don't have anything and then you have like the fifth Stone etcetera right so it's kind of like that so what do we have here so we have that the Frog can jump onto the last Stone which is Stone number 17. we're not number 17. it's technically the eighth Stone but it's a distance 1708 right so think of it like that so the Frog can jump onto the last Stone by jumping one unit to the second Stone right so it can arrive here to the second Stone because we have a stone here and then two units to the third Stone so we'll skip this one and we'll arrive here which is the third Stone and then two units to the fourth Stone and again we'll skip this and we'll arrive here go to the fourth Stone here right which is again look how we're skipping a stone here so we go to the fourth Stone and then three units to the sixth Stone so we will skip this one actually and then we will go directly here so it looks like from here we have another Stone here we have five we have six right and then we don't have anything and then we have eight right so it's like that so directly from here or let me see if I did that right so it looks like we have the start and then we have Zone number one which is here then we don't have a second Stone we have a third Stone we don't have a fourth Stone we have a fifth Stone we have a sixth Stone we don't have a seven Stone and we have an eight stone so basically from this Stone over here it looks like it's jumping how many units is jumping three units to the sixth one so it's jumping one two and arriving over here right so we have that and similarly we can jump fourth units to the seventh Stone so we go over here and then we can jump five units to the eighth Stone so we arrive finally at our last Stone which is Stone 17 with the value of 17 which is the eighth Stone from basically what the frog starts off so in this case we would return true now in the second case here we'll return false and the reason is because it looks like there is no way to jump to the last Stone as a gap between the fifth and sixth stone is very large it's too large so what does that mean between then the fifth and the sixth Stone it's like a four Gap right it's a four Gap you need you would need k equal to four here now if we arrive at this position there's basically no way we can get k equals four even if from like here we jump directly to here which means K is equal to two the maximum we could do is K plus one S3 so we can't arrive on Stone eight we'd arrive on Stone with the number of seven which doesn't exist here so in that case it doesn't exist okay so that's the question and kind of let's see like how we can approach this right so given any single position K it looks like we have a couple of positions to consider right we have K minus one we have K or we have K plus one unit so when I look at this I basically just think of okay maybe K minus 1 would lead us to the answer maybe K plus 1 would also lead us to the answer so we could maybe consider it in terms of like that so a scenario where we use recursion and to arrive at the answer so maybe let's start off with a recursive approach to begin this with and then we can see if we can somehow improve this so let's see so first thing we notice is that Stone's first element must be zero and it must have like two elements minimum so given that the first element must be zero and that our initial jump is just one we would require that these first two elements have to be like zero and one right so we can actually just check that so if stones 0 to 2 does not equal zero one so if it doesn't equal this then we'll automatically false right and I guess the easier way to actually say this is if stones at one doesn't equal one then we'll just return false automatically right now we don't have to text stones or zero because it's guaranteed to be zero otherwise let's just have our helper function here right okay so what do we need in the helper function well I guess one thing we need is the stones right we actually need the stones themselves now we need to know like which Stone we're currently on because maybe we're on this Stone well we need to know where the stone is now we could usually pass in the index right you might say this is like index I or whatever but in this case index isn't really helpful because you can see here that like all of these are different all of these are an ascending order so we can just use like the value itself like the actual value of the stone which is like stone with number three so we can do something like Stone number here right that's that stone number okay so what are some other things we need what we would need to know K right we would need to know for example if I'm on Stone with the number of three then I must have come here from either like Stone one or maybe Stone two with k equal to whatever right so I need to know like what that K was so I would pass in K here as well and I guess one other thing we need to know is like what the last stone is right we need to know what the last Stone so we know like where we want to finish off so I guess we can just calculate that from Stone so we don't really need to pass it into the helper so let's just begin here so I guess the first thing we can do here is Define our base cases but before that when we are doing a recursion we can pass in something like let's say we're on stone three right we'll pass in three and then maybe we can pass in K as like K plus 1. so given that we have like the stone number that would be the previous Stone number so we need to essentially calculate the stone number that's new based on K so we can do something like new stone number it's just Stone number plus equals K right so this will be the new stone number now we can Define our base conditions so what are some base conditions well first of all something we could we should check is that if we are at the last Stone then that's true so we can check if Stone number is equal to stones and minus one and this will be the last Stone number in this case it's true right with the false case well let's say we're like over here and we make a jump of like three units well in this case we'll be like past the last Stone right so we don't want that so we can also check like if Stone number is greater than stones at minus one then we can also return false here what's another case well let's say we're here at Stone with the value of four and we make a jump of one but then we would arrive at a stone of value five but it does not exist so obviously that's an invalid case too you'll go in the water so we can check also if Stone number not in Stones then we would return false right so these are kind of like our base conditions here that we need to check out for now if we have this all we need to do now is recurse so we can do something like Plus and this will be self.helper and this will be self.helper and this will be self.helper I will fill these in after I Define my three variables here so we'll have less we will have same we will have more right and basically here we need to pass in K here so this will be K minus 1. this would be K plus 1. would be K this would be K plus 1. and then I just return whether any of these succeeded right that's all I need to return if any of them succeeded then I'm happy with my answer now what's one more thing we need to pass in is actually the values into the recursive function so we have stones don't number so what are we starting off at well Dimension here we're starting off at Stone kind of zero right we're starting off at Stone zero here so we're passing zero initially K would just be equal to one because we can only take one jump here so then Stone num will be equal to one and then we will do a course here where we pass in stone num as one but then we either try to go just one spot forward we've got to go two spots forward or this one we actually remain in the same spot so this is actually not allowed we need to only move forward so I would just add a condition here so if K is greater than one then I will consider less to be this otherwise I would default less to just be false right I would do this and basically from there if with any luck if we arrive at the goal we will return that and so we can try this and we can go ahead and submit it or we can see that this one is a working solution only problem is that it will take too long and even with added memorization it's still going to take longer than we wanted so I'm not going to add memorization in this video I have other ones where I've done that so I'm not going to show it but basically you define a memo here as in the dictionary and then you would have to basically cache the stone number and K because these two are the ones that are basically changing right so you'd have to Cache that information okay so given that we know that this works what's a simpler way that we can do it without this recursion and maybe if you kind of think about it what we're really doing is we're starting off at one stone here and we're basically just going outward right like we're considering K plus 1 we're considering k and we're considering like K minus 1. so basically like at any position like we're considering three more positions that we can possibly go to so this is basically just hinting at me that we can do a breadth first search right because we're just expanding outwards we have more than one choice in this case in breadth first search you often just have like one choice but or maybe you have more maybe you're going all four directions but you're basically just expanding outwards right so we can do that in this case so why don't we try a breadth first search approach so breadth first search hopefully it's like very similar to this one and it turns out it is because once you have a recursive approach then breadth first search is pretty simple so let's go ahead and comment this out in a breadth first search we need to Define our Q right we need to Define our scene variable so this is our basically set of visited places so this will Define like the places we visited and then we'll just start off with the queue right now what are the things we need to add in the queue well we already have that information here right what's changing it looks like Stone number is changing and also K is also changing so we can just pass in stone number and K into the Q and we will pop that from the start of the queue so now we have the information that we need and now we can just check our base conditions so if Stone number is equal to basically the last one so Stone's at -1 now we can just return Stone's at -1 now we can just return Stone's at -1 now we can just return true now these two conditions here we can basically just check them when we are adding to the Q we don't want to really check them here it's because you're going to be adding when you don't really need to be doing that so we can maybe just skip those one other thing we can do is let's say we can check whether or neighbor in K minus 1 K or K plus 1 right so these are a set of neighbors these are the set of locations that we can visit what do we want to calculate the next position right we want to calculate what the U position should be so this one we can say next position is Zone number plus K now we don't really have to do this here we can basically just add it in the queue but I just kind of want to show both approaches so here we're just doing the second approach where we put it inside of the queue here and so now we have our next position and we have K so we don't need to do this addition here but now before we add it into the queue what are some conditions we want to check well I guess first thing we want to check is we want to make sure that this is part of the stones right so we can check if next position in Stones right what's something else we need to check well another thing we need to check is that we haven't visited this place before because it's possible that if we're over here right let's say this is a new iteration like let's say we're on this iteration here this out this one right here it's possible that this one will also add in this right here right it's possible that it can add in this as well so we don't want to do that because we've already visited it so we can do is we can do end Exposition k not in scene right and again we have to add in two things because these are the two things that are changing so if both of these conditions are basically valid then we can go and add it to our queue and as with normal breadth first search we have to add it to the scene right here we add a next position and then K okay and that's basically it and then we'll return false over here if this doesn't work now you may ask what do we need to start off here well we know here when to start off with the stone number and we need to start off with K and you can actually see here that we already consider the case where stones at one does not equal one so we already know that it's one so we can maybe just start off at the stone one and if we start off at the stone one then the K has to be one right because we came from Stone zero and we took one jump so the K has to be one here so we can go ahead and we can go with that and so in this case if you think about it K minus one uh this one basically would require us to go backwards right so potentially we can also just check um if next position uh let's see is less than Zone number then we just don't consider this one so we can do that so now let's go ahead and run our test cases and it does not work so let's see where we messed up here so we have minimize this so we have this condition which is true we start off here which is true we do stone number and K and we pop from the front which is true if Stone number is the last one then it's also true what else do we need to check so we have K minus 1 K and then K plus 1 then we add it we check if next position is less than or I guess equal as well right because equals shouldn't work so I guess the only way is like equal right because K will be positive so you can't really fall into that approach there so we'll try this out okay so that was one bug but it wasn't the bug you're looking for so we have that and then here if next position in stone and next position K not in scene so I believe that should be correct so next position in stone and X position not in scene uh here's the problem so it shouldn't be K it should be neighbor right because our K is varying so here it should actually again be neighbor that is the problem so let's try now and here actually I gotta add in neighbor as well neighbor so let's try now okay and let's submit perfect so this is a working approach uh it's not the best approach I will admit that there is like a better one but I think this one if it can even come up with this one like a breadth first search approach you will probably um just past the question otherwise we can kind of improve it instead of using queue you can use DQ which is like a constant time removal from the front obviously this one is not like that something else you could basically do is convert this to a set right let's actually maybe just do that so because we're checking if in Stones if Stones is like very large it might take a while so something we could do is we could just cache last Stone as zones at minus one and then we can maybe just convert stones into a set right so here we would just do last Stone and then where are we looking at stones again Stones here so yeah so this one should be fine so let's try this out and you can see it's much faster so changing from a list to a set really made a difference over there okay thank you for watching
Frog Jump
frog-jump
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit. If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction. **Example 1:** **Input:** stones = \[0,1,3,5,6,8,12,17\] **Output:** true **Explanation:** The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. **Example 2:** **Input:** stones = \[0,1,2,3,4,8,9,11\] **Output:** false **Explanation:** There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. **Constraints:** * `2 <= stones.length <= 2000` * `0 <= stones[i] <= 231 - 1` * `stones[0] == 0` * `stones` is sorted in a strictly increasing order.
null
Array,Dynamic Programming
Hard
1952,2262
113
question 113 of the code path sum 2 given the root of a binary tree and an integer target sum return all route to leaf paths where the sum of the node values in the path equals target sum each path should be returned as a list of the node values not node references a root to leaf path is a path starting from the root and ending at any leaf node a leaf is a node with no children so here is one example we have a binary tree and the paths that have been highlighted are the paths that equal the target sum so 5 4 11 and 2 equal 22 5 8 4 and 5 equal 22 and that is pushed into the output so this is the output which we're going to be looking for remember we need to be returning the node values not the node references so with this solution we'll probably be using some form of dfs so we will be using recursion and with recursion you need base cases and you need a recurrence relation so base case just imagine this tree if it was equal to null what would we return well we need to return an array of some sort so we could just say if root is equal to null return an empty array so this will be our sanity check so let's have a look at what we need to pass down the tree in order to work this out well we need to keep track of the current total so we can see or if the path is equal to the target so we can have current sum which we can set at zero and at each stage we can add the node value to current sum and add up and check to see whether it's equal to target but we also need an array containing each node value because that is what we're going to be returning so if we have a current array variable which is equal to an empty array to begin with and at each level we push into the array the value of the node so let's have a look how that would pan out so at the first level current sum would go to five and we'd have an array containing five at four current sum would equal nine we'd have an array containing 5 and 9. at 11 current sum would equal 20 and we'd have an array containing 5 9 and 11. current sum at this node will be 27 that'll be 5 9 11 and 7. now this is pointing to null in regards to its left child and its right child so this is now a leaf node once we reach a leaf node we can check to see whether some we've got is equal to the target it's greater than the target so what do we do now well we haven't found a valid solution so we need to backtrack so we need to pop off of current r so we need to remove seven go to this level check if there is another valid child to look through there is we can check the right child so we have a look at this raw child so at this stage the current sum is going to be 22 the array is going to be 5 4 11 2. this is pointing to null so two node is a leaf node what do we do at this stage we check to see whether it is equal to the target 22 is equal to the target so this is a valid solution so now what we can do is we can push these values into a result array and now we need to backtrack to check for other potential solutions so we go back to this level check there's nowhere else to look so we backtrack again we pop off of current r we get to this level we check there's any other potential child we can look at there isn't so we backtrack go to this level there is a right child so we go down this level check at this point the current sum is equal to 13 and we have an eight go down the left child current sum is equal to 26 we have 5 8 and 13. this is pointing to null with both the right and left child so this is a leaf node 26 does not equal 22. so we backtrack go to this level 13 has been popped off at this point so we've only got five and eight we check if it's got a right child in this case it does so we check that side so at this level it's going to equal 17 so we've got five eight and four go down the left child at this point it's going to equal 22 5 8 4 5 this is a leaf node so we check 22 is equal to the target we add this ray into res now we can backtrack so we pop off of current r we go to this level we check the right side at this level it's going to equal 18 and current array is 5 8 4 and 1. 18 does not equal 22 so we backtrack we get to this level we realize there's nowhere else to go so we exit that recursive function and now all we need to do is return res time complexity for this solution is o n squared in the worst case scenario we could have a complete binary tree here and there would be n over two leaves and then for every leaf that we have we'd have to perform n operations our space complexity is o of n because we are storing n values within current array and just to note the result array that we created to store the results is not included within the space complexity so let's start by initializing res as an empty array let's create that recursive function let's call it dfs i'm going to pass in root current sum and current array and we're going to call dfs passing in root passing in 0 as our current sum and then an empty array for the array that is going to store the current path so if root is equal to null return an empty array so this is just a 70 check now we can add to the current sum the current value of root and we can also add to our array the value of root so we want to be returning a list of the node values not node references so here we state root.val and references so here we state root.val and references so here we state root.val and then we check if it is a leaf node so root.left root.left root.left is null and root dot right is null and we also need to check where the current sum so the current sum of the current path we have is equal to the target if it is then we're going to push into res our current array and i've spread this out to make a copy because we are going to be manipulating current array afterwards then we need to carry out the recursive call so dfs down the left side and the right side and then we need to backtrack and the way we do this is we just pop off of the current r and lastly we return res okay let's check to see if that's worked submit and it you have it
Path Sum II
path-sum-ii
Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_. A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** \[\[5,4,11,2\],\[5,8,4,5\]\] **Explanation:** There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** \[\] **Example 3:** **Input:** root = \[1,2\], targetSum = 0 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Backtracking,Tree,Depth-First Search,Binary Tree
Medium
112,257,437,666,2217
216
hello everyone welcome back here is vamson with another live coding challenge so today uh daily challenge was easy so I decided to do one more so today we will be unraveling the magic behind lead code problem uh combination Su free so it's one of top 70 uh five uh lead code challenges so let's Dive Right In so what this problem is all about we are given two number key and uh n and our task is to find all unique combination of key number that add up to n but here is the catch we can only use number from one through nine and each number can be used at most once so sounds intriguing right so before we brainstorm a solution Let's uh dissect an example so if uh yeah if we have key uh our key will be free and uh yeah n will be nine one possible combination is 1 2 6 so uh yeah sum of those number is nine but uh here is the catch there are other combination too like for example one uh 3 five also s to uh nine and same with two yeah two three four so six n as well so all those number are sum to nine so great uh so now when we understand the task uh let's talk strategy so we can solve this problem using a technique called backtracking essentially we will explore every possible Comm comination but with a few clever uh constraints to make our solution uh efficient as we de into each number we will make a choice to include it or skip it and if at any point our current combination has key number and their sum is n Bingo uh we got a valid combination and we can output it so uh let's dive into coding so uh we will start by defining main function and helper backtracking function and the helper will keep track of our current position and the combination we are building as well and the remaining uh Su we need so uh Define back tracking start puth and tar get Target so uh base case if then pu equal key and Target equal zero result upend list of puff and return four I in range start to 10 numbers 1 through 9 in Pyon so if I greater Target not possible to get a combination and break and recursive call will be as four so back trck I + 1 buff I and Target so back trck I + 1 buff I and Target so back trck I + 1 buff I and Target minus you guessed it minus I so and result will be result and backtrack one to result and return result as simple as this so let's uh run it to see if it's working so yeah uh passed for our test cases um and yeah so that's submitted for un syn cases to double check uh it's working as well so yeah all good and our implementation yeah bit 7% with respect to runtime so yeah bit 7% with respect to runtime so yeah bit 7% with respect to runtime so it's really interesting so previously I implemented exactly uh the same logic and bit 90 something perc so for it will be quite efficient um so yeah probably uh the runtime uh discrepancy so now beating 66% with uh discrepancy so now beating 66% with uh discrepancy so now beating 66% with respect to Rand time so I previously got even 90% uh 33 milliseconds so 33 yeah even 90% uh 33 milliseconds so 33 yeah even 90% uh 33 milliseconds so 33 yeah 33 and 38 is uh yeah 66% so as you can 33 and 38 is uh yeah 66% so as you can 33 and 38 is uh yeah 66% so as you can see same code could produce 33 milliseconds 49 so uh yeah sometimes it's uh good practice so as you can see we H just got three runs 49 then 38 and then uh 40 uh 34 so every time faster and yeah with our backtracking logic in place uh so we initialize our result list and uh backt tracking is processed and uh we have tested so all good and this problem is a beautiful demonstration of how a systematic approach can help navigate the best B of possible combination and if you enjoy uh this uh walk through and yeah uh backtracking uh solution give this video a thumbs up and consider subscribing for more coding adventure and remember it's not just about uh destination but the Journey of problem uh solving so every uh problem you solve uh make you a better programmer so yeah stay motivated happy coding and see you next time
Combination Sum III
combination-sum-iii
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true: * Only numbers `1` through `9` are used. * Each number is used **at most once**. Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order. **Example 1:** **Input:** k = 3, n = 7 **Output:** \[\[1,2,4\]\] **Explanation:** 1 + 2 + 4 = 7 There are no other valid combinations. **Example 2:** **Input:** k = 3, n = 9 **Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\] **Explanation:** 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. **Example 3:** **Input:** k = 4, n = 1 **Output:** \[\] **Explanation:** There are no valid combinations. Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. **Constraints:** * `2 <= k <= 9` * `1 <= n <= 60`
null
Array,Backtracking
Medium
39
867
Ajay soon one my name is Raees and today we are going to call another new questions of garage symbol named transform matrix with determination and crops and right so this question is very easy a bird flu is important because sequence Questions related to this will come forward. It has been placed in Level-2, Questions related to this will come forward. It has been placed in Level-2, Questions related to this will come forward. It has been placed in Level-2, so let us know the questions asked and how one can succeed in it. So look, you will get an anchor and Sam's end dross and skimming matisse. Rate it and transport it. What happens then the according definition is not only in their body maintain good upper triangle of the dial and subscribe to Rai All World Channel electricity take this in a bridge if I say transitions do not happen that then on the flavor board we see that a Women have transport facilities and how can they fix it so if they don't miss it then it's ok, I have secretaries that first of all they believe that the limit is that roads means one square meter spread in square meter, they try to sleep that it is for transport and then they will go. On the regular metal side, we are of graph and type e or call it endorphin, if things mean lamination is tight, then it is understood that I have this meeting in which elements are like this and one does 123 for 132 213 state and induction withdrawal from 012 210 What you have to do is that if you look at this channel, if you think that I have done this, add a little mention to it and think that I will make it its Ravana, I will flip its front, I will make its fruit, oh very. Yes, what is this rotation? You must have read in the Kabaddi special class that such rotations were often done there. Adams used to give Amazon in Atomic. What did they do then? And in Physics too, by showing rotation, bullet action, all this or circulation, heat, this was made. Used to be, I will fill it, test it and do imaging once. Country, if here it is 1123, if I revolve it for this reason, then what will happen, here it will be 11:00, here it will be 222, here it will be of should be 11:00, here it will be 222, here it will be of should be 11:00, here it will be 222, here it will be of should or but this one will go to 80 yes and This one's festival will be like this, right end, this one's three two, here's angry battu, this one's 31st and this team here, write object here, it came here 3rd and this one's 38th, I'm its rights reserved, pray for me, don't pay attention. What will you have to do something such that their hero and column get fried among themselves, this is his, there is a change in the report, but here this is the problem, here Emperor and Dros and Skimming Recent Roshan Mother Bijli Row and Column are different. If it is there then see it must be feeling that it is of some use but let me get the side of referral for once. Look at this problem for once if I am just a mattress, check it here. What is the transfer time bank glass for me but if I Cosmetic is more like medical, if we talk about what Viro 20123 Forces will do, then if I talk about 150 grams, 500 grams, then I had rotated this cord, that's why if you add roti, then think about this partner now. Wife will give two more columns if I get a chronic condition. If I get Shirdi institute done then if you like then I will do my graduation and send it. Will the torch be switched on or will there be cries? Its 572 more columns will go two. Are there only five or so? Roshan Via 572 Row and Column Change and Have Two Se Affair It means to say that if I send same size price encounter is the matter of mission then I can't change the same toe, not you but Shimla's pea will be tight, what is the result of this? If the introduction is asked then 11324 then the app has the problem of understanding this and it also got to know why by preparing the new food because if the food has been prepared here which is far away and in five overs you have to return the new but hence its transfer has to be made. That 205 Ki Ramesh environment will come in it then you will have to create a new WhatsApp right because the time itself is changing time is simple then the result will have to be made Mary so now see I will start making you that will be expressed let's start making new ones see us So we will have to take the values ​​of the past days and what is coming from these years, we will values ​​of the past days and what is coming from these years, we will values ​​of the past days and what is coming from these years, we will keep them soon. Till now I have seen a little change in the value system. Okay, so this is what I am saying, I have just found out what the result should be. Anil will set on that and click on how it is coming. Okay, so electricity, this is the point. This is the point. If I will make element in it, drink the element will have to make a point. Let's marry this with the coordinator. Plus 2. And three four 0 so this is schezwan 181 so f-18 218 schezwan 181 so f-18 218 schezwan 181 so f-18 218 98100 ne 233 laser 4084 218 I want the result so tell me my result so comment it na how is it by the way Prithvi Crush Notes is 45 and the profile is whatever is in the post so all four are made I have been making the end five column 15 column, the problem has been chased since the year, it was made little by little, this one has turmeric, so he arrived frustrated, then this is what happened 0210 340 A little more situation is needed, if this must have happened then this can't be one, if If I do this then its not here 108 102 108 This one is next 108 21 A You see this is written here This is 208 So definitely its route is here which is daily so here the columns are closed and which is the column here The electricity is here vande right so here it is 308 18383 rate at witch complete this here no problem has become okay here similarly s 4084 184 so f-18 truck this similarly s 4084 184 so f-18 truck this similarly s 4084 184 so f-18 truck this rupee has become the previous column front now look once again For this, keep traveling around it and keep controlling it, so I have given 10 elements on R.K. to travel here, when I given 10 elements on R.K. to travel here, when I given 10 elements on R.K. to travel here, when I came here, I have to make the forest famous oil, but remember, the forest got it from this. I have come to know that from here, I am one position limit, keep my hand, stop on this route too, on the matatu, you have fun, role element, go right, go ahead 04043 page, Lokmat Replay, I am forced to do the right thing, all the elements like to, if I end this thing, let me say that What do I mean, clear, you don't have to comment on the result of I Kumar Jai, I should say exams comment or I am matching with metro, you will have to keep the tight matrix of a matter of Vijay Kumar only because here 20 minutes above I am forced to do element. Have you not read it? Look at the right here and there are other changes in Columbus. The one who cries here is the problem. The column is being made here. It is okay, so definitely the comment above was about two rooms. Exams are definitely worth the bill, but where did the phone stop? Tight any moment you see here people will be able to earn that here and have to forgive diner is not guaranteed dial 100 picked up this line police station here many aircraft here this Samsung 2252 went tight like here if about it Yagya was stopped from talking, this was another dinner, could not come all the things Share one here 15152 He is the giver here This is two's one Look here one comment above Which judgment has come on this channel But welcome to, I am targeting this result in 2019. Keep in mind that when the time comes, I will test the earning matter. Yes, yes, for the interview, I will take a little bit of protein. I will make the full screen if you come here to call. I have to make a result, give a result, take out the juice of New Holland, it will be better, otherwise I said ca n't be equal to matrix that dot length and chemical to matrix of Bodoland, so place an order with me now, first to you a tent and see if Send it to you cm and craft end key, then the result you get will be very light, so here we are m craft and here this one, I had this which is every row and this column is light, this is the problem, so what I did carefully here. Do that column cross road, definition of result, from where, what is the mission result, do the column, where the column cross will talk about the popular one, which is the Colombo of the mattress, then you see, repeat has been made, now only pallu has to be applied and AND IF ONE DOES A Starting eye lashes right I went M2 that I am here now first trail is being made Radhe M and I plus for this ullu laga points equal to zero starting from jewelers end because if a we graph end meant first in question now And crops and then e plus result of pi ko maje mein or will I make the result hi ko maje me main matrix off fut matrix off jack ma feel hey look my bus is so urgent kya kar diya pimple tweet hai so if here Par na return type lota plate form of n tha of Tubelight it does kiss okay once Sri Lanka cricket and sequence hello how to run deposit and submit once okay you here we do friend 's vestige basically and And exploit 's vestige basically and And exploit 's vestige basically and And exploit this, Hussain has been inserted in the De Villiers sequence to make a conditioner and now call him. If you liked the video songs time, if you liked the video, then please like this video. Subscribe to the channel and I will give you cigarettes only. In the next question, when we will transfer the end craft end without using any are, okay till then President Brad Ajay
Transpose Matrix
new-21-game
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **Example 2:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\]\] **Output:** \[\[1,4\],\[2,5\],\[3,6\]\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 1000` * `1 <= m * n <= 105` * `-109 <= matrix[i][j] <= 109`
null
Math,Dynamic Programming,Sliding Window,Probability and Statistics
Medium
null
1,903
hey and welcome today we will solve largest odd number in a string interview question this one is simple and quick so let's get into it here's the first example we have a number in a string form in this case 52 and this is an even number but the only odd thing about this number is five here so we might return it again in a string form second example and there's no odd digits within this number so as the question States we might return an empty string in response and the last example which is the entire point to the this question we have a quite big number and we already see a few odd digits in it but the largest number that they form is the given value itself because it ends with seven and obviously it's an odd number so that is what we need to return as answer let's see how we are going to solve this problem let's take the last example and elaborate on it a bit more this question is actually divided into two sections first is finding the odd number or numbers then pick the biggest value out of them so how we can find odd numbers within this string of course you know how it is all about just doing a simple for Loop over this string and as soon as we see an odd digit within that string form we store that number somewhere because you know that the presence of odd digit is enough to convert whatever digits come before it to an odd number and the second step is easy just toss those number into a mass. Max and you have the answer there but wait what are we doing here why are we brute forcing to find the biggest number the problem here is that we are finding the biggest number from left to right and because of that of course we will end up with brute forcing it so instead why are we not iterating from right end of this string value because in that case we are looking for the number by using or biggest odd number detector goggles by default and whatever odd number comes right most as possible is the biggest number it will represent and with that being said let's jump into the code to implement the solution so here we are in lead code let's do ration over given string from end of it so I will be as big as the length of the string and as long as it is larger than equal to zero we will decrement it and within this iteration we need to check if the value is OD how if we take that number and do a modulo by two on it and if the result of it is one then it's an odd number and by the way since we get the number in a string form every digit of it is also going to be string so we need to parse in fact you can also ignore the parts int you will be fine just wanted to hint you that the digit is in string form so if we are in this if case then we know that we have the biggest odd number because we are iterating from end of this string so we will substring it and return it and eventually at the end if we get out of this loop with no result we might return an empty string as problem description says so now if I run this test case are passing and if I submit we are in a good shape here now let's jump into the slid for time and space complexity analysis so the time complexity will be o of n because at Wars case we could get a biggest string that has only an odd digit at the leftmost index and for that we might rrate over the whole string and the space complexity will be all of one constant because simply we did not allocate any space at all so that was it for this video thanks for watching and please leave a like comment and subscribe to the channel I will put a few more links about different playlist in the description for you to check it out and finally hope you enjoyed this video and stay tuned for the next one
Largest Odd Number in String
design-most-recently-used-queue
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** num = "52 " **Output:** "5 " **Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number. **Example 2:** **Input:** num = "4206 " **Output:** " " **Explanation:** There are no odd numbers in "4206 ". **Example 3:** **Input:** num = "35427 " **Output:** "35427 " **Explanation:** "35427 " is already an odd number. **Constraints:** * `1 <= num.length <= 105` * `num` only consists of digits and does not contain any leading zeros.
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
Medium
146
141
hello and welcome everyone let's continue solving the issuan prazad patterns by tackling the list link cycle problem we are giving the head of a linked list and we want to determine if the linked list has a cycle in it and basically we know that um a linked list is supposed to we know that we've gotten to the end of a linked list when detail doesn't point to any other valid node it points to none by the case of a cycle there is not going to be a tail or would have is this endless loop where the linked list points to another node that already exists in our linked list so that is how we determine that indeed there is a cycle and we are just going to give ourselves more room and tackle this problem we will be approaching this problem in two different ways the first is the intuitive approach right using a hash set we use our ash sets to keep the visited the address the visited node basically so we go through the first element we save it in our edge set if it doesn't already exist we go through the second node we store it in our ash set basically i will not be storing the value notes will not be storing the value be storing the node this adjustment we're storing the address to the node not the entire node itself and then we traverse we store our number in our ash set and then we go back and we check because before we store we have to check if this node the address this node already exists in our set and in this case we can see that this address already exists and we're just going to return it through then indeed we have a cycle and this is the most intuitive approach because we know that when we are looking for duplicates or cycles or basically anything that is repetitive in it in a problem our first instinct is to use it sets to keep track of the things we have visited and then we can always check if this current element we are on is an unvisited element if it isn't then we know that okay we are now in a cycle but if it is we are definitely in a cycle this uses um of end time complexity since we are traversing all of the possible items in the um all of the possible given items to find a duplicate and it also uses an extra memory this sets an extra memory and that is o of n space complexity now there is a way we can do this in constant space still linear time or constant space rather using the floyd cycle detection algorithm and this algorithm just basically states that there is a mathematical proof for this in a cycle if there are giving points one is moving faster than the other but they are both moving eventually they are going to meet at the same point that is what the theory is about it's just saying that if there are two points moving one is moving faster than the other eventually they are going to meet if the plane is indeed a cycle if it's not a cycle then they might not meet or if it is a cycle and one is moving faster than the other they are both moving but one is moving faster then eventually because it is a cycle they are going to meet and so we'll be translating that um detection cycle detection algorithm into this code for our own use now we can just check how this works basically so let's say we have a slow a pointer that moves slow and a pointer that moves fast and let us say this takes this slow pointer moves at the pace of it takes one step right it's first steps it lands here but our first pointer it takes two steps unlike the first pointer that takes the slow pointer that takes one step our first pointer takes two steps and it lands here right now they are still moving they're still the same nothing is changing and then our slow pointer goes ahead and take one more step and we can see that this is where the slow pointer lands but record our first pointer this is a different the first loop the slower has gone the second has gone now this loop we want to check if they are moving at the same time now this also moves it takes one step because this is recall that our detection algorithm this is where this is pointing right so when our first pointer takes first step to two this is where it lands and takes the second step to four it eventually the slow pointer and if at any point that they've met we can return that we indeed have a cycle now this is how both works we're going to be coding them both up to just see how it translates to code now the first one i'll be using is we'll be using our cycle using our sets data structure to keep track of visited sets right and while we still have it while there is head we want to check if head is in our set if it says we want to return that indeed we have a cycle if it isn't we want to add the head to our set and we also want to move so we don't get stuck in an infinite loop and we can just return folds if we've come to the end of our linked list and there is no cycle we're going to run this and just to make sure that it works fine and we'll just submit it since this already passes the test cases we can submit this and we see that this actually runs cool now we're going to be using the floyd's detection algorithm to test this and you know that we need two pointers it's slow and the first pointer since they both point at the very beginning of the linked list we can chain them like this in python if your programming language does not allow this then you just assign them differently slow is equals to edge first is equals to edge but we are starting at the same point right now while fast is valid while fast less is because first is going to run when we say that one of our algorithms is going to run faster than the other we've kind of like mentioned that is explicit now that fast is running faster than slow definitely now if fast is null then there is no need we know clearly that slow is going to be null so that is otherwise in fast to check if fast is still valid right then we still want to continue checking that there is indeed a cycle for as long as they've not yet met and this fast is valid we want to check that okay wow fast and well first dot next we want to move our slow pointer by one step and we are moving our first pointer two step side and if at any point slow is equal to fast then we want to return true that we have found a cycle otherwise if this condition is no longer true and we still haven't found the cycle then we know definitely that this is false and we can just submit this to be sure that it works and again we can see that this works i hope this was explanatory it might take a little bit of digging around to really come to terms with how the floyd cycle algorithm detection algorithm works but once you get the angle of it's going to help you with a lot of linked list problem so i think that it's a um understanding how this algorithm works the floyd cycle detection algorithm is a basics for really moving on with your linked list knowledge i'll see you in my next video if this was in any way helpful please subscribe it also support the channel bye
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
41
either and number 41 first we missing positive so give me also generate integer and the smallest missing positive indeed it's a hard question how hard is the question we find them into the fryin integer we can easily sort very first and skinnier time after I found no problem you said you're always a short of running one time constant space so same question with different condition certainly it together it's hard difficulty and after hours of sinking one of these aha moment I can't go sort of solution on this I look at the solution well I applied some research from some discussion I found the solution let's see the example here assuming we have a size every size of sweet and it's kind of sorted elements which are 0 1 2 well the maximum element and so doesn't nothing missing there but if 2 is minus 2 the smallest missing positive number would be so actually the biggest number ray can't contain it must be in the science of the ray so in this case we can say the smallest missing positive integer is going to be to size minus one so the solution here smartly using ray science to determine the possibility of the maximum number another way to understand it is you can sue me if toast element in the array were positive and they should sitting in the position which had a fixed position and for the solution we use example the problem being given 1 to 0 so first we can zero which means T is not in the right position we cannot swap with which the right position so we're gonna move one to one position which especially should be then the two at that position Consuela to zero so we're still at the index 0 now we look at 2 is still not in his right position to his my position and swept 0 so now we see zero position so we moved index to 1.8 his right so we moved index to 1.8 his right so we moved index to 1.8 his right position my choosing is revolution it's not in this case it is a it's kind of using the definition to sort positive number parts is being sorted after that we can adjust the in your skin great isn't it find smallest solution generously shared coding part we have the index from zero and if the tournament is not in the right position and then as well as the element is no equal to a position we can do this well so we're gonna use a template to the car like the car number the entity swept down the signed position otherwise we keep skin and they use another wire loop start from index 0 to find missing teacher which is should be in the right position last one because rate index that marker confirm 18 apply the swap function and apply and submit there you have it the what is it called first machine positive so it is the one of those aha moment and if you have been asked in the interview and you never encounter discussion I will see that example unfortunate and they're wise interview conductor will never ask this kind of question
First Missing Positive
first-missing-positive
Given an unsorted integer array `nums`, return the smallest missing positive integer. You must implement an algorithm that runs in `O(n)` time and uses constant extra space. **Example 1:** **Input:** nums = \[1,2,0\] **Output:** 3 **Explanation:** The numbers in the range \[1,2\] are all in the array. **Example 2:** **Input:** nums = \[3,4,-1,1\] **Output:** 2 **Explanation:** 1 is in the array but 2 is missing. **Example 3:** **Input:** nums = \[7,8,9,11,12\] **Output:** 1 **Explanation:** The smallest positive integer 1 is missing. **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
Array,Hash Table
Hard
268,287,448,770
1,727
hey what's up guys this is chong so to today uh 1727 largest sub matrix with rearrangements and so you're given like a binary matrix which means that there's only the only zero or ones and you're allowed to rearrange the columns of the matrix in any other but you have to rearrange the entire column and you need to return the largest area of submit sub-matrix right and area of submit sub-matrix right and area of submit sub-matrix right and where each element of sub-matrix where each element of sub-matrix where each element of sub-matrix is one and for example right uh this one here so we have if we move these three ones to here then we'll have like the uh the maximum area right it's going to be four so for this one similar right since we can remove move everything into uh all the ones together that's why we have three here and another two and the last one is zero and the constraints is like this right so the total sales right basically m times n is 10 to the power of 5. so it means that it's going to be a either of n solution or unlock and solution so you know with this kind of you know the uh like sub matrix problems you know a common strategy is that we need to pre-process strategy is that we need to pre-process strategy is that we need to pre-process this uh this is this matrix to accumulate it to accumulate some ones at certain location so that we can um so that we can just uh save some time complexity and since for this problem since we can uh move the entire row and sorry the entire columns so it's we should pre-calculate it at so it's we should pre-calculate it at so it's we should pre-calculate it at each of the location here each of the position here how many ones are starting from this one so what i mean is like this so basically you know at this location here so we have two because we have one and a two so here we only have one so the uh basically i'm going to pre-calculate the at each of the pre-calculate the at each of the pre-calculate the at each of the locations how many uh consecutive ones starting from here to the end to the bottom of the right here that's why so for this one it's going to be 1 right so here's 0. so here we have 1 2 and three so that's going to be the common uh strategy to calculate this kind of solve this kind of problem and after having this kind of pre-calculated pre-calculated pre-calculated uh consecutive ones for each of the location then we can uh basically we can just uh loop through we can loop through each of the locations right and then we can try to calculate the area but uh if we're going to calculate the area like within uh by using the like the naive way which means that you know at each of the cells let's say we know the longest uh the longest ones on this on in here so for example we if we have like this one we have let's see at this location here we know the consecutive ones let's say we have three ones uh there's one and one so uh and a naive approach is that you know basically we'll try to expand we try to expand this uh this length to the left and to the right and the way we're doing it that we're doing is we're gonna loop through to the left and then loop through to the right and we'll only look for the uh the what the uh the values right within the same uh row that can have either equal or greater than the current uh count which is three because if there's another three accounts here right another three counts here so we have three here right this is also three here and then the total width will be three by three that's going to be nine right so but if we have like another two here right so if there's another two here so here we have two but two is smaller than three so that's why we cannot uh count those column in yeah and basically that's the most naive way right but as you guys can see that right so for this kind of approach you know the uh the time complexity is going to be a o of uh n cube right so let's say the n is like either length or the width because to loop through every all the cells we need n square and for each of the square we also need to loop through the entire row right that's another end here and this will tle all right so how can we improve that i mean our purpose is what our purpose is trying to find uh find a an efficient way to calculate the error so that we don't have to recalculate uh recalculated the same column over and over so what we can do is like this you know so for each of the row here right so if you guys take a closer look here we can sort the values right on each row by the uh from the biggest to the smallest and why is that because let's say we have three here we have two we have uh two three and two right so if we sort this uh this row from the biggest to smallest we're gonna have like three and then two and two since we can uh rearrange the column freely so which means that we can always try to rearrange the uh rearrange of the columns right to uh with the biggest uh the biggest count to the beginning so that you know the after this one you know the column we can get is like this three two and two so after sorting this one now at each of the locations you know we can all we need to do is that so the array is equal to what so the area is the uh it's going to be the current values going to be the value right times the index which is j plus one you know since we're starting uh in the descending orders so let's say at the current location here right so it means that you know at here at this location the consecutive one is two and but how many other uh columns can have the same have the at least same like consecutive ones it's x is actually the length x no it's actually the length of the current index which is the j plus one because all the numbers be before this index is going to have the either equals or greater than the current consecutive ones that's why we can uh after sorting we can calculate the uh the area in between one time by using this formula right because if i give you an example here so let's say we have uh not this one maybe another one it's gonna be like the uh let's say we have four five and a three right so four five three and a two so if i draw cut draw like a diagram like this so we're gonna have like five four three and two this is like five consecutive ones that's why the uh at each of the locations right the at the rectangle areas it's kind of obvious right so because this is the uh because everything on the left is greater than the current one so that's why the uh with this length with the current lens the biggest uh the current rec the current biggest area with this current uh number as the iso height it's going to be the index that this height for example is 4 times the uh the index plus 1. in this case it's going to be 4 times 2 equals 8 right and same thing for 3 here so it's going to be a 3 times 3 equals to 9. here is like 2 times 4 equals to 8. and we just need to get the biggest value out of all this kind of areas yeah so actually the coding is kind of it's not that long so basically what we need is that we're going to have like matrix have the length of the height of the matrix right and the uh so here i'm going to create like a counts right to store the uh the pre-processed values the pre-processed values the pre-processed values you know actually you can use reuse the same the matrix i guess do a in place updates but i'm just trying i'm just using a new one to make this code a little bit easier to read you know range basically i'm allocating the same size of that right and then to pre-process so for j and then to pre-process so for j and then to pre-process so for j in range of n right because for each of the columns we're going to add up the ones from bottom to top that's why i'm going to do a 4i in range of m minus one yeah i guess you can also do it top down you know i believe you'll get the same result but uh i'm just since i'm using this kind of concept right starting from here until to the bottom that's why uh so we can have the counts at the beginning right so if the matrix of i and j is one right and then we just do this otherwise if it's zero we simply we can simply skip that right which means that it's going to be have zero consecutive ones starting from here so if we if there if it's one then we just uh we will have one at the beginning then if i is smaller than n minus one right and then it will count start i j uh accumulates the counts of i plus one j okay so now we have like a pre-processed okay so now we have like a pre-processed okay so now we have like a pre-processed accounts array here so we can simply uh we can just start uh populating the final answer so which means that we're gonna have like a i in range of m right that's gonna be the rows and we need to sort right the values on each of the row here so um i'm going to have like a sorted count right equals to sorted and counts dot i and then i'm going to sort it in the descending order and for j in range n right answer equals the max of answer dot is going to be sorted count dot j times j plus 1 and then return the answer okay accept it submit okay yeah i mean so in time and space complexity right i mean time complexity is actually so we have like a of uh n square here and here is just uh so it's a it's another of n square yeah because here with stored sword is a unlock oh actually sorry it's not a n square it's a o of n square log n yeah i'm assuming right i'm assuming the uh the n and m they are like equally uh they're kind of uh the same so we have a like uh m here right so let's say this is m right so m times actually the uh so here is actually the log and login to sort right to sort the uh this to sort this count that's why it's going to be a m times n uh log n yeah because this unlock n is greater is a have a bigger big uh time complexity than n here um yeah i think that's it right so i mean so for this kind of matrix sub matrix problem you know it's always a common strategy to pre-process some to pre-process some to pre-process some values uh based on uh each of the locations and since we are so for this problem since we're like uh we can reorder the columns and then it kind of makes sense to uh to pre-process the uh pre-process the uh pre-process the uh the consecutive ones uh i mean vertically and after that so here you need a little bit trick to be able to find a like a an optimal way right to iterate uh all the rectangles to calculate the uh to calculate the area at each of the location uh since we cannot do it uh brutal forcefully like the uh we cannot uh for each of the locations we just either iterate the entire row right that's going to be a too slow that's why we uh let's use one of the common strategy right with this kind of sub matrix problems since the one of the key features for the sub matrix problem is that you know we if we sort the uh the consecutive ones from the biggest to the smallest then at each of the locations here as long as we know the index here right so we can easily get the uh the biggest area right with the current uh consecutive with the current height which is the values the height times the j plus one and yeah and i think that's all it needs to solve this problem cool i think i'll just stop here and thank you for watching this video guys stay tuned see you guys soon bye
Largest Submatrix With Rearrangements
cat-and-mouse-ii
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._ **Example 1:** **Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\] **Output:** 4 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. **Example 2:** **Input:** matrix = \[\[1,0,1,0,1\]\] **Output:** 3 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. **Example 3:** **Input:** matrix = \[\[1,1,0\],\[1,0,1\]\] **Output:** 2 **Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m * n <= 105` * `matrix[i][j]` is either `0` or `1`.
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
805,949
122
is persistent programmer here and welcome to my channel so in this channel we solve a lot of algos and go through a lot of legal questions so if you haven't subscribed already go ahead and hit that subscribe button under this video and let's go ahead and get started today with our question best time to buy and sell stocks too so in this question we're given a input array that looks like this and um if you haven't done the first version of this question i will link it in this video somewhere so you can have a look at that too and so the difference between that question and this question is that we are able to perform multiple transactions um at the same time uh so we can do multiple stock buy and sells but we can't sell a stock um if we sorry we can't buy a stock if we haven't sold the previous stock already so let's look through this example to understand the question um so we're given an array like this and it says that buy on day two so if we buy when it's the lowest tier price one and sell on day three which is where price is five we made a profit of four right and similarly after we have done that transaction then only we can proceed to our next transaction which is to buy and sell again so we buy the stock on day four again which is where price is three and we sell the stock on day five which is where price is six and so we get the total of these two profits that we've made which is four plus three seven so if we look at the graph here um i have plotted out this array exactly and what we can see here is that we make profits when we are going from a lower day to a higher day so here is the case that is written over here where we have the profit of five minus one so we went from a lower day in the previous day to a higher day right and uh similarly here this case six minus three um which is where we had a higher day here and a lower day here okay awesome so let's look at some strategies on how to solve this problem okay awesome so we have visualized the problem here and we can see that um the maximum profits that we can make is when we have a low day and then we sell it at a higher day and then keep selling it if we have a low day yesterday or the previous day and then a higher day the next day so the sum of all these positive deltas is actually what's going to give us um the answer which is seven here right so let's go through this example um to make sense of it more so let's say i take the deltas of everything in this array so remember that we can't um sell something we haven't bought so it's going to be this value the next value minus the previous value so it's one minus seven that's why it's negative six um and then same thing here five minus 1 4 so we can see that this is a positive value right and then we have negative 2 and then we have 3 here so this is again a positive value and we have negative 2 here so basically the idea is that we don't want to accumulate negative values towards our maximum profit because that's not a good strategy to make money when you're selling and buying stocks so what we need to do is add these positive deltas to get us to our final answer now what we can bring from this is we can derive some conditions in our code that we need to check we need to have a way to check if our prices in the next day is higher than the previous day so this is what we're checking right and to convert that to our system code what we need to check is if the current position i'm at is greater than the previous position so i minus 1 is just getting us the previous position so let's say i'm over here at 5. so is 5 greater than 1 yes it is and this is one we need to accumulate and add to our profit so that's the basic idea behind this problem so uh what you need to do is just check this condition and then if this condition meets then we add that to the profit the other case to keep in mind is that if you continuously have a negative delta so there's no way for you to make a profit because you bought the stock on the highest day you need to just return a zero and with our check where we are checking if the price next day is higher um than the previous day it won't even hit this case so we are good with um just uh initializing that profit to zero and then just returning the profit for this case awesome so let's go ahead and dive into the code so what i've done here is i have initialized the profit and we're going to return this profit so i have that at the end and what i'm going to do is create a for loop so um for i in range and our range is going to start from one because we need to go to the previous number so we're going to do we're going to compare that index the price of that index to the previous um index right so we want to start at this position so we can compare the previous index and see if that value is higher and if it is then we're going to accumulate to the profits so you can say land prices and now we're going to have our conditions so if prices i is greater than prices i minus one then in this case what we need to do is we're going to accumulate to the profit so profit is going to be the delta so to find the delta we're simply going to take the day that is higher which is the next day and then minus the previous date from it so we will say profit plus equals prices i minus one okay and that looks good and then what we're going to do is return that profit okay great so let me run this awesome accepted submit yay success
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day. On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**. Find and return _the **maximum** profit you can achieve_. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 7 **Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. **Constraints:** * `1 <= prices.length <= 3 * 104` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming,Greedy
Medium
121,123,188,309,714
1,481
TT Daily Challenge Least Number of Unique Injurers After K Removal and Prob Statement Given A of Injurer and Ijor K F The Least Number of Unique Injurors After Mavi K Element So Statement Prost Forward So What in the Question Asked Us Ek Injur A and We have been given one number and we have to remove all the digits and tell the least number of unique digits that will be left. Okay, so let's see it can be 5 54 A or Elite and after removing the eight, we have to tell the minimum number of digits to minimize the unique number. What can we do for this? We will first remove those elements which have the lowest frequency. It takes less effort to remove them. It is okay. I can do one operation in one operation. I can remove four in one operation. element which is f and in the second test we see one is coming ta ok and two is coming one times th are three times and four are one times and k 3 we can perform three operations i.e. by removing three elements can perform three operations i.e. by removing three elements can perform three operations i.e. by removing three elements Any one is fine. Its minimum frequency is T key and four key i.e. Its minimum frequency is T key and four key i.e. Its minimum frequency is T key and four key i.e. first try to remove either 0 or 4. If both keys are equal then any one of them can be removed first then in one operation I will remove T. I can remove and from one operation, we will have four removed in one operation, now the minimum of T is, we can remove only one F in one operation, right, so still that will be left once, then only what we have left will be saved and And that means we can pass two elements to show the frequency. We can use map maps. Okay, we will get the frequency from that. F will be the frequency. We will put it in an array and mark it with an arrow. So we will get the frequency from minimum frequency to maximum frequency. You will get an array with fancy minimum and maximum times inside it. Try this code. First of all, we will create a map of the frequency of each element. Okay, and will count its fancy. We will create a vector inside which we will take all the frequency noises and map them. And inside that array we will put Fancy K Okay, now let's check what if the frequency lying at the position of frequency is less than k or equal to k then I can reduce it Will count P count Will count the number Element count Number of element count What I can reduce is the unique element that I can reduce, okay, let's define it, count when zero, okay, if this is possible, then the count will count it, okay, and what we will do is complete it. k will b k e k minus frequency k because I have removed so many elements, okay and that and I have returned fancy size, all these elements are as many as we have, these elements are inside this and how many of these can we remove, count from these. You can remove the element, ok, let's run it and see it's happening, submit it's done, thanks for watching the we
Least Number of Unique Integers after K Removals
students-with-invalid-departments
Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.** **Example 1:** **Input:** arr = \[5,5,4\], k = 1 **Output:** 1 **Explanation**: Remove the single 4, only 5 is left. **Example 2:** **Input:** arr = \[4,3,1,1,3,3,2\], k = 3 **Output:** 2 **Explanation**: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left. **Constraints:** * `1 <= arr.length <= 10^5` * `1 <= arr[i] <= 10^9` * `0 <= k <= arr.length`
null
Database
Easy
null
36
Hai Hello Guys Welcome Chala Do Mein Folding Suggestion Problem Solve Problem Different Program By Subscribe Now To Receive New Updates 2012 Idi Do To Ab Kab Due To Be Tu Roads Par At Water Droplets Bluetooth Try to be lit Field Mother Took Place When One End Subscribe 12345 wizard101 Already A Me Pain Cost Effective Wear What Will Happen Hair Oil Add 1062 Flintf 12345 Right One Two Times Can See The Number Two Three Four Completely Normal Number Will Get Blessings And You Can't The Government Has Already 150 This Is Not Allowed Tubelight's Albums Way Through Let Me Not Still Want What's The Number Ten Louis Vuitton Next Cancel Do It I Will Do It Will Clash With Him Too Arrested In The Same For Olympics Strike Not Field Voice World Track Feel Free To Create A Great Feeling Free Dish No Problem And Feeling-3 Requested Not A Single Day Feeling-3 Requested Not A Single Day Feeling-3 Requested Not A Single Day Through It's Not A Single Daily What's Not Playing With Any Of The Box Oil Producer About Cervi Don't Have Any Other Free Sunil Singh OK Knowledge Ko To [ __ ] Free Sunil Singh OK Knowledge Ko To [ __ ] Free Sunil Singh OK Knowledge Ko To [ __ ] Try It feeling-1 It's Problem Try It feeling-1 It's Problem Try It feeling-1 It's Problem Etiquettes Problem Is Bigg Boss Kya Singh Soy Ultrawide Remove Dad Trophy Link Is To Problem Notes20 Cheer Leaders Not Like A Child Playing To The Gallery Entry Feeling-1 Mann Ke Not Misled This Entry Feeling-1 Mann Ke Not Misled This Entry Feeling-1 Mann Ke Not Misled This Problem Addiction Remove Dhawan And Fell Into To Take Off But Last Salary Month Did To Entry Feeling Very Successful Racing Cycle Notes NCERT Book He Feeling For Know What Foods Also Creating Oh My God Tubelight Singh Know What Should Look For A Solution I Will Remove You Point Note Please Do Not Want Know It Means Send's Note Only And It's Default User Can't Feel 1234 Korea The Number Say Right One President * Fennel Korea The Number Say Right One President * Fennel Korea The Number Say Right One President * Fennel Place In Freezer And South East Parliamentary Election And Damage Track Suit With Me Previous Placement Gives Strong Rate Previous Placement Wasif Will Not Right Developed Previously Always Find One Glass Daily And Accepted Pattern In The Previous Placement Gives Strong Saver Mode Start Volume Mute The Previous Placement Of Previously Award Water Have Appeared To Right Selection Raw To Quality Strike One By Well To English Box So in this note correct placement 2012 this I box this problem activities like not valid for all pages in a tumble after to what is a commercial try places are saying they cannot play this world who were traveling for none for its ok and this ok right choice Hogi Sunao Deluxe Bike Again This Time Minute Replacing Manaa Problem So Please Translate Into It's Okay I Don't Have Any Problem Advocate And Plus To That Doping Me Positive For Watching Rebellion Finance And With Uprox Officer Benefit And Wealth Plus To Animals Who Have Surrendered To The next month I expanded boxes and listen to it the right place in this way sing with this is a good place for any place and tourism place in this is not pleasant and replacing 380 300 testing alarm do alarm and column per dedication the box Lighter Note Sir E Listen In This Field That If In This Website Will Have To Three Phase Will Take Place For Indian Festival In This Box In Five Plus To Three Layer Vinod Space For This Plate 1234 Completely In All Box Also Like Sharing Or Place Near So Let's shift ok sorry hokar forest not give any problems lex and go to the most important place in wwe shopping salute oo esports in xbox different in traveling in a good place for kids playing with sons salary movement at right place * can't place to because right place * can't place to because right place * can't place to because feeling Helpless in this regard has no place in this train will go to drops and right place in this problem active and tribes in tourism carat sona agro tourism kuch alag intraoperative those kids stars with adopted kids stars with lots of various government tuk Place in One Place So Every Month Old Play List Ko Bajao Racing Free Leg Not Least One Okay Guy Translation for I Cannot Be Responsible for Scraping in Naseem Columns Election and Typhoid 1234 Everything in This Placement Can Not Hidden Remove The Video then subscribe to the Page if you liked The Video then subscribe to the United Nations Election Words with Translation for It's Not Like the Police Will Go to the Cockroaches Interesting - OK Go to the Cockroaches Interesting - OK Go to the Cockroaches Interesting - OK Sunavai Ko Boxing Contest Ki Setting Male Play Two Countries Residing Place in Freezer Okay No Problem No One in This World Can't Be Placid Into It's Okay No Problem Must Try Number One Two Three Do Subscribe Want to Know the Number Toll Free Number Balance Check Box Button That So That Court Student Will Understand Better in Typing Suggestion Problem of Daily Life Latest to Solve Dab Or Distic Label Function Solve Should Give Like and Share Video Thank you all there is worship First Number to Play the Sun Dot SBI Bank Penis What Will U Will Take And Egg Latest One Android To Do Subscribe Share And Latest Provident Fund Meter I Love You [ You [ You All Subscribe Must Subscribe Channel Simple To Be Ours Is Equal To Daughters Midnight Children and 122 others like this Write below and Share Means The Flight Proof Withdraw Support From Board The Calling Suno Will Destroy This Truth Delegates From Parents Who Deem It Will Break But It Will Be Gone From The Follow Prevented From Twitter Follow There Will See The Flying Instagram Twitter A Noose Hotel For Dogs Who Should Find No Heart Broken Large Event Lemon Juice For Who Will Want To Follow This Will Start Fielder Feeling Value Students Points From The Valley In The Validity Saf Grocery Board Limited Board Of Trustees Anywhere From Want To No Kids Up Last To Days You'll Feel Choked 124 Suzy Refill Up To End Only Water Residues Size Dabbed Then From Doing Shameless Best Suited Solid Late Se Number Of Is Equal To One Number Is Less 121 That Related Person Film etc Spelling Nowhere Near Feeling Values Pages and Notifications This Is Not Presidencies Pay Not Feel That Particular Manner So That They Should Declare Decades of Function Hidden No Heroic Person's Laddu Click on Subscribe Button A Solid Me Gifts Chocolates And When Bheem And Tourist give you letter this character director number to do you want to play a place 1028 convert person subscribe to 2008 value if not subscribed then subscribe is on and here ball election now how to check so subscribe definitely drop the column and milk shake Suggest super then check were checking symptoms of this disease you have number one to three Share It Share It is early in the morning I will remain constant is the current waterfall near Kollam switch off and then board of and sweet oil contact column in change suicide sugar to the calling withdraw its really like share and follow physical long deposit clots opposition in comment box Did provided through all r values ​​in this box in english for values ​​in this box in english for values ​​in this box in english for number chapter 8 so far easier for starting index it 0comments 0 likes him cold to but your notes lucky for all the box is net right and which motherboard so this testing check box office What is the value of water setting 05102 comment box button take off but that in particular and you will be easy for free that now three come in the morning setting value mittu invalid waist 323 and the number you can do you want TO FIND THE VALUE OF THE EAR TO ALL 108 SUICIDE IN ENGLISH LEFT RIGHT NOW LET YOU 5.5.5.5 WITHRON IT'S SUPPORT YOU HAVE TO FIND OUT THE VIEW OF PICROSS PIPE CLICK SUBSCRIBE BUTTON ON THIS SIDE AND WHAT'S THE WHAT DOES NOT WANT TO START FROM THE Video then subscribe to the Page Jhal Flat Se Daru Value Starting At Every Student Item And Defeated Murti Really So What Will Happen In This Particular Case Your Setting More Than 90 Particular Form Plate Se Diet Particular Row Isse Ling High Court Wealth Morning The Want To Meet You Want To Find Out More You Want To Go To Radhe-Radhe Video Shooting Deciding On Radhe-Radhe Video Shooting Deciding On Radhe-Radhe Video Shooting Deciding On Various Subjects Of Holi Festival City 12.5 Auditorium And 505 Tours Secrets 12.5 Auditorium And 505 Tours Secrets 12.5 Auditorium And 505 Tours Secrets From 12562 Which Will Get 1000 Will Get You Answer This Simple Prayer To Go To The starting and what is the role of unmute the same trick and problem solve your setting value can live - live - live - 1 - 12522 will go to the scientific society - mode start point simple you are listening part plus subscribe like and subscribe Do Quad Tried To If This Row And Column Value Special Fear And Starting Column Player Software Will Give Settings Open Amused Servi Naulon Finally Returned To Give Video give a video then subscribe to the Page That Tubewell Insult The Volume Diverse And Events At United States Not let you should particular valid se withdrawal high solve this function and soil has been solved and you can solve wodeyar incentive and passing day reference morning sexual parking board balance first brigade replicated in this world who died and tourism call record public college function and tried To order to gain benefits from already beneficial in the state should be written in to-do list good morning sir kaise lage disease which will break all in the condition when you come MP3 folder sensor field in the case and will not break imagine what will happen And Tours And In The And He Will Be In Jail Bhi Android To Size In The Meeting Is Implementing Will Break Is Situated In The Heart Condition Second Show Is I Is Equal To A Bhauji Killed In The Gifted To Cancel Evidences Rs100 And Choice I Here With Attention Local Variable Is Still Meter Global Variable Its Side Famous Global Variables Dowry At That Time Free Mode Turn On Soul And Spirit Untouched Tourist School Will Return Proven To Be Cursed Toys Return To The Prevention So That Phone Return Grade One Shouldn't Be Written Problem In Kota Ok No In That In Incident To-Do Incident To-Do Incident To-Do List Pinpointed Turning Point Means What If It's Turning Point To Continue Widening Of Course Not Attempted The Board In Case You Can Make A Change In The Value Of Twelve Years And Feel The Love And Returning Vitamin A And Vitamin E Will Make The Valley In M.Com From Today Migration Film Tubelight Number He Again Tried To All The Best Sudhir Web Tracking Of This Country Has Not Less Than Discontent See It's Working Tomorrow Morning Evening Compilation A Lips Servi Ok Kha Lo Research On International Withdrawal Letter Writing that Sudhir weight specified in I for you if internet is rooted in someone then your shoulder Pintu Mandal Lauder SMS on karo hua tha jhal were boys who defined this prescription channel and intriguing relax now specified suicide point but everywhere rail line Indian Airline air cord has been changed so now character elevating dene is 265 plus balance years working nine so some fine but SIM rocketing undefined values ​​pay not getting proper undefined values ​​pay not getting proper undefined values ​​pay not getting proper commissioner dates laddu aap kaise yagya done newly appointed special gym plus two test record tuition The Current System Planets And Then E Again Subscribe Now We Are You To Soldiers And Upon It's Something On Alarm Set Up Date Notification Light
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
209
Hello guys welcome back to tech division in this video you will see minimum sir important problem world record number 2098 from this topic PNB tried to solve ujjain two points and sliding window technique before looking at the problem statement you like to according to courses Which Upcoming And In February Day And Used As A Crash Courses System Design Course To Subscribe Times And The Sunday Indian Times In His Life And Interactive Sessions Court Android Liquid Questions Will Also Provides Resources And Subscribe Interview Or Company Join Course Just For Fun And The Given To Thank You Will Be Made In Just Three Months Ago About The System Design Course They Will Be Coming Machine Coding Networking Fundamentals Communication Protocols Design Algorithms Application Designing And Minute Officer To Switch To Current Available In Starting In Website For Interested To Know More Than You Can Contact From This WhatsApp And You Can Optionally Immune LinkedIn Latest New To Problem Statement In This Problem Giver Positive Energy Systems And Positivity Target Return The Length Of The Country WhatsApp Twitter The Amazing And To The Written 216 Poems In Order To Give To Three One Two Three Element Service Minimum Subscribe Service Subscribe Button Milk To You Can See Responsibility and Secretary Android Plus Two Five Plus One 6 Plus 281 Window 1000 subscribe The Channel and subscribe the Channel Please subscribe and subscribe the Channel Size of all possible windows Size minimum is the number of elements for all elements which will give you a darudo approach for this can be easy to just find all possible service ok khushiyon already how to find all possible service you can just fix starting point servi starting point android 2.2 all a starting point android 2.2 all a starting point android 2.2 all a Point Where You Can Put From 051 You Can Again Stretch Urine Point Thank You Can See December Again You Can Stretch Your Point You Can Create subscribe this Video subscribe The Channel and subscribe the Starting Point - - - 151 - 27 2012 Total Number of Various You Get Is The Sum Of One Plus 2 And To Entertain Any Of Them Into Which Of The Following In This Formulation subscribe to the Page if you liked The Video then subscribe to The Amazing Subscribe Button To That Your Whatever Cancer Multiple Sub 1200 Length With Some Great Think Most Requested To Define Not Look At The Problem Constraints Very Important For Watching The Best All Positive Numbers As Well As The Next Five Years And Not Less For Competition Positive-Positive Number To The Number To Numbers From Left to right the president of do that increasing for monotonic it will never comes down will always be increasing in cases like this is two plus five plus one 600 800th urs the way will always be positive and tours in no problem morning- Subscribe And subscribe The Amazing Equivalent To No Problem The Missions Aapke Subrah Never Received The Systems And You Can Think In Your Logic And Country Planning Sliding Window In All Cases Will Not Work Number Negative Way Will Not Work For Example Will Explain The Number One to the smallest Video then subscribe to the Page if you liked The Video then subscribe to A few servi and sizes not mentioned ok only this dowry and right angle send value only you can take off excise sliding window subscribe do n't forget to subscribe the channel And Subscribe Button And Plus Size 2.1 A Phone Number One Is Obscene Writing Se Zameen 2.1 A Phone Number One Is Obscene Writing Se Zameen 2.1 A Phone Number One Is Obscene Writing Se Zameen Label Issue Ride Point To Write Deposit Will Be Strictly Increasing Cover Is All The Number Positive Thinking Key For Adding The Numbers I Sambhal Ki For Increasing Four Cons Definitive Number Three Will Bay Added To For Nine Zinc Vitamin For Businesses 675 98100 Stop This Point Window 8.1 But Not Only You Want To Indore Reminder Perfectly Valid Window Development Volume Minimum Window Size Center Point Compliant From Left Side Click A Subscribe Button Here To The Journey to the The Rise Again I This Front Window Is Great Think They Should Forget and You Are Not Wrong Doors Correct Body Can We Have a Small Window Size in the Video then subscribe to the Page if you liked The Video subscribe 1230 subscribe moving to keep moving right to the right other even comes great dainik target sambhog dainik bhaskar dainik da subscribe and subscribe the Video then subscribe to the Page Aaj Hum In Whenever You Post On The Idea Of Good Degrees Absolute Minimum Value Solve Video Less Than 10 Value Falls Against Target Units Window Will Be Taken With Just A Small Window - Verb - 12345 Want To Be Effective For Cancer Minus Plus To The Monk Target Samudra Left Point Again To Right And As Soon As You Reach The Earth Will Be Separated Swayam Williams Turn Off Window System OK And Slide Left To The Point To Steel R Previous Point Someone Having Na Dhi 10 Sudhir Va What is the number of elements of minus plus to the total number of elements for window and find the value of minimum Latest Driver Subscribe Now to the payment breeds tenth is The Target Will Keep Moving Cars 521 Video then subscribe to the Video then subscribe to subscribe and subscribe the Subscribe and See How Many Ride Points to the Person Subscribe to 108 Miss World All this element will be included for in the previous element will Also Be Included Records They Have Worshiped By 1.2 Right And Records They Have Worshiped By 1.2 Right And Records They Have Worshiped By 1.2 Right And Decided To Shift From This 223 Length subscribe to the Page if you liked The Video then subscribe to the minus plus one is the current window subscribe minus one to plus two take away subscribe to business Want to find the minimum withdrawal of soil salinity maximum value in this will be compared with the window size four with 3 minus one plus two UV ₹400 Updater Ko ₹400 Updater Ko ₹400 Updater Ko Maximum Solving Problems liked The Video then subscribe to the Page if you liked The Video then subscribe to subscribe our quick direction princess elements of doing today along with the previous element has to be included as well as will be destroyed the basis of winter services 430 minus plus 2 ok so you two for managers 123 9000 side latest that Bigg Boss Subscribe Our Position Subscribe Target Will Stop This Point To Subscribe 9699 Subscribe Hansu Targets You Keep Moving And Left Or Right To Have Left Right Left And Right The Same Position And Going To Remove With The Wind To Rear Minus Plus 1.525 1.525 1.525 Video subscribe please subscribe and subscribe the Video then subscribe to the Page In the condition of Shravan Abhishek this letter is daily and target is rich they tried to compress from left side with compressed air compressor Video Subscribe Minus Plus to Front Part Plus to 9 Organization President Will Be Updated Soon They Will Not Mean That You Are Getting Married With Time Complexity After Thank You Are Able To Understand In Next Video I Will Explain If The Negative Numbers Also Given Here You Can Not Apply For The Video Want To Join Course And System Design Course You Can Contact Person Whatsapp Like This Video Share And Subscribe Our Channel Thank You
Minimum Size Subarray Sum
minimum-size-subarray-sum
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead. **Example 1:** **Input:** target = 7, nums = \[2,3,1,2,4,3\] **Output:** 2 **Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint. **Example 2:** **Input:** target = 4, nums = \[1,4,4\] **Output:** 1 **Example 3:** **Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= target <= 109` * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104` **Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
null
Array,Binary Search,Sliding Window,Prefix Sum
Medium
76,325,718,1776,2211,2329
140
hey guys how's it going in this video i'm going to go through this the code number 140 word break number two so uh this question was asked by um facebook amazon google bloomberg and other and also microsoft uber and adobe so uh this problem we are giving a string of s and the dictionary of strings word dick and as basis in this to construct a sentence where each word is a valid uh dictionary word between all such possible sentences in any so let's take a look at the example in here um the string that we are giving is cat and dog so cat so the output should be a cat and dog that's one possible output another one is a cat sand dog as you can see so we basically sliced the string the given string such that each individual word is can be found in the vertic so we slice this way cat which is this word over here that's in dictionary and also in dictionary the dog is also in the dictionary same thing for this guy we slice it in cat sand and the dog so basically uh the way that i approached this problem was the use of recursion as you can see um we can basically scan through this string for example we uh scan through the first basically for example the first three character and then we've found that it can be found over here it's matching over here and then we scan to the four first four character which can be found in here as well and then let's say after we scan the after scanning the first character and then this one will be the remaining part of the string that can be performed recursively basically we scan the first four character of the remaining after that we just we scanning the first three character of the remaining and same thing when we do cats and we can scan to um uh this substring and then basically we can look at the first three character after that we cut it off and then we look at the first three character in this case but we cannot scan the four first four characteristics have only three character in this case so uh so this idea let's look at the implementation we first have uh the length where map and uh thus we use a default deck that's a set so basically the key on the length and the value of the word in the dictionary and then we look at the minimum length so basically that's the length of the shortest word in the dictionary and then what we do is to uh fill up this a word other length where's map let me show you what it is so again so the key is the length and the value is a set that is containing all the uh the word in the dictionary that is correspond to the deadlines for example um length of three so we have end dog and cat all of them has a length of three so after that we are good to implement a recursive uh which we will recursively call this function if the given string i call the a string is already equal to empty string and then that means we are done so same as all the other recursive function um the first one the first thing we have to do is to figure out the termination condition and if we hit that we just append it to the result by decomposing the list converted to a string append to the result and also if the length of the given string is less than the minimum length that's why we have to look at the minimum length the length of the shortage of word if the given length is already left smaller than the length of events the meaning the length of the shortest word we are done as well so we don't have to do the rest and for the length in the length worse map so basically in this case the word length could be three and could be four and we look at the substring of the given string if that is matching one of the words in the set that means so basically the scanning right so for example the first word length will be three and then we look at the first three character of the substring which is cat to look it up to see if that's in the set in this case yes so we copy a call we copy a copy of the given list we call b list and then append um the word that we just we found it in the set we append it to it and then we put the b list to be input argument for the next recursion and then after that we do the next length which is four in this case so we basically scan to the first three and in the first four and then we recursively calling remaining to trigger running we input the first string also empty list to start with and the result i said i put it as a set so we can avoid the duplicate and then at the end when i convert it back to a list let's submit it after me this is not the most efficient solution as you can see it's not very efficient as compared to other submissions and one potential improvement will be that we can implement a dynamic programming instead of like a purely recursion as you can see a lot of repeating work being done in here i'll leave it as your exercise to you basically we can improve implement a memorization either a list or a dictionary to keep track of the intermediate step that we have done so we don't repeat our work so that would be a lot more efficient so this is my solution hopefully this gives you a starting point to optimize the solution for this problem if this is helpful please like and subscribe right that will be a huge support and i will see you next video thank you for so much for watching
Word Break II
word-break-ii
Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "catsanddog ", wordDict = \[ "cat ", "cats ", "and ", "sand ", "dog "\] **Output:** \[ "cats and dog ", "cat sand dog "\] **Example 2:** **Input:** s = "pineapplepenapple ", wordDict = \[ "apple ", "pen ", "applepen ", "pine ", "pineapple "\] **Output:** \[ "pine apple pen apple ", "pineapple pen apple ", "pine applepen apple "\] **Explanation:** Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** \[\] **Constraints:** * `1 <= s.length <= 20` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 10` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**. * Input is generated in a way that the length of the answer doesn't exceed 105.
null
Hash Table,String,Dynamic Programming,Backtracking,Trie,Memoization
Hard
139,472
1,958
hey everyone welcome back and let's write some more neat code today so today let's solve the problem check mo check if move is legal and this is a problem from this morning's leak code contest so let's get into it and if you would like to see a solution from this knights sleep code contest subscribe and stay tuned for more i promise this time i'll stop being lazy and actually solve those problems so let's get into it we are given a zero index eight by eight grid board but the dimensions actually aren't too important in this problem but each board cell could have three potential values it could be an empty cell or it could be the color white or it could be the color black so three possible values and our job is we are given a single move and we just want to determine is that move legal now how do you know if a move is legal only if changing that cell the one cell that we're changing if it happens to be that it causes the basically this cell is part of the endpoint of a good line now what exactly is a good line well let's read the next paragraph a good line is a line of three or more cells including the endpoints where the end points of the line are one color and every other cell in between these two end points is the opposite color so they can't be empty none of these cells in this line can be empty so these are some examples of some good lines so these four are examples of good lines this is not a good line why is this a good line well it has three cells right we need three or more cells so it has three or more cells the end points of this line are white right the two endpoints the you know the end points basically i think it's obvious they're white the every other cell in between those endpoints is black right so that's a good line this is a good line as well the end points of this are black every other cell in between is white and this has four cells that's three or more cells so that counts as well why is this not a good line well it has five cells that's good but the end points are opposite colors right this is white this is black that can't be the case so this is not a good line now it can't just be in four directions right up down left and right those are four directions but we can also have diagonal lines right so this these diagonal lines are also good lines so i think the general understanding of this problem it takes a little while to get but once you get it's pretty straightforward but the question is how can you actually implement this into code and that's what i'm going to be showing you right now so let's take a look at an example and then i think the solution will become pretty straightforward so let's take a look at this grid the blue stuff are just empty cells we have some white cells and we have some black cells we are given this move that we want to complete stated right here so in row 4 column 3 so this is row 4 and the column three is gonna be right over here and what we wanna do is just change the color to black right you can see right now the color is blue but we wanna change it to black so let's change that to black right now so now we want to know the question is this point that we just added is it the end point of a good line we're not just asking is this point a is it a part of a good line that's not the question we're asking is this the end point of a good line so how are we gonna check if it's the end point of a good line well that comes into the directions that we can search right remember what i said at the beginning it's not just four directions but it could be diagonal as well so technically we have to go in eight different directions right suppose this was the end point of a line such as this one right it would this would be the end point at the bottom position so in that case we have to search up right we have to search up to see that if this is the end point okay so we know that this is black we're going to keep searching up and see if we can find a good line that goes in that direction we can also search to the right it could possibly be a good endpoint of a good line in this position or like this or even diagonally right we have to check eight different directions now what's going to be the time complexity well if we search in eight different directions we're not going to be revisiting the same cell twice probably so the overall time complexity is going to be you know something like proportional to the size of the grid but it's an eight by eight grid so the technical time complexity i think is o of one but if you extend this problem to a generic case it could be considered o of n as well so let's just take it one single example line so suppose we started here right this is where we changed this to black right something like over here and then we want to know okay searching to the right is this the end point of a good line well we're gonna go at the next possible cell right the next possible cell has to be a different color than this one right so the fact that this is a white is good for us right because if it was a black that would mean that we'd have two blacks right next to each other that's definitely not a good line right so then we go to the next cell it's also white so we continue and then we get to a black any time we get to the same color that we started at over here that means we're done right because we know that the end points have to be the same color so these two are the end points and everything in between happened to be white so that's good the length of this is 4 right so we did find a sufficiently you know good line or whatever these two are endpoints of that good line now if we ever reached while we were searching right we know we stop as soon as we get to a black if we ever reached an empty cell in between we got to our first black that would mean we did not have a good line and in that case we'd have to return false we did not find a good line so this is the general overview now let me get into the code it's actually not as hard to write as you would expect so let's get into that okay so now let's jump into the code you can see i already wrote a little bit of boilerplate so what i did first is i took the dimensions of the board so the number of rows and the number of columns but i guess now that i realize it's just eight let's just leave this as it is because i'm lazy but uh the directions the reason i have this array is basically so that we can kind of automate and this is the kind of key part of this algorithm to at least not have to you know write a ton of code so if we have we know that we have eight directions that we're going to be searching in right so basically i just wrote the you know change in direction so if we wanted to search in one direction uh this would be that direction basically this first call this first row here is the four directions right left right up down this next row are the diagonal dimensions right like something like top right bottom left etc right so what we want to do is we want to search all eight directions but we don't want to have to write the code eight different times so let's write a helper function legal to check if starting at this position row column uh and changing the color to this particular color change and going into this particular direction we have one of eight directions to choose from and we want to know did is that a legal move if any of the eight directions creates a legal move right then we return true but if none of them does then we have to return false and one other thing so you can see in the input we are given the row column and we're given the color so let's just go ahead and do that like let's change this position to this particular color that we were given so next let's finish up this helper function so we were given a direction right that represents a chain a dr dc what i mean by dr and dc is the direction that we're going to go in the row direction and the direction in the column direction basically that the difference or the change in row and the change in column so those are what we're given and we can actually make that update right now so we're gonna basically say okay this is the starting position row column and we're gonna update just once so we're gonna say row plus dr and column plus dc so far uh we're gonna say our length is one of our line so far so you can see that we incremented once already so we skipped the first position because we already know what color it is that was given in the input we just changed it so we have a length we have a line of length one so far so now we want to keep going while we are still in bounds of the grid so how do we check if we're in bounds well the good thing in python is it's a little bit easier than i think some other languages so we can do it with a single inequality to check that the row is inbound so we want to know that the row is greater than or equal to zero and it has to be less than the number of rows which i think is eight but i have a variable for that anyway so let's continue and we want to make sure that the column is in bounds so we can do that with a single inequality in python which is pretty convenient if you ask me uh that's it so we're checking we're making sure that we're inbound so as long as we're in bounds what do we want to know well if we're in bounds we can go ahead and increment our length by one that means we found another position that is inbound so let's increment the length by one but so now what now okay we got to a new position in the board right but what color is it or maybe it's not even any color if it's not any color at all we know that because we can check that the row column is equal to a dot right that's what represents empty in our k so if it's equal to a dot what did we say happens if we get to an empty cell well that means we kind of just broke our line right we found an invalid position right that's not a good line right we found an invalid position before we found the two endpoints that we were looking for so what are we gonna have to do in this case we're simply gonna return false right so we can do that over here and the other thing is the other uh end case basically what i mentioned is if we find the original color that we started at right how do we know if we found the original color that we started at well uh similarly in this case we can check the position that we're currently at row column if it's equal to what if it's equal to the original color right that was what was given to us with a variable right the original color and where the first position we skipped right when we started at the first position row column then we incremented it by once so this is not necessarily going to execute you know on the first iteration of the loop right so because we skipped the first cell so if we find the same color again that's when we stop now it could be that just because we found the same color doesn't mean this is a good line it could be a good line or it could be you're not a good line how do we know if it's a good line well it has to be at least length three so let's return true if this is greater than or equal to 3 if it's less than or equal to 3 then we return false so we can do that with an inequality like this we'll just return the result of this inequality now we checked the case if it was empty we checked the case if it was the same color what if it's a different color well we don't really have to do anything in that case right because if we start with a black for example right we start with a black then we get to a white like we could go on go like this forever it doesn't matter any whites are just basically ignored if we started with a black and then once we get back to the end point right we get to another black that's when we reach the same one that we started with at the beginning and then we'll basically check this inequality is the length of the entire thing greater than or equal to three yes it is we return true right or maybe we never saw any whites at all maybe we just got a starting black and then we got an ending black what are we gonna do in that case we're gonna say okay the length is not greater than or equal to three we return false so that's the basic logic in this case now every iteration of the loop we do have to update our row and column positions moving them in the direction that we specified so we'll say row plus dr column plus d column and so this is like our terminal case but if we exit the entire loop and we never found a good line then we have to return false in this case right so now we have our entire helper function it's not quite as hard as you would have thought maybe it's definitely some a solid amount of code maybe some people know how to shorten this up i look forward to seeing how you guys can do that but this kind of direction really is what makes this problem simple for us because now all we have to do is just go through for d in direction the eight different directions we have we just have to go through each and then call our helper function legal passing in the starting row position starting column which was given to us as input parameters row move column move and the color that we're changing it to color and last but not least the particular direction we're going in with which is just d in this case right so that this is how we're going to call the helper function we're going to do eight times one for each direction if we ever return true like even a single time if this is true then we can return true in the entire function but if it never returns true then the loop will exit and then we'll have to return false out here and as you can see this is the entire code and you can see that i just ran it and it just gave me accepted on the contest so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and check out my patreon if you would like to further support the channel link will be in the description and i'll hopefully see you pretty soon thanks for watching
Check if Move is Legal
ad-free-sessions
You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`. Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only **legal** if, after changing it, the cell becomes the **endpoint of a good line** (horizontal, vertical, or diagonal). A **good line** is a line of **three or more cells (including the endpoints)** where the endpoints of the line are **one color**, and the remaining cells in the middle are the **opposite color** (no cells in the line are free). You can find examples for good lines in the figure below: Given two integers `rMove` and `cMove` and a character `color` representing the color you are playing as (white or black), return `true` _if changing cell_ `(rMove, cMove)` _to color_ `color` _is a **legal** move, or_ `false` _if it is not legal_. **Example 1:** **Input:** board = \[\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ "W ", "B ", "B ", ". ", "W ", "W ", "W ", "B "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\]\], rMove = 4, cMove = 3, color = "B " **Output:** true **Explanation:** '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'. The two good lines with the chosen cell as an endpoint are annotated above with the red rectangles. **Example 2:** **Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "B ", ". ", ". ", "W ", ". ", ". ", ". "\],\[ ". ", ". ", "W ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", "B ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", "B ", "W ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", "W ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", "B "\]\], rMove = 4, cMove = 4, color = "W " **Output:** false **Explanation:** While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint. **Constraints:** * `board.length == board[r].length == 8` * `0 <= rMove, cMove < 8` * `board[rMove][cMove] == '.'` * `color` is either `'B'` or `'W'`.
null
Database
Easy
null
130
hello everyone welcome to day first of november eco challenge and it's the new month a new beginning and i hope as for the last six months we are able to continue the consistency for the next six months as well we are able to get the november lead code monthly challenge badge as well without much to do let's look at the today's question is rounded regions here we are given a matrix size m cross n and each cell on the matrix can either be a x or an o we need to capture all the regions that are four directionally surrounded by x so without much to do let's try and understand the question by the presentation that i have created for this so moving on to the bbt i'll be explaining the question as well as the solution there and then itself it's a medium level question on lead code and i somewhat also feel the same there is a small trick that is associated in the question if you know the trick you will be able to come up with an optimized approach surrounded regions lead code 130 so let's take the same example that was specified in the question we are given a matrix of x and zeros we need to toggle those regions that are four directionally surrounded by x so let's try and look at both the islands that are specified here in yellow so let's draw the boundaries of these islands so these are the two boundary coordinates this is another boundary coordinate this is another body boundary coordinate remember that this is not a boundary coordinate because this is diagonal to o so diagonal elements are not considered as boundary coordinates now what do we observe that this complete island is surrounded by x in all the four directions so here we have x now for such islands we need to update the value to x itself so this gets updated to x now let's look at the other case the other island that we have and let me just change the color of pen let's take blue what are the boundary coordinates of this particular island there are three such possibilities one is this the other one is this and the third one is this we can see that in the three directions it is surrounded by x and in the fourth direction it's the boundary of the cell so we can't do anything we cannot say that this particular island is surrounded by x in all the four directions that means we don't need to update this to x we have to maintain the current cell value of this particular island so now comes the approach how are we going to solve this up the first and the foremost knife approach that comes to everybody's mind is to iterate through the island and as you vibrate through the island you keep on checking the boundaries of the island if uh the boundary of the island is not in touch with the outer boundary of the complete grid we update the cell to x for example uh let's walk through this if this is not in touch with the outer boundary we update it to x as you progress down the complete island however as soon as you witness that your cell is in touch with the boundary of the matrix uh let's hypothetically assume you had an o here as well so this o is in touch with the boundary of the matrix what do you need to revert and toggle the complete process that you did you need to update all these x back to 0 because in those cases you are not allowed to update the value of 0 to x because this particular cell is in touch with the boundary of the complete matrix so how do we solve this problem to understand it better let's take a slightly different example here there are again two islands one is this one where i can i have highlighted zeros and the other one is this one so let's try and identify which one will be actually toggled to x this particular island is in touch with the boundary of the complete matrix this won't be toggled and however this particular island that i'm highlighting right now will be toggled to x because you can see that it's it is all surrounded by x on its boundaries i think this is fair enough so far we are good so how do we approach the problem instead of identifying those islands which will be toggled to x what do we think in the reverse direction we'll try to search for those islands which won't be toggled for example we know that all the cells that start from the first row or the first column or the last row or the last column are not bound to be toggled so we go and do a dfs operation on each cell of this complete matrix that i have highlighted on the boundary if the cell value starts with an o on these four boundaries then we perform a dfs operation and we iterate through the complete island starting from those o's what do we update the values to some other character let's say v so we saw and over here we start the dfs operation when we update all the elements that exist in this island to v now we know that all the islands that lie on the boundaries have been updated to v what do we do the next step is to update all those values that exist in the matrix where the value is o so we go and update all those o's to x because we know that we have updated all the islands that started with an o in the initial state to v that are in touch with the boundary of the complete matrix whatever remains are the insiders so we update we go and update these cells to x and once we are done with this we reiterate the complete matrix and update all the cells that exist with the v in the matrix back to o so it's a three-step process it's a three-step process it's a three-step process the for in the first step we update all the cells to v that lie in the start with the boundary of the matrix and then we go and update all the cells that lie with an o in the matrix to x and in the final step we update all these back to o because the initial state of all these was o itself so this becomes the final state of the matrix we can say that all have been updated to x and whatever should have remained as i know it still holds the value o which is highlighted in green right now i hope this approach is clear to you uh the time complexity of this approach is pretty simple and straightforward is the order of n square and let's see how i have written the code for it as a basic under default case of the iteration i have created a private class point that stores x and y coordinates of my cell then i go and ahead and check if my length of the board is zero or the number of columns that i have is zero i simply abort the process then and there itself otherwise i'll go and extract those values in two variables n m i trades with the first column if my cell in the first column happens to be an o i perform the dfs operation on that column so let's see the dfs operation it's a simple helper method that is iterating and updating the board values to b in all the four directions once i am done with this i iterate in the last column first row and then last row i have walked through all the boundaries of the matrix and now whatever os remains in the matrix should be updated to x this is what i have done here and once i'm done with the step two i go and update all the v's back towards because these word was an intermediary state ideally it should not have been updated as per the question and we go and update it back to o in the end we are done with algo and let's submit this up one millisecond 99.82 percent faster one millisecond 99.82 percent faster one millisecond 99.82 percent faster which is pretty good this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye
Surrounded Regions
surrounded-regions
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`. A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region. **Example 1:** **Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Explanation:** Notice that an 'O' should not be flipped if: - It is on the border, or - It is adjacent to an 'O' that should not be flipped. The bottom 'O' is on the border, so it is not flipped. The other three 'O' form a surrounded region, so they are flipped. **Example 2:** **Input:** board = \[\[ "X "\]\] **Output:** \[\[ "X "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is `'X'` or `'O'`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
200,286
1,317
hello so doing this lift code contest 171 that was yesterday so the first problem was of the contest with this problem 1317 converged integer to the sum of two nonzero integers so the problem says given an integer n we have something called non zero no zero integer which is just a positive number that doesn't contain any zero digit like any digit zero in its decimal representation and so when I return any two numbers a and B such that both that are not know zero integers which means they don't contain zero any zero digit or digit zero itself and then their sum is equal to a and we are guaranteed that there is a solution so for n equal to 2 we can just say 1 and 1 both don't contain any zero and so we return to 11:29 their sum is 11 and they don't 11:29 their sum is 11 and they don't 11:29 their sum is 11 and they don't contain zeros so what's the outcomes of this problem so you can see n can be up here to 10 to the power 4 which tells us that an oven algorithm would work fine so this is prescribed for a solution right we can just go through n go through from 0 to n or from 1 to n because we know 0 contains 0 right and then just find two numbers that don't contain 0 essentially just literally a translation of the problem and so here we need to go from 1 to N and then we check that so if for I and another number to be equal to n the number has to be n minus I right so we just check I and n minus I and make sure that they don't contain 0 these numbers don't contain 0 so to check that in Python you can just check 0 it's not in the string representation of I right because let's say we have 102 right as a number we just converts it to a string and make sure that there is not 0 in it but here it would be in it and then we return false otherwise if it was 3 0 not there so return true so we check that and for the other number which is for them to be equal to their sum to be equal to n it has to be n minus I so we check also that 0 is not in n minus i right and then we need to convert it also to string to be able to check that and then at the end if you find the first two that we find that verify this criteria which is returned them so I and in mine side very straightforward and this the time complexity for this is oven space complexities of one right so if I submit this it passes the test cases so now since this is an easy problem we'll just try to do it in different ways right so well here we are doing not in 0 not in two times which is kind of not really good so we can just take the concatenation of the two and check if 0 is in there right because if there is zeroing of any one of them coca tonic intimate checking that zero is there we'll find it right and so you just make that in one not repeat this 0 not in part so shouldn't have this okay so it still passes now another way we could do this string thing here so Python has this format function where we could say the first put the first thing here in this zero and put the second thing here in this one right and then format ply format and just say so if I just show you in Python what the format function does so format function here if I give it let's say 0 &amp; function here if I give it let's say 0 &amp; function here if I give it let's say 0 &amp; 1 so I need to just keep it the arguments to place 0 &amp; 1 with so I could arguments to place 0 &amp; 1 with so I could arguments to place 0 &amp; 1 with so I could give it like let's say character a in character B it should give me a B if I say this is maybe a this is B to give me B a right so we just put the first argument in the zero position the second argument in the one and so here we want well any order is fine since what we are interested in is just that 0 is there so you could just say I and n - I these are you could just say I and n - I these are you could just say I and n - I these are the two arguments and that's pretty much it submit okay so that versus the other thing is actually it's madness since here we don't care actually about the order also and could just by definition it will put the first one here the second one here so you could also do that so that's so passes the other thing also is that python has this much nice thing that can you can do instead of using format function it could just put F before the string and then just put your string as it is so whatever you we were putting a format here or put inside it and it will kind of replace the value of it instead so we could just remove this and this will do the same thing except we need to use a single quote and this will work in the exact same way as the format function we did before so same thing goes like this so it will just replace with the values let's go this a little bit just love just while this is running the other way we can write this is so this for loop we can write it as a list comprehension so it passes let's submit so we could write it as a list comprehension which means for let's call this I here so we could just say if put the if in the list comprehension part like this and what we want is I and n minus I so just for loop instead of writing it in this way you could write it as a list comprehension and then just say we want the next one which means the first one out of this iterator and so if you look here in pythons so what next does is from an iterator it will just give you so if I give it the range of one the range of five it will give me the first one so it will give me zero so the range is not an iterator most give it may be something like this so any character so let's say I for I in range oh five so it should give me the first one which is zero if I do two here and twelve take me to the first one so it just gives the first thing in the decorator and that's what we want the first thing that has that matches this continually these this condition this if in this range we want to get that and so we could just replace this entire thing with this one liner and that will give us the exact same thing so this the previous one pass it okay I made a mistake here so n I and n - I for I in that range if I didn't - I for I in that range if I didn't - I for I in that range if I didn't return its I forgot to return okay so it passes yeah so that's those are just different ways you could do this problem yeah so that's it for this thanks for watching and if you liked this video please press the like and subscribe thank you and bye
Convert Integer to the Sum of Two No-Zero Integers
monthly-transactions-i
**No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation. Given an integer `n`, return _a list of two integers_ `[a, b]` _where_: * `a` and `b` are **No-Zero integers**. * `a + b = n` The test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them. **Example 1:** **Input:** n = 2 **Output:** \[1,1\] **Explanation:** Let a = 1 and b = 1. Both a and b are no-zero integers, and a + b = 2 = n. **Example 2:** **Input:** n = 11 **Output:** \[2,9\] **Explanation:** Let a = 2 and b = 9. Both a and b are no-zero integers, and a + b = 9 = n. Note that there are other valid answers as \[8, 3\] that can be accepted. **Constraints:** * `2 <= n <= 104`
null
Database
Medium
1328
310
hey everybody this is larry this is day four of the november daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm or just in general uh and today's problem is minimum height trees okay so what is this a tree is a okay i know what a tree is okay those are the minimum height as a minimum high tree okay so then you can take any edge um you can return the answer in any order we turn a list of all of the labels okay um okay let me think about this for a second um i mean i think so the thing to notice is that you know on the longest path on a tree it's going to be something that's um well the first thing to know is that uh you know you could do an n square but n in this case is 2 times 10 to the fourth so 10 squared is going to be too slow it is a tree though but uh and the second thing to note is that it's going to be on the longest path given the longest path you take the middle node or the middle two nodes and that would be and those two notes should be good enough so there should be at most two notes to the answer uh because yeah because it's a tree so you know so it can be um so that's the answer have to think about how to implement that correctly so finding the longest path in the tree which is also known as the diameter of a tree that's kind of uh a solved problem you basically um and if you don't know it don't feel too bad because it's kind of like i don't know it's just really hard to plant proof by yourself i mean maybe it makes sense but i don't know it's just something that over time you pick it up um and because it's a nonish problem maybe not well known but known enough so if you don't know it don't feel that bad but you know uh it's called the diameter of a tree and you can deal with two that first search um you just do a different search from any node and then you do a second default search from the farthest node and then that longest path will be it um yes i think i'm just gonna do that um i have to kind of do double check some math to make sure that it's good i might have to play around some edge cases but i think the idea is around that um so first let's just say you know we have a definite search we have a node we have a parent uh this is how i write my tree based depth research i also write maybe how i want to do it let's just say distance is equal to um infinity times n uh let's just do this and then what is edges it's just an edgeless right okay wait oh no these are just edges so i do so i want to put it into an edge list this is literally a list of edge i want to put in adjacency list is what i mean um so let's just say adjacency this is you go to collections dot default deck of list and then for uv in edges uh adjacency list of u is equal to append of we and also the same going data with direction uh now i have that for search we want for i guess neighbor but for we in adjacency list of node if read is not parent then we do a definite search on we with notice the parent right something like that but we have to kind of figure out how to do the distance so that's basically it um yeah okay so let's just do distance oh we are at the distance but let's put it closer to the code um so let's call it current distance maybe so distance of node is equal to current distance and this is just current distance plus one right and now we get the for this node so um so max of distance so for this distance as you go to this thing uh well after we could we can use it on any node so we're just gonna write zero as far as distance and then we get the farthest notes so far this node is equal to um x in for x into the uh let's just to enumerate index x and we just want the index for which um if x is equal to furthest distance right and we basically we want this to a list and then the first element they should always have one element um and then we do it again from the furthest note through the snow negative one zero and again we set distance equal to infinity times n so we do this thing um we want to keep the furthest distance because it should oh no we don't um so we do this thing and then now we are so each candidate will be uh the furthest distance over two notes away right so uh if yeah i mean that's right but i feel like that may still be a little bit messy so let me think about this for a second uh because we still have to narrow it down a little bit right because there could be many uh entries with photos notes but not all of them will be rooted in a tree um i think it has to be on the path to the distance so so huh i mean there are a couple of ways to do it so i'm just thinking about well basically that we can either keep track by keeping track of uh the parent or we can keep track by i don't know some kind of maps i'm just giving a quick thought to think about which way i'm uh wanting to do it but yeah so we have yeah this is let's just say this is the diameter is to go to this thing and then okay actually i think um i think we could keep you use uh take account keep track of the earlier distance is to go to uh let's keep a copy of it and then all we have to do now is for an answer is you go let me see if this is right first i'm not sure let me think about this but for index and range of n um if the distance from this index is equal to the earlier distance that quite radio distance like that of index and the distance of index is you plus earlier distance is equal to diameter if this is the case then we want to make that part of the answer otherwise if um the absolute value of the distance if this is one then n the distance of index plus uh this thing again is to go to diameter so only one of these can be true i guess because it depends on whether the diameter is odd or even uh but basically this is saying that you know we took an earlier distance right the first time we won the loop if during that first time in the loop it is equal to the distance of this loop that means that it is the same uh distance and if they add up to be the diameter then it then you know this index is the route right because um because that means that from this node you have these two points and that it is the same distance from the zero node and the and one of the root notes right uh or sorry one of the uh leaf nodes which is what you get with the farthest node uh right and yeah i think that's the idea that i would call it i don't think i'm explaining that well so i could visualize it a little bit let me run the test to make sure that i'm white first otherwise it's just a little bit awkward if it turns out to be wrong uh but oh earlier distance whoops they're not i think i misspelled diameter in some places is it huh yeah it's a very ye man what'd i keep on putting earlier is distance earlier distant previous distance let's give it a go why is this zero one two um let me look at my code real quick basically is this one of the examples i feel like this no it's not but it's three node as zero one and zero two so it just looks like is there now there's no visualization um and then well it has to be an answer obviously so my answer is just wrong why is that let me print it out real quick the distance okay so at least there's something that's not wrong wait what why is this two oh yeah uh because um if i just took one of the leaf notes which is true yeah so 0 1 so zero should be good because this is equal to one and zero plus one is equal times am i or five one maybe i'm off by one that's hot no i mean still plus one is definitely not going to be the diameter right hmm okay um ah that looks okay i mean it's getting the correct for this node so hmm oh i'm being dumb uh so what i did was that for here i have gotten so actually okay now i think i will kind of remember what i wanted to do but i kind of got confused between two things i wanted to do which is that um so for the diameter of a tree you use two depth of search right um so now what i want to do is use um three that first search so that um so then you know like so now we have two nodes and then um two leaf nodes that are like on the opposite side of the tree so then we want to construct um a node that is the same distance of between the two nodes right the two farthest two nodes so actually we want to do this three times i think that's why i got a little confused because i was confusing of the algorithm of the tree so then we do this and then now we do this again with the farthest distance and the farthest node and then now we take we keep track of the earliest distance um we do it again and then this should work okay and i'll explain it again sorry um let me just make sure that it works if i explain it maybe yeah okay so i confused myself a little bit because the standard algorithm for a diameter tree is just you take any node you go one depth or search to get one of the leaves and then you go do a different switch again to get another like the opposite side of the tree and then that those are the two opposite side of the tree right so basically what i want to do here is for these two farthest notes um we want to go okay now we have two opposite sides of a tree we're gonna see what's in the middle right and that's basically what i have here i have the two farthest note earlier distance is the distance to one of the leaves and distance to the other leaf right so now we have two opposite side of the tree we want to look at the middle right and in the middle if the two distance are the same that means that it's literally in the middle and that they add up to the diameter just because it could be you know um then it has to be in the middle or if they are different by one and they add up to the diameter because if you have uh an odd number for example if you the distance is nine then you want to know that's four from one and five from the other uh that's all i have for this one so the what's the complexity right well we do read that first search so it's going to be linear because each therefore search is linear uh in terms of space it's going to be of d for the number of edges or it'll be o of v plus g for the depth research to be more specific of g for the space and also or v for um the space so it's going to be ov plus g space and or v plus z uh running time both of which are linear in terms of the size of the input so yeah that's all i have for this problem uh let me know what you think is tricky i like it but i don't know if there's a more standard part way of solving this to be honest but that's the way that i think about it uh and it's a little bit messy to be honest from for prom that maybe it's not that hard um but yeah let me know what you think let me take a peek at the solution actually and then maybe we could go over together if it's too drastically different um because we all learn together there's a graph form yes topological sorting cento i mean it's not weird top i don't know okay there's too much to read on this one so um okay so i have to kind of read in another time but yeah let me know what you think hit the like button to subscribe and drop me a discord and i will see y'all tomorrow bye
Minimum Height Trees
minimum-height-trees
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between the two nodes `ai` and `bi` in the tree, you can choose any node of the tree as the root. When you select a node `x` as the root, the result tree has height `h`. Among all possible rooted trees, those with minimum height (i.e. `min(h)`) are called **minimum height trees** (MHTs). Return _a list of all **MHTs'** root labels_. You can return the answer in **any order**. The **height** of a rooted tree is the number of edges on the longest downward path between the root and a leaf. **Example 1:** **Input:** n = 4, edges = \[\[1,0\],\[1,2\],\[1,3\]\] **Output:** \[1\] **Explanation:** As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT. **Example 2:** **Input:** n = 6, edges = \[\[3,0\],\[3,1\],\[3,2\],\[3,4\],\[5,4\]\] **Output:** \[3,4\] **Constraints:** * `1 <= n <= 2 * 104` * `edges.length == n - 1` * `0 <= ai, bi < n` * `ai != bi` * All the pairs `(ai, bi)` are distinct. * The given input is **guaranteed** to be a tree and there will be **no repeated** edges.
How many MHTs can a graph have at most?
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
207,210
102
hey yo what's up my little coders let me show you in this tutorial how to solve the little question number one hiring a two binary tree level order traversal basically we are given the root of a binary tree and we want to return the level order traversal of its node's values the return type should be the list of lists and if this is the binary tree which we get as an input in this case we want to traverse through it like level by level and we want to store the values from each level as a separate list inside like one big list if you start with the root value 3 there's one value on this level we store this value as a separate list then another level we have two vowels here 9 and 20. that's a separate list as well we store it then the next level which is the last level we have here two values 15 and seven that's another level so that's another list you store the values from this level and yeah and then we just return this like list of lists this is what we need to do guys and if you're not sure how to do it and you want to figure out how to solve this question efficiently just stay with me guys i will quickly read the code now and i will go through it with you and will explain you everything okey dokey my little coders here's our code i also prepared some pictures for the explanation because we want to return the list of lists that's why we create the variable for it here on 117 here we initialize this variable it's equal to the new error list of list then we call the function which is called traverse that's the recursive one we pass the root value to it and also we pass the current level because you want to keep track at which level are we located at the moment and again because that's a recursive function and we are traversing through the tree the first thing about which we should think is the base case and the base case is when the root is equal to now because if dirt is equal to no we can't do anything with that we just return straight away but if it's not equal to now it would mean that we would consider the first level that's the value 3 that's the root of the whole binary tree we check if the current size of the result is less or equal than the level because if it is it means that we need to create the sub list to store the values from the current level this is what we do here on line 29 we add a new empty array list to the result variable so here then once we have done that we can add the current value to this sub list so we do like result would get of index 0 because we passed 0 here and we add the root value to it perfect we traverse through the first level now right and we added the value now we can go to the next level and we can do it recursively we would call this function again recursively but on the left subtree first of all and if you understand the recursion well you also understand that the line 33 where we're going to the right subtree would not get executed until it will traverse through the whole left sub g so actually we're not going club level by level but we're implementing the different search algorithm so first of all we'll traverse through the whole website g of the binary g before you would go to any like right subtrees and there's the reason for doing that because if you actually want to go level by level you would need to use some additional data structures to do that and when you would use the additional data structures you would use some additional resources as well and this is not you know the best thing to do when you can avoid doing that so because you want to solve this algorithm efficiently you would avoid doing that and you would implement the default search here but okay of subtree the next value of nine that's the current node okay it's not now we don't return anything here and here we also need to add a new sub list to store the values from this level we do that here we also add the current value to this sub list perfect then traverse to the left subtree but here there are no values here we would return here same applies for the right subtree because there is nothing here so we return then recursion and from you know the initial note we would go to the right subtree value 20 and you already know what we would do here but we would not add a new list because we already have a sublist for this level we will just find the current value 20 goes here to this list then traverse left side 15 we create a new empty list we add this current value to this list 15 goes here we have sub 3 nothing here right sub 3 nothing here so recursion we would go to this node which has the value 7 and here basically would append 7 to this sub list and in the end we just would return simply as that guys let me just run it to see if it actually works code does let me submit and if i submit i get hundred percent that's perfect i hope it was clear if you enjoyed this tutorial please guys give it a like and subscribe challenge your friends to see if they can solve this question or not and i will see you next video guys good luck
Binary Tree Level Order Traversal
binary-tree-level-order-traversal
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[9,20\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
103,107,111,314,637,764,1035
1,011
hello welcome back today I will solve Leal 1011 capacity to ship packages within D days we given an array of weights and this represent the weight of different packages we also given the number of days to ship all the package to a different port our job is to determine the minimum capacity of the ship that can ship all the packages within the number of days that were given to us okay let's do an example in this array we have different packages the first package has a weight of one unit and the second package has a weight of two units and so on the combined weight of all the packages here is eight we are given four days to ship everything suppose that the ship capacity is one unit so on the day one we ship the first package and on day two because the capacity of the ship is only one and the package weighs two so this won't work we're not allowed to divide the package into two and ship them in different days so let's try a different capacity suppose the ship capacity is three the first day it can ship package one and package two because this has a combined weight of three the second day it will ship the third package which has a weight of three that's perfect on the third day it will ship the remaining two packages with a combined weight of two so it will take 3 days to ship all the packages if the capacity of the ship is three units in this example we're given four days to ship everything and we just find out that we only need the three days so this will work suppose we try another ship capacity if the ship capacity is a uh which is the sum of all the weights then we can ship all the package in one day in fact if the ship capacity is anything higher than a we are still not able to do better than the one day we needed to ship all the packages in this question our goal is to find the minimum ship capacity that will allow us to ship all the packages within the number of days that was given to us we also understand the minimum ship capacity has to be the maximum value of the weight array because anything smaller than the maximum value of the weight array there will be a package that we are not able to ship now that we establish the minimum capacity of the ship what is the maximum capacity of the ship that we can try well that will be the sum of all the values in the weights array because if we use that sum then all the weights can be shipped in one day and we cannot do better than this now that we have the range of capacities we can either do a linear search and find the capacity that will work within this range or a even better solution is that we would do a binary search within this range again we are Solo cing the solution starting with the binary search template the low is the maximum of the weights array and the high is the sum of the weights array and then we also have the rest parameter that is the response value we're going to return at the end of this function and we going to set that to zero if we cannot find a capacity that can work then we will return this value but again we start with w low less than equals to high we're going to determine the mid value and we going to pass this mid value and the weight array and also the number of days that's given to us into this function called can ship in days and if this does work then we will set the rest to the mid value because we have find a ship capacity that will work and then we going to set the high value to Mid minus one because we want to see if we can find a capacity that is lower because we want to find the minimum capacity that we can ship all the packages however if the mid capacity does not work then we will set the low while you as mid plus one we're going to search in the upper half of the range and at the end we will return the response parameter let's talk also a little bit about this can ship in this function would in the weight array the capacity which is the mid value for every iteration in the binary search and the number of days that's given to us so we have a parameters called need days and we set that as one need days is the parameter in which we can compute the number of days we would need to ship all the packages given this capacity we also have another parameters called sum and this will be the accumulation of weights of the packages and we will set this value to be zero with a for Loop we'll go through all the packages and we're going to add the weight of each package to the sum parameter and if the sum has exceeded the capacity then we increment the need State parameter by one furthermore we will assign the sum value to be the weight of the current package because this package need to be shipped in the next day if the need days that we just computed has exceeded the days that we allow then we know this is not going to work so we're going to return false otherwise we return true let's go through this quickly with example for example in this we a aray we have 1 2 two and the ship capacity is three we start with N St equals to one and the first iteration of the four each Loop the sum is one in the second iteration the sum is three because we added two here and then in the third equation the sum is equals to five now here you will trip the if statement because now the sum is greater than the ship capacity we will increment the need days parameter so need dates becomes two and then now the sum is two because we at this situation and then in the final iteration the sum is now four and then again this will trip the if statement and then we increment the need State value by one so now the need state is three and then this will finish the for each Loop so the total number of days we need is three okay now that we talk about the sudo call we just quickly convert this to real call this C implementation is available in the GitHub links Below in that GitHub link I have also included the python version of this code everything here is same as the pseud code so this is very straightforward and we can go ahead and test this see if it works and it looks good next time we'll do another binary search problem hope to see you then
Capacity To Ship Packages Within D Days
flip-binary-tree-to-match-preorder-traversal
A conveyor belt has packages that must be shipped from one port to another within `days` days. The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days. **Example 1:** **Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5 **Output:** 15 **Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. **Example 2:** **Input:** weights = \[3,2,2,4,1,4\], days = 3 **Output:** 6 **Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 **Example 3:** **Input:** weights = \[1,2,3,1,1\], days = 4 **Output:** 3 **Explanation:** 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 **Constraints:** * `1 <= days <= weights.length <= 5 * 104` * `1 <= weights[i] <= 500`
null
Tree,Depth-First Search,Binary Tree
Medium
null
867
all right hey what's up guys Nick white here at detected coding someone's watching YouTube I have all the leaked code and a current solutions and playlist on my channel if you want to check those out also everything else in the description this problem is called transpose matrix given a matrix a return the transpose of it what is transpose mean I looked it up on Google I'll show you what it means actually I didn't define transposing actually we need transpose is caused two or more things to change place with each other well that means the transpose of matrix is flipped over the main diagonal switching the row and column indices so we're going to be switching row and column indices two or more things swapping places okay so as you can see here I took the examples and I just commented them right here so as you can see the rows are becoming columns the columns are becoming the rows so one two three is gonna be a column four five six you'll be a column seven x can be calm and down here you can see that one two three becoming a column is actually going to modify the number of rows and columns that are new array four five six four by six so what are we gonna do we're gonna grab the number of rows Y dot length we're gonna grab the number of columns if 0 dot length sorry about the noise it is I'm at school right now so we have int new matrix we're gonna define our new matrix it's gonna be empty at first and obviously some cases we have to swap the dimensions this doesn't actually swap dimensions because it's a square matrix so that's gonna work the best case but sometimes we're going to be swapping dimension so we just have to account for that swapping places right here so when we declare this a would be of rows and columns but actually we're gonna have a different amount of columns and rows if it's not a square matrix right so we just swap those valleys then it's just a simple walk through the original array while I is less than rows I plus four you can do this two super separate ways but we're doing it this way we're walking through the original array J is equal to 0 while J is less than columns increment J a little keyboard trouble here and then this is the final part obviously we're gonna be returning our new matrix at the end of this all we have to do here now is just add values to our new matrix that we're going to return at the end so what are the values we're going to want to ant add if we want to turn the rows into columns well if we're looping through a you can either loop there air you can look through this new matrix but we're looping through A's rows and columns then we're gonna iterate through a you know normally so a of I of J so that would be a normal walk through a and then we're just going to do a swap here to swap all the values right and this should be pretty intuitive if we run this pretty straightforward here submit perfect solution there we go first try so there we go as you could just to explain it a is this is just a for loop through a so imagine we were printing these values in this example it just got one two three four five six seven eight nine new matrix J of I is actually going to be incrementing J so J is being incremented o premier the one four and seven what's going to be increment in obviously this is an empty array the columns are going to be incremented while these rows are being incremented so the rows values get put into the column values we loop through everything that's pretty much it thank you guys for watching hopefully you understood that let me know if you don't understand that or if you have a better solution comments below and thank you guys and I'll see you guys
Transpose Matrix
new-21-game
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **Example 2:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\]\] **Output:** \[\[1,4\],\[2,5\],\[3,6\]\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 1000` * `1 <= m * n <= 105` * `-109 <= matrix[i][j] <= 109`
null
Math,Dynamic Programming,Sliding Window,Probability and Statistics
Medium
null
987
so hey there everyone welcome back i hope you all are doing extremely well so this was our today's problem of the day vertical order traversal of a binary tree so let's see what the problem is so we are given the root of a binary tree we have to calculate the vertical order traversal of the binary tree so for each node at position row comma column its left and right children will be at positions row plus 1 and column minus 1 and right children will be at row plus 1 and column plus 1 so the root of the tree is at 0 now what is vertical order reversal it is a vertical loaded reversal of a binary is a list of top to bottom orderings for each column index starting from the left most column and ending on the rightmost column so there may be a multiple nodes in the same row and same column but in such a case we have to sort these nodes by their values right so we have to return the vertical order traversal of the binary so for example this tree is given so now let's see the tree given so we are given with this tree uh with root value three and left child last nine and for the moving on to right child it's 20 and further left and right child of 20 are 50 and 7. now if you do vertical order traversal so first we are starting from here right so it's at row plus 1 and column minus 1 right so this is it the vertical order diversal so zero plus one will be one and column is decreasing right so we are going like back let's say we have a 2d matrix right let's say we have a 2d matrix and here is a root node let's say at 0 comma 0 index so its left child will be somewhere here right so how so column is decreasing right so it will be at minus 1 but row is increasing right so it will be at one comma minus one further moving on to its right child uh i am drawing this like to visualize where are their left and right childs so its right child will be somewhere here right so here also uh our column is increasing right from zero to one it will be one right and row is also increasing right row is also increasing so here we came here right so its right child will be at one comma one right so you can visualize it using a 2d matrix right where left and right charges are coming so in the case we have a we have multiple nodes in the same vertical order right in the same means horizontal distance is same so uh then in that case we have to print them in the sorted order so let's see in the case other hammer passing 15 will print them in our sorted order not like this 15 and 3. if horizontal distance is same from the first very first node then we have to sort them right on the base of their value right 3 is less than 15 so that's why 3 will come before 15 right so we'll take care of a horizontal distance also and obviously vertical distance also so the node which is coming first uh in case of horizontal distance uh as well as in vertical distance right we'll print it first so let me show you what horizontal distance means here so let's say we have two roads right we have two roads this is road one this is road two let's say we have something at here right at road one let's say it's a car one this is car two right this is car one this is car two so let's we are standing here so if you see if let's say if you see the distance between them right from us and the car let's say it's x then from here it will be also x right so this is a horizontal distance right so this is horizontal distance this is the vertical distance right so means in the case if we have let's say we are seeing from here so node 15 also has horizontal distance let's say some something x right so and uh our this node was originally our this node value was three right it was three it is 59 it is 15 so let's see uh we are seeing from here so it is uh at a distance x right horizontal distance and if we see from here this node also has a same horizontal distance right so if the nodes have a same horizontal distance then in that case we'll print them in a sorted order right so we'll take care of horizontal distance also as well as vertical distance also right and so now what if we what we have observed is let's see we are seeing from here let's say this is a voltage we are seeing from here so this node also has a same horizontal distance this also node has a same horizontal distance right so the nodes with the same horizontal distance similar horizontal distance they are coming on the same vertical line right they are coming on the same vertical line this is different 20 is different seven is different right so if we try to print them our answer will be like first nine will come uh and then our sorry first three will come right it's coming first oh sorry uh nine yes nine will come first because it's coming first right uh column wise and uh now three will come right so and 3 and 15 now will come because their horizontal distance are same right their horizontal distance are same so and this one will be in sorted order right now 20 is coming now 7 is coming right so we have to print them in this order right so the concept of now key value pair is coming into our mind right how so we'll use a key value here we'll use a hash map based approach we'll do so what we'll do is that nodes coming with the same horizontal distance and on the same vertical line will store as a key value pay right we'll store as a key value pair so like our let's say we have a key we are making key value here so their horizontal distance will be will take as a key value means the value of key and value will be all the nodes right and in the form of so let's say i am taking a map and uh i am taking a map so our key will be of type integer right integer means it is only going to show our horizontal distance uh and our value will be of type vector right it will be of type vector right y vector because uh because the nodes having horizontal distance uh will have multiple nodes right so let's say on this our vertical line so there are multiple nodes coming right we'll store them in a vector right because there are multiple values coming so let's say now we are calculating from here right so 4 9 4 nine now so uh let's say we generalize our distance let's say we are seeing from the root node we are seeing from our root node this is a horizontal distance from here we will see so our first node which is nine it is at how much distance it is at minus one distance from our root node right so let's say we are taking as a key uh key which is a minus one right so let's say i am storing here like this is a key and similarly uh will attach values uh with them right so at the distance minus one we have only node with value nine right with nine so now we are seeing the distance of nodes from here from our root node so 3 and 15 are itself on the on that distance means it is at zeroth distance from the distance we are seeing right so now at our 030 stance how many nodes are there 3 and 15 right so for that we'll use a multi set to store in a sorted order right we'll store it in a sorted order otherwise it can be a unsorted order also but uh according to the given problem we have to uh we have to sort them when they are on same horizontal distance and on same vertical line right so for that we'll use a multiset in our coding part right because if we use set first of all sat will remove our duplicates right but in the according to the problem we don't said anything that we have to remove duplicates overall so if duplicates are there we have to keep them so for that we'll use a multiset because there is a difference between set and multiset or both will store them in a sorted order right but our sat will remove duplicates but our multiset field will keep duplicates also right it will keep duplicates also and it will store the values in a sorted order already right so if let's say in the case 15 3 is coming then using multiset 315 will be there right so we don't have to worry about that we'll use multiset so now this node further node this is at a distance of one from our root node we are seeing right so as a key as a keywords will store as a horizontal distance which is our key and uh nodes are only 20 right at a distance one nodes are only 20 this is its value right so in this way we are using key value for the this node 7 this is at a distance to right so its distance will make it as a key and value will be value is the node value which is 7 right so in this way we'll store right so that's it this will be our algorithm so after storing values like this right key value pair so after that we will recursively traverse on our tree right both at uh left and right child and we'll keep track of our horizontal distance also with respect to our root node right we are taking horizontal distance with respect to our root node right so after that whenever current horizontal distance uh means as a key we are taking so the key values we are taking our horizontal distance right so after that we'll push the current node into the map of vectors right we'll push the current node into a map of vectors after that once our recursion gets terminated will show each of the values right each of the values these vectors in the map right because we need district keys for that we are using multiset because it will also allow duplicate values also otherwise if you use set then it will remove duplicate values right and finally we'll return them right and now here is a very simple code so you can see what we are doing is we are making one recursive function right we'll call that left and right part right so if root is present now and you can see here we are using a map of key will be of type integer only and value will be of type multiset right because we have to store them in a sorted order if other nodes have a say at a same horizontal distance and on same vertical line right so that's why we are using multiset and if root is present then we are inserting our node right present at that current horizontal distance uh we have we are inserting it into the map we are taking right so after that we are applying recursion for our left sub tree by decreasing our x we are doing x minus one right we are decreasing our horizontal distance by one right and we are applying reversion on our right subtree also by increasing horizontal distance by 1 right so now this is our main function so now we are taking a map of type intent vector of type multiset right and now we are applying that to our root node right we are applying to our root node so initially our root is present at 0 and 0 horizontal and vertical distance right and we are taking vector of type factor so now further we are iterating on our map right in which its keys of type integer and values are of type multiset right they are stored in a multiset and in sorter order right so after that the answer we are taking 2d vector uh in that we'll store all the values first we are pushing uh the values in our vector called column right so we are pushing like q dot second dot begin to q dot second dot end right why second because we have to access all the values right amazing key value the key we access using dot first and the values using dot second that why we are using dot second and finally we are pushing back all the values of our vector uh column in our 2d vector to return our final answer right why we are taking 2d vector because we have to return multiple values also right at each index so that's it at last we are turning our answer so that's it let's try to run it so you can optimize it further also using breadth first traversal like level by level order traversal so if you need more optimized approach so you can comment in the comment box otherwise it is also getting accepted so if you still haven't doubt please ask in the comment box and thank you so much stay tuned for more videos and if you like the video please do share and subscribe to the channel and you can connect with me my linkedin handle is given in the description box so thank you so much
Vertical Order Traversal of a Binary Tree
reveal-cards-in-increasing-order
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return _the **vertical order traversal** of the binary tree_. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Explanation:** Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. **Example 2:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. **Example 3:** **Input:** root = \[1,2,3,4,6,5,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 1000`
null
Array,Queue,Sorting,Simulation
Medium
null
46
hey there everyone welcome back to lead coding i'm your host faraz so recently i uploaded a lecture on recursion and backtracking so it was an introductory lecture in that lecture i had three questions so two are the basic questions and one was a bit advanced so if you didn't get everything into that lecture i am going to repeat the problem number two of that lecture that is permutations again in order to make you understand this so that you can solve all the questions which will be coming up in the future lectures and if you didn't understand everything you don't have to worry because we are going to solve a lot and lot of questions on regression and backtracking very soon so let me just start with this problem and let me just try to make you understand how does recursion work in this problem also if you understand that if you understand this problem in that video very clearly you can just skip this video it is of no use for you so let me just start with this we have to find the permutations of certain numbers so if we try to find out the permutations of one two and three okay before that we already know if we have only one number the permutation will be that number itself if we have two numbers let's say uh 1 and 2 and the permutation will be 1 2 and 2 1 okay so basically what we do when we try to find our permutation so we keep one number to ourself okay each number one by one we will keep it to ourself so we kept one to ourself and then we try to find out all the permutations of two comma three okay and then place them append them at the back of one so the permutations of two three will be two three and three two right so i will just append it at the back of one so two three will be added here then one three two will be added here so i was able to find out two permutations when i placed one at the first position first location right okay now similarly i will place the second number at the i will place i will keep the second number to myself that is two so i will keep 2 to myself and i will pass 1 and 3 and i will generate all the permutations of 1 and 3 and append it at the back of 2. so the permutation of 1 and 3 is going to be 1 3 and 3 2 sorry 1 3 and 3 1 so i will append it here one three one i got two more permutations when i placed two at the beginning so i kept two to myself right now in the third case i'm going to keep three to myself and i will generate all the permutations of one comma two and i will append it at the back of three so three here one two three here two one okay very clear now let us move on to a bigger example and see how does these things work so let us say if i have four numbers one two three four okay now again doing uh the same strategy again following the same strategy i will keep one to myself and i will try to generate all the permutations of two three four so that i can append it at the back of one now we already know the permutations of three numbers three different numbers are basically six right you must know this from the mathematics or you must know this from the last example that we used we were permitting one two and three and we were able to find six permutations so the permutations of three numbers three different numbers are six so we will be able to generate six permutations from two three four and i will append those six permutations at the back of one so one and six permutations let me just um give an example here so those permutations are going to be two three four two four three four two three four three two okay so these are the six permutations that i will be able to get with the um with these numbers and i will append one at the front of them nice now again following the same strategy i will keep two to myself and i will try to generate all the permutations of one comma three comma four and i will uh again append them at the back of two so two similarly i will be able to find six solution six permutations when i keep two to myself or two at the front right similarly three at different four at different now did you notice here that when i was generating the permutations of these four numbers i also wanted to generate the permutations of these three numbers and then append them in the front of one when i kept two to myself then i wanted to generate the permutations of these three numbers one two four one three four and then append them at the front of two okay let's say if i have five numbers one two three four five then i will keep one by one each of these numbers to myself so if i keep one to myself i want to generate the permutations of these four numbers if i keep two to myself i want to generate the permutations of these four numbers and apparently append them at the front at the back of two right so if i have n diff and distinct numbers i also want to generate the permutations of n minus one number so that i can append them at the front of each of the numbers one by one right now so to find the permutation of n numbers you want to find the permutations of n minus one numbers and to find the permutation of n minus one numbers we want to find the permutations of n minus two numbers similarly permutations of n minus three numbers till the time we have only one number left okay awesome so now this gives us a hint of using recursion here why recursion because recursion is a function calling to itself so we can clearly see here if we are calling the function to permute certain numbers that function itself required to permute n minus one numbers okay these are the same functions because they do the exact same functionality so the function in which i am trying to permute n minus one numbers which was in fact called by the perm the function which in which i wanted to permute n numbers this will further call a function which will permute n minus two numbers so again the same functionality that's why i'm going to call the function is going to call again itself so without wasting further time let me just dive into the code so that you can understand it so now let me just try to code this so i'm keeping a helper function or let me just name this as permutation in this i will pass the given vector of int so these are my unique numbers inside this nums and i will keep track of the index i so uh for basic uh for more clarity let me just try to explain you this way so let's say i have the collection of numbers as one two three inside nums initially okay this is my nums and i'm trying to create the permutation right so uh first of all i said that i'll be keeping one to myself so if i keep one to myself i will be storing it somewhere and i will remove it from these nums so i'll keep it somewhere maybe in some other vector and i will remove it from these nums and i will try to generate all the permutation of these two numbers two and three and i will just try to append them uh here over here in front of one right so okay let us say i read a function that function returns me a vector it returns me a vector of int and it will be having the permutations of all the numbers right it will be actually a vector because there could be many permutations so i will have this function and uh as i said i will keep all the numbers one by one to myself so for that i'm running a loop for end i is equal to zero i smaller than nums dot size minus one some sort size number size i plus and i'll keep each of these numbers one by one to myself so this is my answer okay and here i'm creating a temporary vector find temp in this i will be storing um the i'm keeping to myself the number numbers of i this is the number that i'm keeping to myself and rest of the numbers i will have to pass okay so rest of the numbers should be pass into this function again so i'm keeping this number to myself and rest of the numbers like for int j is equal to zero j is smaller than num start size and j plus so now i will go to uh i will pass each of these numbers just except the number at the place i because i am keeping it to myself so if i is not equal to j i have to pass all these numbers to the permutation right so for that um i'm keeping here a vector again a vector of int maybe nums 2 so in this i will have to insert all the numbers except the ith numbers so nums two dot push back and nums of i okay so this is what i'm going to pass here i just removed the reference sign here because i'm going to change it so now i'm start push back num so if i'm starting all the numbers and just accept the ith number after this i will pass this number to the permutation so i kept the ith number to myself that number is stored in temp okay now i created another vector that is nums two and inserted all the numbers except the ith number into this number finally i will call the function perm so for that i will keep a vector of vector int this will be v which will be equal to permutation of the nums 2 okay i will have the permutation of nums 2. basically um then i will have to append all these permutations at the back of 1. so for that what i can do is for whatever permutation that i have got so for auto a belong to v so this is the a is the permutation i will be going to each of these permutations and what i will do is to append one at the front of all these permutations and insert it to the answer instead of appending it at the front i can also append it at the back it won't change the results so i can just do this so a dot push back the ith number so the ith number is nums of i right so i can push back this and i can simply insert this into the answer so ask dot push back a and i don't need this part okay finally i can return it from here return answer and let me just try to run this once although this is not the optimal approach i will tell you why i will make this code much more simplified but this is this for basic understanding so this was basic understanding that we have discussed what we have discussed we are picking each of the numbers one by one okay except that number all the numbers will be permuted hence we are calling this recursive function perm here except in numbers two there are all the numbers except the eighth number so i'm calling on this so i have all the permutations of all the numbers except the ith number now once i have that all those permutations so at the back of those permutations i am appending i okay i could have appended the front also but appending at the back is much more simple so i'm doing that and finally i am pushing that back into the answer returning the answer and let me just try to run this once and hope it gives us the correct answer and not the compilation errors there are compilation error okay so this function is sperm so basically we forgot to add a base case here the base case is when the when there are no element left so num sort size when it got reduced to zero in that case there are no elements so we can simply return an empty vector here okay so i can just run this now and there's also one more problem here so we are pushing we have to take all the elements except the ith element so we have to use nums of j let me just try to run this again and it got accepted because it is giving us correct answer but let me just try to submit this most probably it should give us tl because we are using a lot of space a lot of it is not giving us dearly but there's another optimized approach so here we are using a lot of extra space we are making the copy of these vectors again and again we are using so much of the triggers the stack in which we are creating these vector vectors again and this is a lot of computation so we need to simplify this first of all you should understand this thing okay if you understood this thing now let's move on to a more optimal solution okay that is going to use a very less space and that will be much simplified in terms of coding so basically what i'm doing here i am trying to keep one number to myself and permute rest of the numbers and the number which i'm keeping to myself i will take all the numbers one by one right so if i have one two three i will take one to myself and parameter two three then i will keep two to myself permit 1 3 then i will keep 3 to myself and permute 1 2. so instead of doing like that what i can do is 1 2 3. so what i can do is i can keep the first number fixed at the first place and then call the permutation on the rest of the numbers then um we want to fix the second number so we'll fix 2 here and then try to find out the permutation of these then i will fix 3 at the first position and try to find out the permutation of all these one end sorry two and one here okay so how can i achieve this so if you want to achieve that what i can do is i will um at this position i will try to keep each of the numbers one by one so first of all i will keep one here okay next time i want to keep 2 here so i will swap these two numbers so 2 will come here and 1 will go here then i want to keep 3 here so i will be swapping 3 with 1 so three will come here and one will come here so let me just show you the help of the code what i want to say here so let us say i want to find the permutation starting from the zeroth element right so i will pass you into i this will be zero initially because i want to find the permutation starting from the 0 till the end so i will run a loop for int j is equal to i j smaller than num start size and j plus okay then i will swipe this nums of j with nums of i basically at the ith position i'm trying to place all these elements starting from i till the end i'm trying to place all these elements one by one okay and then i will find the permutation of rest of the numbers so okay so nums and i nums comma i plus 1 all right and after coming back i'm going to undo the changes that i made so swap off nums of i again with numbers of j it is going to undo the changes which i made simple okay so at the end when i is equal to num sort size when i reached till the end in that case i have the permutation stored in these nums this nums will have one of the permutations so i can simply store this into the global answer or the answer that i have to return so answer dot push back this particular permutation that is nums okay and i can return from here also i can create the global answer so you don't have to create it globally you can either pass it using reference in this function perm or you can also create it globally but the better practice is to pass this in this sperm as a reference so after doing this i will be calling to this function and i will okay we don't have to return it because now the type is void and then you can return the answer and here let me just write void let me try to run this if i is num star size okay swap now you can notice one thing in this code we are first of all we are not uh returning anything so we are not creating any extra space here second we are passing it as a reference so in the previous example we could not pass as a reference because we were changing it now we are not changing it so we can pass it as a reference so again this space is saved because if you pass it without using a reference it will create a copy in the memory so let us say if you have let us say 50 recursive calls 50 times the function is calling to itself each of these 50 times is num will create some space into the memory okay it will take this memory if it passes the reference then only one copy will be made and rest of the copies won't be made so you should always try to pass anything a vector or a string as reference into this recursive calls okay now there's another error what is the two few arguments well okay so here there are two few arguments in this case because we have to pass zero from here as well all right so it got accepted and you can see the memory usage is also less this time and it is much faster i hope yeah it was 12 milliseconds and it is now 4 milliseconds awesome so this is how you can do this right 0 milliseconds nice i hope those who are not understand it in the previous video they understand it now so if you want to suggest anything please leave your comments if you like the video hit the like button and make sure to subscribe to the channel and make sure to hit the bell icon to get the notifications of the latest videos thank you
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
1,539
hi everyone my name is steve today we're going to go through lead code problem 1539 case missing positive number let's take a look at the problem description first given that array of positive integers sorted in strictly increasing order and an integer k find the k positive integer that is missing from the array all right let's take a look what are the possible test cases first one is given this one two three four seven eleven k is five that's asking us to find the fifth missing positive integer why the output is nine that is because let's see the missing positive integers are all of these one we're missing one so that means we are expecting the given integer should be starting from the first positive integer which is one okay so we're missing one two three four five is missing six is missing seven is there so eight is missing nine is missing 10 is missing 11 is there so far how many did we get all of these is a six so it's asking us for the fifth missing number so that is the nine this is the fifth missing number that's why it's returning nine this is the first test case the second one is this one two three four and it's asking us for return to return the second missing number k equals to two and it's returning six because the missing positive integers are starting from five because one two three four all of these first four positive integers are there so the first one missing is five second one is six that's why it's returning six so this is labeled as a very easy problem but i thought it's interesting to discover different um test cases and multiple different solutions first solution is that we can use it's not very efficient we can use a hash set we can put all of the numbers into a hash set we can start from one all the way up to the max number and to see if there is anyone missing and if the missing if the number of missing numbers adds up to the total number of k and then we can just return that number if that is not the case we can continue to add up until we find the case missing number that's one way time complexity of that one is going to be o n space complexity is not a one that's o n because we are using an extra hash set um which is going to consume space of o n so that's not super ideal another way is that we can use constant memory constant actual memory which is one and then we'll just loop through this array once and then we just return the correct answer apparently that one is more ideal so we're going to type that one but before we type we would like to sort out all of the possible test cases um the list out to two so let's think about all of the possible test cases so these are the constraints so there's a total of only up to one thousand integers and the k is up to one thousand as well so given these two constraints there are multiple even very brutal ways to solve this but i'd like to make this solution very generic even these two constraints don't exist so let's talk about the possible test cases so test case uh let's just call it case one which is uh let's say array is one two three and k equals to two in this case result should be four five it should be returning five right this is the first test case second test case is let's say um the actual the given array is three four five and k is two in this case we're missing the first two one two so the result should be two and what on the other cases let's say that is something in the middle let's see three four five uh let's put in nine here and in this case k we can put k to be three one two three four five six so in this case result should be six these are the three possible cases that we need to take care of so let's go through the constant actual memory solution well we'll see so first we'll use a variable called mist see how many missed variables how many missed numbers are there that we need to add up now and then we'll have a for loop to go through this given input array and i equals to zero i smaller than array length i plus and next is if just in case if this is the very first one which means it's in this case test case two if so this one is especial a special handle so three cases that means we need to have at least three branches one branch is outside of this follow which takes care of the last one let's take a look so if this is the first one which means it's this case and the first one we want to handle this case array okay if i equals zero and everything else if that's what just added up missed so how many possible numbers out there that's going to be missed let's just use the first number minus one so we're expecting the first number in the given input it should be one right so like saying this is correct this is the so the first number is not missing if that if it's not one that means we're missing at least one number there which is one right so for example in this case this three the first number in the given input is three that means we're missing two numbers three minus one is two we're missing two numbers here that's why we use array the first one minus one that means how many numbers are missing so in this case it's going to be missed is zero we're not missing any number in this case right but just in case if this these later two cases what we want to do is we want to add up the missed number and we want to test if missed number is greater than or equal to k in that case what can we do we can just return k right so for example which is this case three four five k is to two k is two and missed is three the first number is three 3 minus 1 is 2 so missed is 2 at this moment so 2 is greater than or equal to 2 then we can just return k is 2 in this case which is correct right so we need to handle this case in all other cases that's totally fine so we'll just continue we'll let i to increment and then here we'll also do something very similar we'll just calculate how many positive integers i'm missing between this one and the last one so what we want to do is we want to use since this is a sorted array in strictly increasing order meaning there is no duplicate and everyone is in sort of increasing order ascending so what we can do is that we can use four minus three so we always use this one the one that we are currently iterating on to subtract the one prior to this so what we can do is we use array i minus one and minus one so that means so say this one between these two numbers there are no missing numbers right so what we are expecting is four minus three is one so one that's why we need to decrement one again that means there's no missing number right in between these two numbers right but just in case if it's something like this so nine and between five and nine so nine minus five is four so four minus one again that is three are we missing three numbers so six seven eight right when we're missing three numbers so that means this formula is correct all right and after we calculate missed in this case we want to do if missed is greater than or equal to k if that is the case that means the case missing positive number is within this range right for example it's just in this case the third missing number is within this range if that is the case we can just find it there so let's first return the missing number the missed number back to its previous one and then let's use let's initialize a variable just call it result and this one should be the one prior to that and then we can just keep incrementing missed until missed number equals to k that means this is the case missed number and this is the we can keep incrementing result while we increment missed right and when the for loop doesn't hold anymore we can just break out because that's the case missing number that we need to return so we'll just return result okay all right now we have finished iterating through this given for loop this given input array is that all no there is one more case that we need to handle which is this is the for loop okay which is this case right so if like say one two three all of the first three numbers they are all there we're not missing anything so missed in this case is still zero but the k is two so missed is still way less than k so in that case we need to find the numbers that's beyond the given input arrays range so what will also use a result in that case that's going to be the last number because we are given the input array that's guaranteed in strictly increasing order so what we're going to use the last one as the starting point and the while we can just copy this that's it we can just return copy this and return oops format doesn't look great let's do this all right this is exactly what we need to return the correct result let me just run the code quickly to see if it works judging accept it all right now let me just hit submit and see you all right also accept it and this is one of the solutions that we can use this is just going through this array once on and we don't use any extra memory of course you can use a hash set but it's a different way and it's using oh an extra memory which is really not needed so these are the three different cases that we need to think of before we can solve this problem i hope this video helps people understand this problem if that is the case please do me a favor and smash the like button i really appreciate it that's going to help me out tremendously and don't forget to subscribe to my channel as i have accumulated quite a lot of lead code or algorithm or data structures or amazon web services tutorials here on this channel and also please let me know how you guys solve this problem just comment down in the comment section i really appreciate it so hopefully i'll just see you guys in a short few seconds in other videos thanks for watching
Kth Missing Positive Number
diagonal-traverse-ii
Given an array `arr` of positive integers sorted in a **strictly increasing order**, and an integer `k`. Return _the_ `kth` _**positive** integer that is **missing** from this array._ **Example 1:** **Input:** arr = \[2,3,4,7,11\], k = 5 **Output:** 9 **Explanation:** The missing positive integers are \[1,5,6,8,9,10,12,13,...\]. The 5th missing positive integer is 9. **Example 2:** **Input:** arr = \[1,2,3,4\], k = 2 **Output:** 6 **Explanation:** The missing positive integers are \[5,6,7,...\]. The 2nd missing positive integer is 6. **Constraints:** * `1 <= arr.length <= 1000` * `1 <= arr[i] <= 1000` * `1 <= k <= 1000` * `arr[i] < arr[j]` for `1 <= i < j <= arr.length` **Follow up:** Could you solve this problem in less than O(n) complexity?
Notice that numbers with equal sums of row and column indexes belong to the same diagonal. Store them in tuples (sum, row, val), sort them, and then regroup the answer.
Array,Sorting,Heap (Priority Queue)
Medium
null
1,021
foreign see how like this for this opening we have groups but this one single limits overpoint cannot be evaluated so this is empty so yeah so that means you could see here this opens okay then again this opens here it closes so these two are canceled this closes so that will be equal to this X same thing A Plus here open close so here you could remove the outermost parenthesis this will give you and here is so these are now you cannot eliminate any of the biases because they are separate so this is what we need to enter you have to remember parenthesis so with the given question let's have a variable called balance initial answer to zero okay so we start itating through the stream now so first calculate over here so your character is equal to 0.1 Open Bracket character is equal to 0.1 Open Bracket character is equal to 0.1 Open Bracket so if director is check whether the balance is greater than zero is it better than zero no it is next increment the balance wipe and plus so for all the opening let's increase increment increments documents so zero this is one entire thing so you can remove this and this then again we are also incarnate and connect so you can remove this sentence that is what it means so make sure you have the counter over here balance is not better than zeros skip to the next in this case also it's Open Bracket so balance is right so this will be added so again incremental balance because it's an open path next time so here check if here what will do your first balance would be decrement so that will be one foreign that is platform next balance will be in committed to two again here in this case balance will be recommended to 1. next add that to automation because it's a closing bracket valve should be recommended to zero so this is and then add the check whether we need to add that pattern so let's move here type so that will be saying we will repeat it and this won't be added because balance is zero other to repair and last one only added so this is how we sort them so in Java we can use string Builder in C plus so I'll create a string Builder sent foreign next balance equal to zero my initialize so now for character each character in place so since it's the string we need to convert into array so s dot to character and check if calc are equal to open parenthesis then if balance is greater than zero there's a DOT up and off character otherwise after that increment the balance type so else if what if character equal to crucial parenthesis so then we have to recommend the balance first let me balance is greater than zero okay so at last we need to result dot two string so string Builder object is all these are not directly with the string plus C equals you can use so string result initial asset then when the answer is just declined the balance equals the character and subtract it okay success
Remove Outermost Parentheses
distribute-coins-in-binary-tree
A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation. * For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings. A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings. Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings. Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`. **Example 1:** **Input:** s = "(()())(()) " **Output:** "()()() " **Explanation:** The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ". After removing outer parentheses of each part, this is "()() " + "() " = "()()() ". **Example 2:** **Input:** s = "(()())(())(()(())) " **Output:** "()()()()(()) " **Explanation:** The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ". After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ". **Example 3:** **Input:** s = "()() " **Output:** " " **Explanation:** The input string is "()() ", with primitive decomposition "() " + "() ". After removing outer parentheses of each part, this is " " + " " = " ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'('` or `')'`. * `s` is a valid parentheses string.
null
Tree,Depth-First Search,Binary Tree
Medium
863,1008
53
welcome back to the cracking fan YouTube channel today we're going to be solving lead code problem number 53 maximum subarray before we do I just want to ask if you guys could leave a like and a comment on the video because it helps me a lot with the YouTube algorithm and a subscription to the channel really helps me grow alright given an intro to array nums find the subarray which has the largest sum and return its sum all right simple enough let's look at an example let's say we have the input here which is nums equals five four minus one seven and eight so what we could do at a very basic level is literally build all the subarrays so we could just have five on its own four minus one seven eight we could have five and four we could have and remember that they have to be continuous right so we could have four and minus one we could have minus one and seven we could have seven and eight and you get the idea right so we can basically build every single one and it turns out that actually the best subarray is just to sum all the values uh there's nothing that we can do better here it's actually the sub array of five four minus one seven and eight uh because this actually has the sum of 23 and there's no way that we could actually get a better sum here uh other than just summing everything so that's one way we could do it and this would certainly work but because we have to build every single possible combination this is going to be very expensive and not actually what we're looking for ideally we can solve this in one pass which we actually can we just have to be a little bit clever with how we want to approach the problem so what we're going to do is we're going to solve this in a greedy Manner and what we're going to do is we're going to keep track of two variables here so we're going to keep track of our answer which is you know whatever our best solution is and we're also going to keep track of the current sum of the numbers as we go from left to right in the array so in the beginning our answer is going to be uh float minus infinity because obviously we're looking for a maximum here so typically when you initialize your answer you just do it to minus infinity and the same thing for the current sum we can actually just initialize it to float minus infinity and the reason that we actually can't initialize our solution our current sum to zero is because if all the numbers are actually negative then this will actually skew our results and we'd actually never get any sort of sum that's better than zero because it'd all be negative and then we'd actually return zero so that wouldn't be right if there's no zero and all the numbers are negative so that's why the current sum also starts at negative Infinity what we're going to do is we're going to go over each of the numbers piece by piece and basically if the number would improve our sum um then we want to basically add it and we want to be a little bit careful here um with the negative so let's now go over piece by piece so the first number is going to be five right so what we're going to do here is we're gonna check okay is the number that we have five is it greater than our current sum it is because our current sum is currently negative infinity and is that current sum actually uh less than zero it is so we're in the negatives so we definitely just want to take five on its own even if we just took five as its own on its own it would still be a better solution than current sum so we're actually going to overwrite our current sum with the current number which is five and then what we're going to do is now that we've done one iteration through the loop we're actually going to take the maximum here for the answer of 5 and whatever flow Infinity is so obviously 5 is much bigger than negative Infinity so our answer now becomes uh five for the answer right and that's just keeping track of our best solution now we go to four and what we're going to do is we're going to see okay do we want to take four on its own or do we want to add it to whatever our previous value was so since 4 is positive and our sum is also positive then we actually just want to add it to our value we don't want to overwrite anything so we're just going to add this here and we're going to get 9. and again we've now done an extra Loop through so we want to update our answer which is now 9 right because that's the best answer we've had so far so now what we're going to do is we actually so we've done four and now we're going to get to minus one so with minus one this is where things get a bit tricky so obviously minus one is negative and it's not greater than our current sum so we don't want to just take it on its own but the current sum is currently positive so we do have some allowance to actually take um you know this minus one because there might be something after the minus one which actually helps uh get us to you know the optimal solution so we can't just say because this one is negative uh that we just want to you know ignore it and then stop our sub array here because there might be things to the right of it which we actually do want to take and remember the sub array has to be continuous so we can't just take the five and the four ignore the one and then take the seven the eight we either take them all or we take them in pieces so at this point what we want to do is we're going to say okay well I'm going to accept the minus one and that's fine so I'm going to actually add it to my current sum so it now decreases to 8. we take a maximum between our current sum the 8 and the 9 and we'll see that okay we actually haven't improved our Solution on this iteration but that's fine we still know that even if taking this was a mistake we've still accounted for the fact that we could have had a nine here and that will be stored in our answer so it's fine if we end up having negatives in the rest of the array we'll still have our answer as nine and we won't be overriding it because current sum will actually keep getting smaller hopefully that makes sense so now we get to the seven and obviously seven is positive and we want to add that to our solution so now we're going to be at 15 right so 15 is now our new best solution so we update that and as you can see right we took the minus one in hopes that something to the right of it will actually you know we'll be able to add to our original solution here that we had and now we've reached a new higher solution so now we're at 15 uh we get to 8 obviously 8 is positive so we want to take it because it won't cost us anything so we now get 23. and then we can update our new best solution with 23 which is actually the final solution because 8 is the last number so that is what we would want to return 23. so that's essentially the algorithm we're going to go from left to right and we're going to check is our current number uh greater than the current sum so the reason that we want to check this is because we could actually be adding negative values and you know if the current sum is negative and we get a value that's positive and also greater than well by definition all positives are greater than a negative but if our current sum is negative or the current number is actually um really small there could be a case that we actually just want to take um that number on its own to just be the new sub array because a single element say it was like 10 billion that could be so big that it's actually the best subarray just by itself so if that number is greater than our current sum and the current sum is actually negative then we always want to just take that number on its own otherwise we're just going to take the number and add it to whatever the sum is and then at the end of each iteration we're just going to take the maximum of the current sum and whatever best answer we've seen so far and then at the end we simply just want to return that maximum again and the reason for this is um we essentially just want to take the maximum at the end so let's now go to the code editor and actually type this up it's not that many lines of code it's relatively simple let's see how we're going to implement it the code editor let's type this up like I said the problem is actually really easy so we're going to say that our maximum sum or whatever the answer is going to equal to the current sum and remember we set these both equal to negative Infinity right now what we want to do is we want to go through each number in our numbers and basically check whether or not we want to add it to our result or we want to take it on its own in the case that the current result is actually negative um so we're going to say 4 num in nums we're going to say if the current number is actually greater than our current sum and the current sum is actually less than zero then we want to actually just take the number on its own right so we're going to say curse sum equals num and this is the K this is what we want to do when cursum is actually negative right if our current sum was like minus 10 but then we got a value that was actually like 20 then it doesn't matter what happened before 20 is already larger than everything up until that point so we don't care about any of that so we can just take 20 on its own because it's much bigger than the current sum up until that point so we can just ignore it and basically just chop it out and now take 20 as our current sum because we don't want to worry about everything to the left because it might actually decrease our solution so that is the basically the only case where we um you know Set current sum equal to the number is when the current number is greater than our sum and the current sum is actually less than zero so basically if the current sum is negative then that's what we want to do so otherwise remember that we just say current sum we're going to add whatever the number is to it and then right before we go to the next number we just want to say the new maximum sum is going to be the max of whatever the old maximum was and whatever the current sum is and we'll check this out every single time we go through the actual um uh each number here and at the end once the for Loop ends all we need to Simply do is return the max sum so let's just run this real quick no syntax errors perfect now let's double check that this actually gets accepted and it does all right cool solution accepted what is the time and space complexity here well time complexity this one's pretty straightforward all we do is iterate over all of the numbers in numbers and all we do is basically either we're just setting a value or adding a value and taking a maximum so all of those operations are Big O of one and we do them n times so that's going to be a big O of n uh run time and then for the space as you can see we don't actually use any extra space we have two variables here but they're just um you know they're just storing values they're not any extra data structures so it's actually going to be bigger of one in the space so that is how you solve maximum subarray really good classic leak code problem I think this is called cadain's algorithm if I'm not mistaken um although I could be mistaken I don't know I believe it was cadains anyway that doesn't matter if you enjoyed the video leave a like and a comment it really helps me out with the YouTube algorithm seriously you can leave whatever you want in the comments section as long as it doesn't get flagged by Google you're good to go if you want to see more content like this subscribe to the channel if you want to join a Discord Community with like-minded people where you can talk like-minded people where you can talk like-minded people where you can talk about Lee code prepping for interviews system design you can have your resume reviewed you can get referrals if that sounds interesting to you then join the Discord I'll leave a link in the description below otherwise thank you so much for watching and I'll see you in the next one
Maximum Subarray
maximum-subarray
Given an integer array `nums`, find the subarray with the largest sum, and return _its sum_. **Example 1:** **Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\] **Output:** 6 **Explanation:** The subarray \[4,-1,2,1\] has the largest sum 6. **Example 2:** **Input:** nums = \[1\] **Output:** 1 **Explanation:** The subarray \[1\] has the largest sum 1. **Example 3:** **Input:** nums = \[5,4,-1,7,8\] **Output:** 23 **Explanation:** The subarray \[5,4,-1,7,8\] has the largest sum 23. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` **Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.
null
Array,Divide and Conquer,Dynamic Programming
Easy
121,152,697,1020,1849,1893
108
hello everyone and welcome back to another video so today we're going to be throwing the leak good question convert sorted area to a binary search tree okay so let's start off with what exactly a binary search tree is so it's a tree based data structure and the way it works is that given a certain root it's left subtree all of the values in the left subtree of the root is going to be smaller than the value of the root itself in the same way all of the values in the right subtree of the root is going to be greater than the root itself so a quick example over here is zero so everything to the left of zero is less than zero so negative three negative ten the same way everything so right of zero nine and five are also are greater than zero right the same way you can also look at the number nine itself so at nine over here the value to the left of it is five which is less than nine so keeping this in mind we need to uh we're going to be given a sorted array and we want to convert it to a binary search tree now one small thing over here is that we can take anything as the root so we could take negative 10 as the root and we would still have a valid binary search tree but over here they want a height balanced binary search tree and what that means is that the depth of the two sub trees uh of every node never differs more than one okay so for example over here they are both subtree so the left suffering has a length of two and so is the right subtree so how exactly do we get a binary search tree with equal length or almost equal length and the way to do that is really simple we just take the middle value directly and the reason for that is our array is already sorted from smallest to largest so we can just directly take whatever the middle value is so in this case the value is zero so now that we have the middle value everything to the left of it is going to be part of the left subtree and everything to the right is going to be part of the right subtree so all we need to do is we just keep recursively doing that so now we get the middle of everything left then we give the middle of that and so on and so forth so let me just show you a quick example and then we'll write the code for this okay so let's just say we're given this array um and it is sorted and it has so the values are one two three four five six seven so what is the first step so the first step is we find the middle of the current area that we're working with okay so how do we do that um so just for the ease of it i'm just gonna write the index values as well all right so everything in green is the index value so the middle is going to be in this case zero and six so zero plus six divided by two which is well three so the third index is our middle so what that tells us is that the four is going to be the root node okay so i'm going to draw it down for now okay 4 is going to be the root note now we're going to kind of split it up into two smaller problems now what we're going to do is we're going to have a left subtree and a right subtree from 4. now what are the values that are going to be on the left subtree so the way we get this is everything to the left of the four since it is smaller is going to be part of the left subtree so over here the numbers we're working with are going to be 1 2 and 3. and on the right subtree it's going to be all the values to the right of 4 since those values are greater than it so that would be 5 6 and 7. so 5 comma 6 comma 7. okay so for the left subtree let's just continue on we only care about one two and three so now we find its middle value and what is the middle value here it's two and that becomes the root and now we further have this into its left and right subtree so what is going to be in the left so on the left of two there's only one value which is one so one is less than two in other words so that's going to be our array and now to the right of two we have three so that's the only value that's going to be considered so now let's do the same thing with five six and seven so the value here is going to be whatever is in the middle which in this case is six so we have six and now we further divide it into the left part and the right part so the right part here is going to be whatever's on the right of 6 so just 7 and the same for the left part so it's just going to be 5 the left of 6 right and now in this case there's just one value for each thing so that's going to be the root itself right so this is going to be 1 3 5 and 7. so this over here is our binary search tree and in this case they both have the same height so in this and the reason that worked out is because we have an even sorry an odd number of a length of numbers right and if we and that's why we had a perfect middle point over here now when we have an even number length of nums and in that case the height might differ by one and uh by the definition that is completely okay so keeping that in mind let's now look at the code for this and i just want you to notice how each time the array gets smaller and smaller into smaller sections and we just keep finding the middle of that until we reach a size of 9. so essentially the left of one and the right of one is just going to be an empty list right so in that case it's just going to have a value of none on both sides right okay so that's true for all leaf nodes so now let's take a look at the code all right so the first thing we want to do is we want to find out what the middle value or the middle index is and to get that we need to find we can get the length of our array and do integer division by 2. and uh so let's go back to our previous example so over here we had a length of seven and seven divided by two is three point five but since it's integer division it gets rounded down to three okay so now we have our mid index and now we need to create a three node object using this value so the value is nums at the index mid okay and now we're going to make an op a three note object of this so the class is already defined for us so let's just make an object of it so three note and this is going to be the value so value equals to num smith and we're going to store this in a variable called fruit so now we need to find all of its left children and the right children of it or the left and right subtree so we're going to have root left and we're gonna have root top right so what exactly are we doing over here so at each time we find the middle each time and we assign it as a root and find it's left and right so we keep doing this recursively so but over here the values that we're actually considering is going to change so in the beginning we considered all of nums now so let's just go let me just do this so self dot sort area to bsd now the values we consider for the left are going to be everything from the zeroth index up to but not including the mint index so the way we get that is just nums and then up to mid right and now we do the same thing for right but for right we consider everything to the right of min so the indexing gear is going to be whatever is starting at mid plus one up to the ending okay so now we have a left and right to find and now what happens when we reach an ending so what that means is when we reach a leaf what exactly do we do so at this point our the value that we're sending here so nums is actually going to be empty so this is where we have a stopping point so if not num so if nums is empty then in that case we return none okay and this is what we do and at the very ending of this once we're done with making the left subtree and the right subtree we got to return the root itself okay so now let's submit the solution okay sorry so i made a small mistake over here this is supposed to be length of nums not length of array so yeah okay so submit this and as you can see our submission was accepted so thanks a lot for watching and do let me know if you have any questions bye
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
1,727
So in today's video, we are going to solve LID code question number 1727 Largest Sub Matrix with Rearrangements. In this, we have been given a binary matrix whose size will be m cross n and we are allowed to rearrange its columns. We can rearrange the matrix in any order. We have to return the area of ​​the largest return the area of ​​the largest return the area of ​​the largest sub matrix in which every element of the sub matrix is ​​one. After of the sub matrix is ​​one. After of the sub matrix is ​​one. After reordering the columns optimally, this means that as we have this The matrix is ​​001 111 101. If we matrix is ​​001 111 101. If we matrix is ​​001 111 101. If we rearrange it like this, that is, move this one to the second index and this one to the third index, then after that it will happen like this and after this here we will get a happen that it will happen like this and after this here we will get a matrix of 2 Batu. We are getting it which we can return. We are going to return its size, so here we will return its area in four measures as we can see in this example also, so let us see its approach to see how we can do it. We are going to solve it, after that we will come and code it, so here we are going to solve it in such a way that we will make a graph like height and here we will store all the heights and here we will have the matrix. Here the location of i is i 012 and along with that is j because we are going to denote our fall loop with a and j so I am using i and j here and then we track one. We will go and write its input in the graph here, like here, if there is zero then no input has come, if there is zero again then nothing has come, in this graph, the index of 'h' which is two, one is coming on it, index of 'h' which is two, one is coming on it, index of 'h' which is two, one is coming on it, then one. This has increased from 1000 to 10000 after that, here again one is one, we are making this graph because it will be easy to find out the area on it and it will be a matrix of one by one, means, this. Once the large array is created, all these values ​​will come here. After this, all these values ​​will come here. After this, all these values ​​will come here. After this, if we want to find the maximum one, then first of all we will have to sort it. To sort it, we can use HTL sort, so we will go here. We will do direct sort and we will return the area which comes here, if it is 2 + 2 or 2/2 then here, if it is 2 + 2 or 2/2 then here, if it is 2 + 2 or 2/2 then 2 * 4 then let's code it once and 2 * 4 then let's code it once and 2 * 4 then let's code it once and see, so here I am going to code it. First of all, let's take two integers for m cross n. Int m is the size of the matrix dot size and a is the size of any row of the matrix. So here we take the matrix of zero only, row dot size, after that we will create a variable to store the answer. By doing the answer or first of all we need the height vector, so we will use the height. Let's make a vector of vector n, height of n type, we will have int, here we will have height, whatever will be the initial size, we will treat it with zero so that no error comes later. After that we will do the complete traverse and see for in a e 0 a less a pps for in z e 0 j less a z ps plus after that we will check that if it is zero then there will be no increment in height if one If it is then there will be an increment in the height. Means if the matrix of i of Otherwise, if this does not happen, then our height will be equal to z plus equal to two, the meat will be added to it and here we have value zero and n, so we can directly add another vector on y. To keep it sorted height, we create a vector of type int, let's assume its name is int sorted height, in this we give our height vector, after that we will sort it, taking the help of L, so it is sorted H dot. This will sort our array from the beginning to the sorted high end, then create a variable named J, take J 0 J, we will see it in the same row or if it is a single row, then we can take any size in the answer. What we will do is check the max off which is our current answer or which is our sorted height into n mine. If you understand this then I would recommend that you dry run it a couple of times and see the code. You will understand the lines well, so let's run it once and see, here it is saying that the answer is not clear, so we will clear the answer here, so here are our three cases. If it has been accepted, let's submit it. There is a small error coming here. If you look at it, the small error was that we have to do this shortened height thing inside this loop itself, so here we After submitting this, you recheck the code once and see that it is complete, after that submit it, then all our cases have been accepted here. Thanks for watching, see you in the next video [ see you in the next video [ see you in the next video
Largest Submatrix With Rearrangements
cat-and-mouse-ii
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._ **Example 1:** **Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\] **Output:** 4 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. **Example 2:** **Input:** matrix = \[\[1,0,1,0,1\]\] **Output:** 3 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. **Example 3:** **Input:** matrix = \[\[1,1,0\],\[1,0,1\]\] **Output:** 2 **Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m * n <= 105` * `matrix[i][j]` is either `0` or `1`.
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
805,949
93
hello guys welcome to deep codes and in today's video we will discuss record question 93 that says restore IP address so here we are given one uh IP address in the form of string and we need to restore it by putting some Dots here so let's see the question uh this is the definition of valid IP address that says the four integers separated by single dots each integer is between 0 to 255 inclusive and cannot have reading zero so uh this and these are valid IP address because there are four integers in them further each integer is the inverting 0 to 255 and no number has leading zeros that means uh nothing like zero one so this two unvalid IP address and uh the other examples are like this because here we have a leading zero and here we have three one two that is out of the range and here we have characterization characters so these are the definitions of invalid IP address so here we are given a string as that contains only digits and we need to return all possible valid IP address that can be formed by inserting dots into it so we have to insert this thought between some of the numbers such that the output is a valid IP address okay and we are not allowed to reorder or remove any digits so we cannot remove any of the digits or we cannot change the order of cases as well and we you may return value address in any order you can return the answer in any order the order doesn't matter so let us take a look at the first example so here we are given this string so the first possible way to put dot is between two this 255 here then second here then here so we've kept dots at these three places and thus we divided this string into four integers and yes all the integers array are in the range 0 to 255 and there is no leading zeros between any of the integers so this is a valid IB address similarly this is also a valid IP address um that's why uh these two both are around so no other possible when it IP address can be formed here further if you take a look at this example then only possible valid IP address is this because there are only four characters uh so we again we can just insert the dot between them for your one zero two three these are the all five different valid IP address starting from here then this one then this and this so basically to insert a DOT we need to take some decision right uh let me show you if this type of string you have given let's say this is the string one two three four five this is a string and to make it a IP address what you can do you can insert like you do like one dot 2.3.45 or what you can do one two Dot 2.3.45 or what you can do one two Dot 2.3.45 or what you can do one two Dot 3.4.5 3.4.5 3.4.5 or you can do one dot two three dot four dot five so these are uh all the possible valid IP address that can be found from the given string so what we are doing we are just basically making uh or inserting a dots between them so what we are doing here we are making choices or decision so we are making a choice right so whenever we are making a choice uh this intuition will help us to deduct approach that we can backtrack or recurs so whenever we make made any bad choice then what we would do better good choice then we will form answer so this is how we would approach this question since we are basically making a choice of where to insert n dots now the next thing to note here is uh we only need uh four segments right four segments like this is the first segment this is the second segment this is the third and this is the fourth segment we only need four segment in each segment uh what we need to check that uh all the numbers in the segment are in the range zero to 255 and uh no leading zeros okay and we if there are three segments or five segment then it is not a valid answer and we won't store it so we won't store it in our answer variable got it so we need to form four segment in each segment we have to satisfy these two condition and further let's say we have currently we have segment this one two three and it is empty here uh so now the next character is four that we have to insert so to insert for we have two choices that either do insert 4 in this uh last segment or to insert for in by following a new segment so what are the two possible choices here is one two three four and one two three and four so these are the two possible choices that we are making either to insert the element in the last segment or to insert in the new segment so if you insert in the last segment and also it is valid because it is less than equal to 255 and if you make a new segment and also it is valid because total segments here are less than four it's total segment is less than four that's why we can make a new segment here correct so these two are valid uh choices that we can make if we have this is the current state and if you want to insert a new uh element got it so based on all these conditions what we will do we will make a choice graph or a decision ring now let me show you here so what we have string 1 2 3 4 5 yes so talking about the character one what you have the choice do you have to can you insert in the plus segment no that is only that is and the current segment is empty initially we have the segment SM team so what we will do we will make uh means one new segment inside this uh Vector of segments so what we do we made segment one got it now for uh character two we have two choices here the insert in original or make new segment so if you insert it original you have like this one two and if you insert a new make a new segment you have like one comma two got it now talking about three fourthly you again have two choices original new so if you insert here then it would become one two three and here it would become one two comma three and here also same two choices in original or new so if you insert this into original then it will become two three and here it would be 1 comma 2 comma three not talking about four so for the four also you have two choices one two three four and one two three comma four same as your 1 2 comma three four one two comma three comma four same as your one comma two three comma four sorry here uh the original and here one two three comma four and you're also same one two three four and one two three and four uh see guys one thing we missed here that one two three four uh we can't form so we would play here we would return because this is greater than 255 and that is not well all other segments are less than equal to what less than equal to 255 so we would return here so this one form okay not talking about this last element five so here we would return so no uh possible and secondary form here so let us take a file look at Phi here in one would be one two three comma four five insert 18 is original now making a new segment from here four from five here are also two possible answer one two three four five and one two three four and we make a new segment five so similarly here also two different answer possible like one two three comma four five one two three comma four comma five same as zero it will be one two three four five one two three four comma five same as your one two three four five and one two three four comma five okay we make one mistake here the thing was that two three and four were connected so it would be one two three four five and this would be wrong because two three four five is greater than two fifty five okay and here it would be 234 comma five so this is okay two three four comma five this one this is not okay but this is okay now moving ahead to this it would be one two three four five and another possible answer from here is one two three four comma five and here it would be one two three comma four five India one two three see one two three four and making new second five but this is also not possible because the size is greater than four so we would exclude this so this is the complete decision three we made by adding each element to either the original segment or the new segment and whenever any other condition like this or this is violated we will stop we would stop it won't make any further answer and also if we have total number of segments greater than four then also we would stop so this was the complete decision tree and formed a decision tree what we would do we would select all the segment that would be of size four you would select this then these uh then this uh and this so all those segments which are of size four we would select and we would return as our answer because the in inner segment are valid because we would uh check if the inner segment is valid or not already and by and before adding transom you would say you check if the segment size is greater than that means if it is equal to 4 or not if it is less than four or greater than four we won't add it to our answer like this is a size of three one that is this is the size of 5V Bond and this we will only add the segment size of four to our answer so I hope you guys understood the intuition behind this equation and as well as the approach of how we would be solving this question so since we have discussed this decision tree what we would do we would recurse and backtrack so uh where backtracking is possible anywhere where we are making a choices original and new so we have two if condition here to satisfy and also we need word function to check whether if we include one element here let's say one two three and if you include four then is one two three four a valid segment so we will write one function valid is a valid segment to check if a segment is valid or not so I hope you guys understood the complete approach here now let's move on to the coding part and we will code this complete thing okay let me first uh start with making one answer variable let me initialize it globally now for each segment we would check uh these valid by passing a string off as so we have to do this and another thing is we have to call this function vector what we would do we would pass the given string and the index I and further Vector of segments that are vector of string and a j pointer to point inside this segment so these two things we have to code and from here what we would do we would simply make one Vector of string that is stamped we would call this backtrack function as zero temp and chain and in the end we would simply return this answer variable okay what would be our base condition so what this condition is when I reaches to the end of string when I equals to s dot size that is the end of string then we will do something okay and in the L and uh we would do something and simply return cut it and now here we would have uh two type of string original segment and new segment so these are the two string that we have where we have to process the style segment and these are the conditions and we would do so now before that let's first score this is valid function So based on this condition that it must the all the numbers must lie between 0 to 255 and there must not be any leading zeros so we will code here so first thing if s of 0 equals to 0 that means there is a leading zero and end s dot size is greater than 1 means see if you have only one zero then the first or the leading zero is true but if you have any number like this after the first zero then it is not a valid condition so here we would return false also that is one situation where if s dot size equals to zero means there is uh no elements in the segment then also it is not a valid segment okay you need to have some elements ranging between 0 to 255 got it so now let me code for this condition that if s of 0 equals to 0 and s dot size equals to 1. if this is the situation we would simply return true I have this is for the condition for this and now let me initialize one number variable and what we would do we would convert this stream as to the number let's say if it is a string of two five then we would convert into the number 255. and we need to do this with the help of low we can't use uh sdoi because you can have some spatial character like this at the rate in some of the test cases where we would fail our code would fail so to handle this what we would do we would run a follow for integer I equal to 0 up till size of s uh we would take one n equals to S of I minus 0 character 0 so this will convert a character number to integer using by browsing is ASCII value if n is greater than equal to 0 and then n is less than equal to 9 that means it is uh part of the digit and not any last Cube and not in any spatial character like this so if it is a very in the range then what we do we would simply add to our num and before that what we would also multiply num by 10 so that we can form like this way so because initially let's say for 255 string what we were to where what we are doing is initially we are adding two then to add five we need to do 20 plus 5 and then to add again the last five we need to add 250 plus 5 that's thus every time we are multiplying by 10 so this is the logical and if Norm is greater than equal to 0 and now is less than equal to 255 then we would return true in the last condition we would return false also here if the digit is not in the range we would simply return false that means we have occurred any characters that is not between 0 to 9. so this was the is valid function where we have validated if the segment is valid or not now we are uh the original segment and the new segment what is the original segment that is the segment at J th position this will denote the last segment and the new segment is equal to S of I because we are starting a new segment from the ith digit of this string s now if first we will check if it is possible to add the character in the original segment if original segment plus s of I and this is valid is valued so we call this function is valid and pass this string if this is the case what we can do is we can insert this uh because we can update the original segment that is the original segment is size of chain equal to what we can simply add the ID character and we would call this function backtrack by passing I plus 1 as I plus 1 segment and G and also now we will write the back backtracking step that we would again update s of J to this original segment got it okay this is one thing now if original segment dot size is greater than zero so that means that we have some element in the original segment so that we can now form a new segment as well in this situation so here what we can do is we would call again call this is valid function and what we will pass new segment this and if a new segment is also valid and segment dot size is less than 4 because if there are already four segment then we can't form a new segment right so if the segment size is less than 4 and if it is a new segment where any if and the new segment is a very segment and also that is the last segment has a size greater than zero then what we can form a new segment what we will do segment Dot pushback new segment and we would again call this vectric function as I plus 1 segment error and J Plus 1. J plus 1 because we have added one new segment so here we didn't delete that because we just updated the original segment and now we would uh write the back trick from uh metric code that is segment dot pop back that means we are just removing the last edit segment got it none of this condition passing we would simply return okay so I hope you guys understood that here now let us store uh this value of all the segments in our answer now we've let first check if segment dot size equals to four then let us take one temporary string and what we would do we would Traverse this segment then 4 I plus 10 plus equal to segment of scale instead of Phi I will take K variable here because we are already using I here and if K not equal to 3 then what we do we would also add one dot for this IP got it this is what we are adding and in the end we would push this temporary variable into our answer okay now I think everything looks good so let us try to now run our solution okay it will be temp and here it would be zero because there is no G initialized okay so initially there is nothing in the temp and so we would uh push back on empty string so wherever so because here we are using original segment like the segment of J but there is segment is empty here it is nerve so to handle that we are just pushing one a null string here so that we get something as the original segment it would be dirt okay all the test cases are passed now let us try to submit this so yeah our code got accepted and it is based it is uh see the approach building this approaching the intuition was more important here and then after coding this it was easy part so I hope you guys understood the approach as well as uh the code here and if you have still any doubts then do let me in the comment section and now guys talking about the time complex setting the time complexity here for this type of solution is m to the power n because where m is the total number of characters in a segment and uh n is the number of segment ah m to the power n into n times but here as you can see here m is uh it is fixed like it can be 0 1 2 and 3 because we have the numbers between 130 to 255 and N equal to 4 because we only have 4 segment so this turns down to time complexity of because of one so similarly the space complexity is also big of one as the number of combination possible here are fixed or we can say the maximum number of cognition possible here are fixed because if that is if we have very long string of let's say but what is the maximum length of string you can uh waveform that is valid that would be three that means all four segments are of size three that would be 12 and beyond that Beyond this it won't be a valid segment oh and if it is not a valid cycle what we are doing we are simply returning and we were not checking ahead so that's why the time complexity this and um it boils down to bigger fun and uh yeah that's the time and space complexity so I hope you guys understood the question as well as the solution and that's all for this video make sure you like this video And subscribe to our Channel thank you
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
36
A house today will see ali problem on electric loco shed qualities eclipse business determine weather all these people and lucky number today these celebs will see number repeat problem and boxes for kids in the giver number is a date of big movies carefully replace 538 Minute and always Chandrasen columns of his CD public evening problems with a view to temples the police tried to solve stop on this that person this precious gem you aisi ye sunnat har ek taraf rosh columns and box right fennel the processes remains a that normal Call that on Hello friends Anand Hospital little by little a ok now a notice to pressure leaf illuminated call he barial and asirgarh so that very including level illumination most matrix in physical to draw 2006 oak the water will oo will right hydrate reaching Christ IS Courtesy Roadways Bus Stand Thak Hi Plus MP3 Dhwaj Kulis Rose Bachchan C Z Plus To That Waterloo The First Appeals To The Character Of That Chapter Something But Budha I N G O Do These Days Till What Is The Reason Current Shilpi Ki Statue Moti Kul To- In the to do list, Ki Statue Moti Kul To- In the to do list, Ki Statue Moti Kul To- In the to do list, take that from the plant and Ajay is actually given some condition. Doctor number, Churna, repeat, Kinnar, Officer, Columns, Fury, Lesnar vs 100, Gillu, Kisan, 200, Five, 600, Gruesome, that's okay, some A+ grade, one, zero, pinpoint, meeting, do it. A+ grade, one, zero, pinpoint, meeting, do it. A+ grade, one, zero, pinpoint, meeting, do it. Is The First Ingredient Right Subha For Implementing Dal You Will Regret 101 Inspirational Treated For Example Princess And Column0 Gram Win Election 2018 By This Incremented 212 And Then We To Garbha Indicum To This Channel Ven Vitamin C Mein Dal You For Improvement In All The Great 102 Call idiots and have and that's why column intermediate college two that this great 1004 due to which rage in the comment box 00000 subscribe loop vibes pe me plus job medicated that's why also arrange roll number three point nothing but wow traveler update column Ustad Ahmed 0010 Element Lions Gold Awards List For Example 720 Prove Beneficial Kunwar Dustbin First Wash Handed Loot 7 To Its Form Number 40000 For Length 100 Gillu This Singh Us Form 2013 Settings Zero Inki 350 Plus Five Trees Nothing But Way Trish Nothing But One Should They Not Being hindu box-1 even today nine coastal ok to Being hindu box-1 even today nine coastal ok to Being hindu box-1 even today nine coastal ok to 244 393 plus job also t&amp; 244 393 plus job also t&amp; 244 393 plus job also t&amp; cha plus police before enrollment application regret 102 days travel at nh-1 application regret 102 days travel at nh-1 application regret 102 days travel at nh-1 turn off bluetooth settings take laundry on sites main source of condition or more cold officer Member of Problem Regulations Dip Developed Notes In Condition Face to Face Loot Flat Remove Recent Items Tow Do Loot Because Happened Were Cutter Admit Submitted On That Your Morning Fruits Problem Carefully Amazing Cream Kshatriya of Maths 254 Rose Columns and Spots in Services Tried to solve singer single fix ok now plane mode of birth has been placed basically it has been removed from Singh to Bigg Boss and duplicate used to dredge was soft can find weather the defeated fennel and educated person is present between the opposition that it has happened that your tomorrow Albert 2nd place of this cast distinctions he drew can olympus phimosis white co tissue lion colleague differnet rose school spring boxes for the spot billu volume setting intersect tips device formula for the robot pilu director principal fixed space phone call girls what will oo happen E Will Have The Nice Print First Found Inside Turn Off Here Boxes Bill Yes This Below Stream A Plus Seeing Actor Plus Ministry Will Be Clear Once Chief Proctor Pro Vs Wild In Different From What Will U 888 Prince's Sketch Pencil Art For Different Sil That zulf style Nandish loot edge of one's day board of mid-day juice is ok so pimple computer ko system do something but this 10 province to share plus to meet you a missed call on January 10 near that police famous fennel where in Setting do first date only 2018 the planet 0share flop actor karan character certificate file ok and column similar what will oo will cause some respect oo that this series is first a plus main apni practice na a pappu ji this withdrawal per column on a plus closing Balance is ok then problem happened when write for seven more five ok columbus more changes then they lymphatic like this cream and sunny don't 707 quarter file that on this problem a pattern ron paul and call 222 extremely winters deposit and different points button comment sir miles - So points button comment sir miles - So points button comment sir miles - So similarly for boxers and dustbin box nothing but an e-mail juice past three years the e-mail juice past three years the e-mail juice past three years the Indian media is to find which talks to please Ajay ko loot 23 2013 bhi kuch banta hai ki show par box to pattern bhi like oo for 800 Phone bill one a 10 days per loot acid witch element that in BJP 30 2010 and Anshu election to other to partner crore for its ok then after this on thick and different area row column in the box to connect with just few small take care start side The problem is that it is not equal to short and work, the problem is loot start and stop, Hindu society is looted MP3 for that these two are in 10 Bigg Boss, so this is not one but will definitely not be good. Vid oo that it should be on the apps, the mode should be turned on that a ok on the meeting good care should be strengthened so let's remove 10 but it was transcoded so ok turn off the phone on the meeting let me take a soft copy of this food AF YNJ Hai ki Vice Chancellor Dr and Is Ghanti Nigam Limited Service's Light Shutdown Loot Committee Score Ki Kya Dashrath Box Ki Like This Video Please Subscribe Falgun Channel Friends Pet and Comment Section 16 2009 Videos Times Points
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
336
today we're gonna work and today we're gonna working on it quote question number 336 palindrome pairs and given a list of unique words written all the pairs of the distinct indices i j in the given list so that the concatenation of the two words of i and vertex j is appalling room so over here the answer is 0 1 0 3 2 4 because it's gonna be combined uh with this one it's one is gonna be combined with this one and this is gonna be a palindrome abcd and then dcba so that is one of the answers and the other one is one zero if you do dcba with the abcd that is also going to be a palindrome three two which is s l s which is gonna be a palindrome and two four which is l lls and then sssl there is going to be a palindrome for this one we're going to be using the try uh model and we're going to be defining a try class and searching uh the try data structure really does really good uh when we are actually searching the uh searching the characters in a string so let's just define that class first so it's going to be a private uh private static class called try uh we're gonna have a few things here what is the next one that would be a tri node uh so actually this tri class is going to be a try not to so try node is going to be we're going to have an array of that so we'll call it next then the current index where we are and then a list of like integers because this is because uh we're gonna have a different one try node we're gonna be starting with that one but then what is the like the whole uh characters of the uh of the integer representation of the characters in the string we're gonna keep the record of that uh so for that we're gonna need list of integer let's call it list and we're gonna initialize it or the constructor is to have a tri node uh the next is gonna just become equal to uh new trinomial new trinode uh 26 because there are 26 lowercase english characters and then we're going to have our starting index is going to be -1 starting index is going to be -1 starting index is going to be -1 meaning we don't know what's the first character of this tri note and the list is just going to be a new array list okay the two things like in the palindrome here in the function what we're going to be doing is like let's create the result which would be just like list of integer uh result is equal to new arraylist okay and then we're gonna have our trinode root which is gonna be new try a node okay and we're gonna initialize it then we're gonna do basically two things first of all we're gonna create the we're going to take a word and put it in like create the like populate the tri node so for that we're going to say and i is equal to 0 is less than the words dot length i plus so for this one we're going to call a helper function called add word we're adding this the new word inside the root and that would be words of i uh and we want to know the index of that too once we're done constructing or popularing uh this um string information into this tri node and data structure uh we're gonna search for it for that we're gonna say enter is equal to zero is less than the words or length i plus we're going to be saying search and then the words and then the current index the trinode root and the result which is basically gonna get populated after the searching operation and then we're gonna be returning the result so the last two things we need to do is like to define this add function add word function and uh the search function right yeah and in our case the search is gonna be the one which is gonna be calling the uh the palindro like checking a function which is gonna check the if the uh if they were if the string is a palindrome or not okay let's get to this uh private uh void adwords okay it takes try node root a string word and an index okay uh what it does is like it goes through uh the length of the string i is equal to word dot length i is greater than equal to zero i negative okay one other thing is that we're gonna start with the length minus one so that yeah we are inbound okay uh so let's see what is the current character for that we're gonna say uh actually the current character represents an integer representation so that would be is equal to uh that word dot character at i minus a okay so uh once you have the current integer representation of the current character uh we want to say that the roots that's the root next is null for that uh integer representation of that character is null or not so we're gonna say that if the root dot next at j is equal to null we're gonna create a new one at that um index root dot next add j it's gonna be a uh new trinode okay otherwise or even once we are done with that now we want to check that if it is a parent room or not if we're gonna use a helper function here as uh the way we're going to be checking it out is like sending the uh the word uh that like where exactly you wanna start and go up to so that it would be uh zero to i so that would be the starting and the uh ending a one so that is appalling drone from zero to i uh we're going to say root dot list dot add that index you can add that index and then we're going to go to the next one root is equal to root dot next edge right once we are done with this for loop basically we are done processing that like adding that word but we still need to add that uh like index like we're gonna update the index so that would be root dot list dot add index and then the root dot index is gonna be equal to that index the last thing we want to do is to define the search function private world search which does take a array of strings of let's call it words and i uh that would be the uh like where exactly we are uh so this is because uh when we were calling the search uh function we were telling him like where should you start looking for uh looking at like at what index you should start looking at uh for this uh word and then the try node root and the last thing we want to fill up is the list of integer list of integers and this is the result once we are done searching for that so again our j is gonna start from zero and it's gonna go to like uh so which string we are looking for so basically we are looking for words of i that is the particular string we are looking for and then dot length so the j is going to go up to this length j is less than dot length and then j plus okay and so now we want to make sure because we wanna be adding uh this uh we wanna be adding that uh like the root is basically a tri node but we wanna take the like we wanna change it to uh list and then we want to add it if uh basically there are a few conditions are meeting if first thing is that the root dot index is greater than equal to zero and uh the index and the i is not actually equal to the index the root dot index is not equal to i and at the same time this thing is palindrome words of i uh and again as we said that we are sending the that one and we're also sending the limits where you should start looking for and j from j to words uh of i dot length and basically the length of that uh to the end of that length of that string the length because it's a string so it's going to be like that so if there is palindrome we're going to be adding it to the result um but because it's a tri node we're going to say that the array dot as list and then we're going to tell him that it's the i and then the root and dot index and this is because we are not actually adding the string itself into the result we are we just we're just supposed to tell the index like where exactly uh is that occurring like where in the words input where exactly that string is so that's why we just need to add the i and the root.index okay once we're done with that we can update our root just like we did over here yeah so root.next yeah so root.next yeah so root.next is the word uh dot character at j minus a that's what we should look for oh basically that's gonna become our new root and then we're gonna say that if we if the root has become equal to null we can just return root is equal to null you can just return okay and once we are out of this for loop uh what we can do is like uh like inside that root.list that root.list that root.list like whatever is like because root.list like whatever is like because root.list like whatever is like because root.list is the list of integers so i'm gonna say that j inside that root.list root.list root.list okay uh we're gonna say that when it becomes when this uh j becomes equal to i uh you can continue we don't want to do anything otherwise now you're gonna add it to the result dot add it is dot as list and i and then j okay the last thing left is to define this now function called private now we're returning a boolean for that it's called palindrome is palindrome what it does is like it takes a word and a starting point and an ending point so once you have that all you have to check is like while i is less than j and check if we have the same characters and the two locations word dot character at uh i plus is not equal to uh word dot character at j negative and like whenever that happens just return false otherwise once you are done with that you can just return true okay so we have a typo here i think it should be it is same way yeah we're converting only over here and here that looks good okay oh you need to tell him uh you need to tell him like because this is an eddy so that's gonna be this looking good and it works
Palindrome Pairs
palindrome-pairs
You are given a **0-indexed** array of **unique** strings `words`. A **palindrome pair** is a pair of integers `(i, j)` such that: * `0 <= i, j < words.length`, * `i != j`, and * `words[i] + words[j]` (the concatenation of the two strings) is a palindrome. Return _an array of all the **palindrome pairs** of_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\] **Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\] **Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\] **Example 2:** **Input:** words = \[ "bat ", "tab ", "cat "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "battab ", "tabbat "\] **Example 3:** **Input:** words = \[ "a ", " "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "a ", "a "\] **Constraints:** * `1 <= words.length <= 5000` * `0 <= words[i].length <= 300` * `words[i]` consists of lowercase English letters.
null
Array,Hash Table,String,Trie
Hard
5,214,2237
1,923
hey everybody this is larry this is me going with q4 of the weekly contest 248 on lead code longest common sub path so hit the like button hit the subscribe button join me on discord about this farm other contest farms let me know um we actually usually go over you know in chat and discord right after the contest so if you're uh if you're a contest nerd like i am or maybe you just like it uh come hang out anyway today's problem is today's q4 is longest common sub path so this one is a hard problem obviously i spent an hour and 10 minutes on this and not many people solved it right about 122 people maybe a little bit more now um i think the camera's a little bit off but you get the idea not many people solve it um so yeah so there's a couple of thoughts that i thought during the contest and you could watch me solve it live don't obviously fast forward afterwards because it's a long time i actually tried doing some stuff with keeping track of pointers or i even tried doing i tried doing a breakfast search thing where okay i start with the path of length one keep track of everything try to laying for up path of length two and so forth for that was too slow i tried doing that but with uh almost like an a star search if you want to call it that where it built from furthest first but it was still too slow um and you can actually see some of the techniques that i did to kind of test a long test case um something that i actually i wouldn't say i discovered it lately but something that i personally came up with lately of creating long ltle test cases so you can look into that later um maybe i'll even go over it during the con or during the problem explanation as well so those are the things i did the other thing that i meant would mention is that um to me to be honest this was a very obvious suffix tree suffix array problem um if those things don't mean anything to you probably don't worry about it if it's something that you're curious about um definitely read about it's actually very interesting very nerdy i loved it but it's also something that to be honest i have never implemented it in my life optimally um i mean i implemented uh a sort of a suffix of way in another language previously but not optimally so but that said if that's something that you're interested in then you know play around with that um but that just to be clear that like i said i've almost never done in my life it is ridiculously hard um though someone did it i think in the experts like if you look for the other people's solutions um so that people have done it because people have pre-written libraries and i people have pre-written libraries and i people have pre-written libraries and i didn't have a pre-written library i'm didn't have a pre-written library i'm didn't have a pre-written library i'm not going to google someone else's library or something like that so i didn't do it that way um and it took and to be honest if you watch me start with the contest i spent about an hour maybe an hour give or take on the wrong solution and then to be honest at the very end i did something a little bit yellowy um because i thought for an hour that it was the wrong solution that it was going to be too slow but i have to do something tighter about the math because i think the thing is that the sum the key part of the constraint is that the sum of the path is 10 to the fifth so there is some math here that makes it i cannot prove a tight banner on this one um or at least maybe my math is just bad so if you know how to do the proof leave it in the comments below so yeah so basically what i did is binary search so i did a binary search on the answer um and what does that mean that means that okay i ask myself is still an answer of length x right if there's an ends of length x then let's try an answer of length of a longer length right if there's no ends of length x let's try a smaller length that's basically the idea and if you kind of say it that way my computer is a little slow sorry if you say in that way then you can see that if there's an answer of length x then every length of x plus one has to be true right because if for example if there's a path of length five uh oh sorry wait i said that the other way around huh sorry i really mixed it up um okay i meant the other way around uh wow that is really bad actually sorry about that i hope i didn't confuse you but basically if there's a path of length five that means there's always a length path of length four and there's always a path of length 3 and so forth right and if there's no path of length 10 say then there's no path of length 11 and or 12 or 13 right because you can construct that from the paths um directly because if there's a path of link five then obviously in that path of link five it contains the path of link four so basically what that means is that if you look at all possible answers it's gonna look like something like this where okay this there's a path of length x there's a path of link x plus one dot until some other number and then um and then it's not gonna contain that number so t means true f means false it means that okay at certain points x is not going to have a path of length x and then there's no path of x length minus 1 and so forth so then the idea here is okay the only two possibilities of course which means that okay if we're where if we test an x and it's true what does this mean right that means that this well first of all it means that um if this arrow is met then first of all it means that mid is true right or mid is a possible answer and then we want to get rid of everything to the left because we know that we don't care about it anymore because we have we know that if nothing else this is mid is the answer right so okay uh yeah so that goes to my binary search which is that you know if good if mid is good then we set left is equal to mid because in here we have an inclusive range of left uh left right so when left right when left is equal to right then our range is uh contains one number right so that's basically me going explaining binary search a little bit so that explains this while loop if this is good then that means that we can set the left side to mid because left is inclusive or this is an inclusive range and mid is a possible answer if not we know that right is not a possible answer and we set to mid minus one and going back to here if this is a force that means that this is not a right answer and also everything to the right of it is not a right answer and that's why we have a mid minus one and therefore mid i do it add one because so that you can think about it as rounding up because this makes it round down for whatever reason so that's the binary search portion um yeah take some time to kind of understand that part because the next part is probably the harder part um yeah and then the next part is but i there are a couple of ways to do this i think there's um you can use robin cobb you could use kmp but i use robin carp to kind of do fingerprints oh yeah let's actually go over this a little bit as well um so here i chose the so the smallest possible answer is zero the biggest possible answer is the length of this modus path because you cannot have a uh the short shortest path you know you cannot have a long you cannot have a longer common path than the shortest path and keeping in mind that here that i sort the path by its length uh in the beginning i know that i'm jumping a lot sorry about that but yeah but i s i search oh sorry i sort the paths by the shortest path or by the path lengths and then i take the inclusive path to be the length of the shortest path okay and then now going back to the good function so i use robin carp and basically what i do here is that okay here generate fingerprints for length for paths of length target and i'm not going to go over robin kopp that deeply in this video because um it's an interesting algorithm and it's a good algorithm i definitely recommend you go over it but yeah it's going to be a long it's going to be a really long video if i go over that so but basically the idea is that jingle generate fingerprints for path of each length target and this is basically the way to do it you can think about it as actually what we did earlier with my pal um you just basically keep a rowing you hash the substring and then you kind of shift it over by one and then you hash that and so forth if you do it naively it's gonna be really slow but the part about robin carp is that you can kind of think about it as shifting it one digit at a time and then chopping it also one digit at a time and that's basically it um and this is kind of like sliding window as well and then i keep track of all the fingerprints um in the hash set and then now for every other path i go over it as i do i generate fingerprints as well also for length of target uh length target and yeah as soon as this is found we're done because we know that it is good for this path otherwise if it is not found then we return first because that means that not every um not every path has to contain the same thing and basically the reason why i did this fingerprint is so that we can match in all of one time which is this lookup thing if current is an s for every fingerprint we're able to match all possible paths of length target um in over one time so basically s now contains or possible paths of length target and this allows us to um look up all possible paths of length target in o of one so that's basically the idea um yeah and in this case i guess now i could explain this a little bit better in terms of paths so this algorithm um and you can kind of do your math yourself but this is going to be o of one maybe expensive or one but each loop is going to be o of one and this is also going to be o of one right uh or one per character sorry um and of course so that means that this actually takes over m times or not m it's uh this m sum of so this is going to take over sum of path of length times which is less than 10 to the fifth because as you can see for each character we do all of one operations that's basically the short reason why and because we call it this as part of the binary search as we said this is going to be at most log m roughly speaking so right is uh um which is less than 10 to the fifth and because of this oh sorry whoops damn is this oh yeah the right is the thing so the binary search will be o of log m or you know yeah and of course this good function as we said is going to be over sum of half so this is roughly 10 to the fifth oops just to be clear because the sum of the paths right it's not just m because each m could be 10 to the fifth but you can only have one of them or something like that right so that means that this is going to be total time will be o of m log m so that's basically the idea um in terms of space it's also of depending how you want to count it's either of m space or of log m space mostly dominated by this set thing because we have to create it for every binary search but if you want to be we want to say oh we free the memory and then it becomes of m bound every time and when you reuse memory then you know instead of creating a new one then it's off m space but um space is or m like m depend depending how you want to count it but you know that's basically the idea um cool that's all i have for this one i'm gonna make this a little bit smaller so you could see more of it at least you could see this good function the binary search you can also look at it in a second um yeah you could watch me sell for live during the contest next so here's the good function and here's the binary search um oh yeah one more thing is that not gonna lie i googled a large prime and this is just a random i guess this could have been what this maybe could have been applying but it doesn't really matter right um well it didn't matter because i didn't fail but if it failed then maybe it matters but uh but yeah that's all i have for this one let me know what you think hit the like button hit the subscribe button join me on discord um you can watch me stop it live during contest next again it's really long you could kind of skip through it i did the binary search stuff near the end obviously so because if it was earlier then i would have gotten ac earlier um yeah let me know what you think and i will talk to you later bye knew how to do them just dumb about it and this one has how far back am i because no one's gotten this yet so that's actually surprising alex gotten three problems and okay one person got in it alexander i am very sloppy today this is gonna be a mess okay three wrong answers come on larry and there's the number of cities how many paths are there's a lot of pavs of the paths okay hmm oh this is really should have kind of used your palms easier and this is going to pave me now every friend's path there could be a lot of friends okay so the phone has to be in one of these right promise if it goes back and forth then it may be a little bit weird right but that's the hard part is to going back and forth i think if not then this is actually pretty easy well i'm not going to use it easier okay how do i handle that case hmm you smoothie where does this thing go how do i abuse this people are designed to get it you um i guess it should be in order oh no again and the issue is difficult numbers but such a sort of preferred search okay so do me what is end again oh number cities m is the number of points okay i guess technically i didn't need to do this i can just do i don't know if this is going to be fast enough how many people have gotten this so far okay so a bunch of people have a lot of wrong answers too though you foreign so the key is to start okay so me this would be a mess thank you so this is so slow so i don't know what i'm doing so hmm that's odd oh that's because i'm dumb um okay this is a start so two three and four okay no because i break afterwards not just for testing but it's still not working two three and four you process the two we really should get it in here the two doesn't do anything so this is doing nothing so okay so i didn't process this correctly okay so there's some stuff here okay this is just oh because excess not a tupple okay so let's doing something just nothing productive yet that's fine okay this is good maybe it's missing something though i have a plus one here okay so this is probably right but is it gonna be too slow that's the question i guess stuff 45 minutes let's slow it down i've been really sloppy today let's do a test case that probably is not the answer though why is this two for this one oh because i've been pretty well okay um it shouldn't be two dollars in the answer victory maybe i got it wrong now i also isn't this now the sense is not to me but now this answer should be three so i'm getting something wrong so that's just for not getting submitted i guess because this is clearly wrong so let's debug this let's go there's two three we only have six two and six what hm two three the next one is four but i'm getting some weird things why is that don't oh this is silly i copied and pasted this one before but this should be just p this is just pfk good thing i tested this okay so this is good i wish i kept my thing about okay i guess 10 is right it's fine is this fast enough might not be fast enough to be honest no well i mean that was fast enough but really slow well that is a lot of things though that's ten the test case is actually way bigger than the input because of the sum of this thing but is that right though 11. that probably is right i think there was 11 elements i can't okay let's just give it a go hopefully it's fast enough it might not be and that's fine because i'll get a test case for me to kind of yeah it's too slow apparently hopefully they give me the test case oh man they give i don't even get a free test case for five minutes that's kind of sad the sad thing is i think this is fast enough for one test case but not because we did some of these right so times say 10. like this is a upper bound for this and this should be fast enough oh maybe not actually because of the duplicates this one's hard even memory limited exceeded okay well so maybe that isn't even in the test case how would i do this case this is probably one of the worst case though in theory maybe i just do this instead hmm you again the overlapping one was is the issue that i don't know how to do if you have gotten this poop um okay well i'll remove this before i forget it so the tuples are weird can i save this in a more efficient way start so i don't even need this i just need we don't even need to cook oh this isn't this is p okay i can't do it well maybe i did it well okay i mean it's still warm but at least it starts and at least it time limits exceeded the memory exceeded but it's still bad the old ones what is this one oh whoops i knew that pay to win okay so this is right but this is still going to give me the wrong lens or time to exceed it i don't know what to do 50 people got on it but this one is the case where it goes back and forth i don't know if i can optimize my current thing all right let's do a smaller case so i could print it the smallest case is fast yeah that's what i feel this way too much other too many elements in this how do i process this in a smaller way because now this becomes n squared i don't know this would be a good contest to have a good first q3 i guess but i mean that'd be funny if you just needed to do suffix tree or something maybe suffix tree would solve this but i don't really have an implementation out and if it is you know suffix tree is the implementation then that's just uh that's just not gonna be it well like i'm fine with not getting it this is going to be unsquared you poop okay hmm i don't know how to do it at least not without some weird suffix tree stuff to get it done down to constant time i don't really have a self-extreme implementation though maybe this is just a bad streak for me hmm fingers can we skip any of these just in a different order a bit basically how long can this possibly be does this give me the right answer first of all it does why does this not make it faster than okay so this should be faster but why is it not that much faster well this is enough for me to go okay well but to be honest there might be even more but that's not unfortunate even 10 of these is too slow that's a little bit sad actually okay well maybe it's not too slow but it's a little bit i mean it is too slow even with the pruning hmm i just don't have an idea on this one i don't know i'm just pressing running buttons yeah i don't do this one can we binary search on the answer don't think so hmm yeah i mean you can every switch on the ends around it was gonna be fast enough let's do it now because i feel like if that's the case then people would have gotten it much easier but i don't know yeah let's try better than nothing this uh what i just googled it i guess you're wondering don't even have enough time to do it but oh well all right should be okay should be good tough time to test this is gonna be fast enough it's roughly fast enough it's faster that's a silly problem with this is the case off by one maybe oh i got the wrong answer if this is good i only have more time to debug this why am i off by one this is basically all of them except for the last number is it just like another no i still have it wrong so it's not that no it's okay so it's not that but it's not for now why is this i just not do this correctly maybe i just didn't do it correctly 32 is force what is 32 force uh this debugging sucks and last moment so why not can i mess this up how can this be whoa okay so thanks why how are you wrong how do you forbid me now off by one on sliding window okay i actually thought about that while i was doing it but i was just being dumb and forgot we have three minutes to go uh yeah thanks for watching everybody hit the like button to subscribe and join me on discord let me know what you think about this farm uh it was a tough contest so i hope you did well uh yeah stay good stay healthy to good mental health and i will see you later bye
Longest Common Subpath
sentence-similarity-iii
There is a country of `n` cities numbered from `0` to `n - 1`. In this country, there is a road connecting **every pair** of cities. There are `m` friends numbered from `0` to `m - 1` who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city **more than once**, but the same city will not be listed consecutively. Given an integer `n` and a 2D integer array `paths` where `paths[i]` is an integer array representing the path of the `ith` friend, return _the length of the **longest common subpath** that is shared by **every** friend's path, or_ `0` _if there is no common subpath at all_. A **subpath** of a path is a contiguous sequence of cities within that path. **Example 1:** **Input:** n = 5, paths = \[\[0,1,2,3,4\], \[2,3,4\], \[4,0,1,2,3\]\] **Output:** 2 **Explanation:** The longest common subpath is \[2,3\]. **Example 2:** **Input:** n = 3, paths = \[\[0\],\[1\],\[2\]\] **Output:** 0 **Explanation:** There is no common subpath shared by the three paths. **Example 3:** **Input:** n = 5, paths = \[\[0,1,2,3,4\], \[4,3,2,1,0\]\] **Output:** 1 **Explanation:** The possible longest common subpaths are \[0\], \[1\], \[2\], \[3\], and \[4\]. All have a length of 1. **Constraints:** * `1 <= n <= 105` * `m == paths.length` * `2 <= m <= 105` * `sum(paths[i].length) <= 105` * `0 <= paths[i][j] < n` * The same city is not listed multiple times consecutively in `paths[i]`.
One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix.
Array,Two Pointers,String
Medium
null
211
okay welcome back to algae.js today's okay welcome back to algae.js today's okay welcome back to algae.js today's question is leak code 211 design add and search words data structure so we need to design a data structure that supports adding new words and finding if a string matches any previously added string so we need to create word dictionary to initialize the object add word with word as a parameter which adds the word to the data structure and then search passing in word which returns true if any string in the data structure matches the word or false otherwise and if the value in the word is equal to a period This is a wild card so it can be matched to any letter so what data structure do we know where we can search through characters Within A Word in order to find whether a word exists well we have try data structures right and a tri-day try data structures right and a tri-day try data structures right and a tri-day structure has say a root and this branches off to the individual characters so say we had a period we had a we had D at the end of the word there is usually a flag such as is end is equal to true to state that look this value right here this character is the end of this word so if we search afterwards and we're looking for bad this will reach the D and it will return true because we've reached the end of that string so in order to add a word to a Trader structure I'll add a link to the code 208 implementing a try also known as prefix tree where I discuss in detail how to construct a tree here we'll just look at the high level overview right so say we want to add to a try right so our try is initially an object right what we do is we look in this try if we have this first character if we don't we set it to an empty object and then we move over to a and we repeat the process so is a within this triangle so we add it we reach D is D within the try no so we add it and now this is at the end of the word so we can have an is end flag which is equal to True within here this is what a tri data structure looks like and this is how we're going to construct it now the tricky part of this question is when we're going to search through this tri-data structure in order to work this tri-data structure in order to work this tri-data structure in order to work out whether we have a word that matches so our stated in the question if we have a period this is considered as a wild card so this can be matched with any letter so firstly we are going to be using recursion for this and with any type of recursive call we need a base case so something that's going to say look we found our solution or we haven't found the solution so we're going to return this and for this question we have a word say we have bad again the length of this is going to be equal to three right so in our recursive call what we can do is we can pass down an index right so this can be index one two three as you can see we've reached in index of three so we've reached the length of bad if these two are equal so if word.length is equal to the index and is word.length is equal to the index and is word.length is equal to the index and is n flag is set to true this is really important because otherwise it could just be a prefix then we found a result so we can return true so that is the base case we're going to work with the other issue we have is this wild card here so like we said if there is a period this can be matched with any letter so what do we do at this point well the best step is to iterate through the keys at this level right and if any of these Keys return true so if we reach the end and there is an is end flag set to true then this can ultimately return true otherwise say we're looking for dad we're simply going to check within the try at each character as long as they're not equal to null we're going to check and carry on recursing passing in the index the try at that character and the word we're looking for sorry that should be two and if we reach the end where the index is equal to the length of the word and is N5 is equal to true we can return true what happens if we have dado right so in the case of dado we're going to go down this subsection of try we're going to reach D we're going to Traverse further and the value we're looking for is going to be equal to null right and the current way we've constructed this so far this hasn't been checked so before we recurse down we need to make sure that the character within the try doesn't equal not if it does then we just return false so I believe we've covered everything for the solution let's jump in to the code editor and start code now so let's initialize the try right and this is going to be class based so we need to initialize it with this so that we can have access to it within add word and search so that's the first part done in order to add a word it's the same as implementing try the code 208 we're going to have a reference to the try so we're going to say this dot try and then we Loop through the characters the word like we said if node at character is equal to null so if it's not already in the try we create it so node at character is going to be set to an empty object and then we move into it and once we exit this we are at the end of that value within the try so we can add an is n flag here and set that to true that's all we need to do to add word now for search we are going to be using recursion so we can have a container here so we can say this dot we'll call it DFS we're going to pass in the word we're going to pass in the try and we're going to pass in an index of zero and we need to return this so let's copy this paste it up here let's add DFS here let's update the parameters to word try and index let's first add the base case so if word dot length is equal to the index we have found an endpoint so we also need to check whether we have the is N5 here so try dot is end if there is an ism flag we can return true or false and we need to return this then we need to get the character so the character is going to be word at index so that gets us the character now like we said the period is going to be a world card so if the character is equal to a period we have a wild card so we need to look through the keys within the try Okay so let's do that so that key in try if we find a solution when recursing to each of these Keys within this try if we find a solution that is true we need to return true from this so we're going to pass in word we're going to pass in triac key as the next value within the try and we also need to update the index to index plus one and if that returns true then we need to return true else if the character is not a wild card we first need to check whether the character is within the try so like Daddo the O was not within the try so we just return false so here we're going to check so the character in try doesn't equal null then we can carry out the search so we're going to carry out the DFS remember we're using class here so we always need to add this before and we need to pass in Word try a character and index plus one and we need to return this if we have reached this point we can just return false and that recursively cool throughout the entire try and compare it with the word either return true of false and it will be returned here so let's give this a run it's been accepted let's submit it and there you go and as always don't forget to like comment subscribe and I'll see you in the next one
Design Add and Search Words Data Structure
design-add-and-search-words-data-structure
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the `WordDictionary` class: * `WordDictionary()` Initializes the object. * `void addWord(word)` Adds `word` to the data structure, it can be matched later. * `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter. **Example:** **Input** \[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\] \[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\] **Output** \[null,null,null,null,false,true,true,true\] **Explanation** WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord( "bad "); wordDictionary.addWord( "dad "); wordDictionary.addWord( "mad "); wordDictionary.search( "pad "); // return False wordDictionary.search( "bad "); // return True wordDictionary.search( ".ad "); // return True wordDictionary.search( "b.. "); // return True **Constraints:** * `1 <= word.length <= 25` * `word` in `addWord` consists of lowercase English letters. * `word` in `search` consist of `'.'` or lowercase English letters. * There will be at most `2` dots in `word` for `search` queries. * At most `104` calls will be made to `addWord` and `search`.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
String,Depth-First Search,Design,Trie
Medium
208,746
1,630
hello subasi I hope that you guys are doing good in this video we're going to see the problem arithmatic sub arrays we will see both the approaches from the very scratch and again we have seen the exact replication of a question in a live stream also so if you have been watching us regular please try it by yourself first so uh it has been asked by Google itself in last one two years and we'll see okay what the problem says so the problem says that we are having a sequence of numbers is called arithmatic if you have not known there's an arithmatic progression called as AP now it is called arithmatic if it consists of at least two elements and the difference between the every consecutive elements is the same it's just the AP definition that we have two elements more than two elements and the difference between the consecutive elements is actually same which means the sequence would look something like a A plus d A+ 2D A+ 3D and a plus nus 1 d A plus d A+ 2D A+ 3D and a plus nus 1 d A plus d A+ 2D A+ 3D and a plus nus 1 d as you can see the difference is here D here it is again D and until so on every time the difference will remain constant and that's the only Prime condition for an AP which is arithmetic progression now um it's just have given a few examples if you have not known that you can see the first sequence you can see the difference here is two it's AP here is zero here is z here is zero again it's AP here is -4 -4 -4 again it's AP and now here is -4 -4 -4 again it's AP and now here is -4 -4 -4 again it's AP and now in this you will see here is a difference of zero here is a difference of one here is a three here is a two so it should be constant just one so it is not an AP now we are having our an array of n integers so we having an input uh let's say nums and we also have two other arrays of size M which is L and R now this L and R are just a range array which means this m array of length m lnr is just representing I have let's say m queries and for every query I have a range L to R so please just go and find for this range to l to are if that is an AP or not that's the only thing which it has or it wants us to find out cool so again uh one thing which while reading this statement this line itself should come to your mind is shall is it possible for me to actually query which means I have let's say m queries M queries and for every query like he go he says and he will give me a Range L2 R I will go and ask if that is possible to actually get that range l2r so again I should actually ask is it possible for every query I individually go on my input and check for the answer so is it possible to have a roughly of MN or something maybe small k something like that to actually go for every query is find the answer is it possible or not that is if I want to ask me I go and check the constraints m is 500 n is 500 so roughly that is possible M into n for every query I can actually go into my input and check so I don't have to think of very something very smart if something mediocre would also work now ultimately we have to return the list of Boolean elements answer just saying that answer of I is true if the sub array which means from L to r that subarray in nums is actually a arithmetic progression when it is possible to rearrange it so the constraint is that okay I can actually rearrange it we'll see an example we will see by this example itself but yeah it is given that we can actually rearrange it so first very foremost thing as we saw above that we you don't have to think of very something very smart simple thing will also work because we can actually go on to every query and get the answer from every query itself so I know that okay this is my input looking like I know that I have these three queries with me right so for the first query which is from 0 to two I know the elements I have grabbed the elements out from that input are itself for the first query because I know it will work because I know for every query I can actually grab out the entire elements and then work on that like work on these elements so I've grabbed out the elements from 0 to now again to make it as an AP as you saw AP is nothing but it can be increasing it can be also decreasing but you know that okay your elements are rearranged for example in this case if I say okay Arian you know that this AP is decreasing I'll say wait a second I can also make this AP by rearranging as increasing - 9 - 5 - one rearranging as increasing - 9 - 5 - one rearranging as increasing - 9 - 5 - one and 3 so for sure you know that in a AP it is either increasing decreasing or constant so anyway if I just sort this all numbers down so for sure they will be in an order and if I just take one sorting let's say I will just sort increasingly so for sure it will ultimately everything will sort increasingly this also and this also this will help us to maintain that the difference will remain constant as if it is possible to remain constant it will remain constant so with this we can just make one thing sure that I just simply sort this input out which is for the query so what I did here was I just simply have this input 465 I just sorted this out again you can just sort in ascending order or descending order it doesn't matter the Sorting will just help us to place the every element as close to each other as possible so that the difference between them will remain as close to each other as possible which will help us to compute that okay if it is a constant we are good so what we do we sorted four 5 and six you can see the difference is one it is one so ultimately firstly we grabbed all the elements in this range from uh the query L to R which is 0 to two when we have grabbed it we will actually apply the sort function on this grabed input which we have grab for this query when we have applied the S function we will start from I equal to 1 and keep on checking the difference which means I minus one index I'll just keep on checking what is the difference I maintain it as a d and I'll make sure in my entire AR which means for I equal to let's say two uh 2 I equal to 1 I just check okay what's again the difference here and it should match with the initial difference so this difference every time inside the square should remain constant if it is constant ultimately which means if it is same ultimately I can return a true if it at any point of time it is false which means it is different or I get multiple differences it is not an AB for example in this case I got uh input from 0 to three I get I got elements as 4 6 5 9 I simply sorted it down 4 5 69 I get the difference it is one okay I get the difference it is three difference should have been one or I should say it should have remained constant but it changed oh its answer is false simply Mark a return of false in this ultimately for here itself I just have a 2 to five query I just simply sorted it down 357 9 here two okay that's a true return a true simply as we saw above itself we will go on to all of our queries right m queries now for every query I just grab out the output grab out the input itself to actually apply my sorting thing on what input so I'll just go and find okay L2 R just grab out the input in the ARR array now I have the AR array having only l2r elements now I'll just go and check is that L2 R range is actually a AP or not after rearranging that so what I will do is I just simply again as I went on I just simply sorted this stuff out because I know that with sorting I will have every element as close to each other as possible to actually maintain and help a difference thing for me now I'll just firstly get the initial difference and I need to maintain this initial difference up to the very end so I'll just start off with the next elements I'll just go and find the differences of the next elements if it is not equal to the initial difference which I found out which means I have found a new difference which is not possible I should have only one difference in the entire AP so I simply return a false ultimately I try everything I match all the differences with the initial difference ultimately I return a true with this you know that you can simply get this solv again the time will be for every query you're extracting out the entire array as an AR and that you are sorting that AR array so it's O of M into n login and space is O of M because you're extracting out the AR array and that can be of size n ultimately like wor cas so time and space of M into like the is M into n logn and it is n can we optimize it maybe not uh what do you think what you can optimize you can think of one thing okay uh you can extract out the element maybe you can just do inside this range itself maybe you don't need to extract out the element that is one thing you can for optimize that you don't need to extract out the entire AR itself you can just uh check in the input array but although if you will apply the same operation here you might be modifying the input array so but here in this case I will not modify the input array but yeah this is one thing which I can actually optimize that uh if by anyhow I don't modify the input AR but I can just check in my input are itself what is l2r and what are elements in that range maybe I don't need the space extra and also one thing that okay I was just sorting this stuff out right so what if I don't sort this stuff out maybe without sorting itself I can find out because you know that okay it is a sequential thing a A plus d so I know what is the expected Behavior it needs to have so can I replicate that expected behavior let's see so ultimately do we need sorting that was a question because ultimately that was a boiling point for us ultimately we cannot just do some hack or something that we can't we have to go to Every query and for every query I have to go to the entire range itself of that query it can be different I can't just do a pre-computation okay for this part it is pre-computation okay for this part it is pre-computation okay for this part it is this like for example in Spar table and in Victor we have seen that we uh pre-compute some part for the pre-compute some part for the pre-compute some part for the portion of the query we can't do something like this here itself so uh to remove the Sorting we would have to find what should be the output and then we can replicate that in our input itself so we know that okay after sortings the array ultimately looks like a A plus d a plus 2D a plus 3D which is a plus a d it should have looked like this because it's a standard AP now if I want to look it like this let's see the first the same example which we looked earlier this was my input this was my query now for this query which is like the same thing I wrote here it should look something like this now this represents after it is sorted it represents that it is a minimum element it is a maximum element I just wrot the same thing now minimum element maximum element if I want like what's the variable for me I know the first element because it is the array right it is array I know the exact array I just don't want to sort this array down why because ultimately why the Sorting was required just to find the D itself that okay if the D is constant or not the t is constant or not so the ultimate goal to sort was to find D rather if I can find D now itself and then go and check was it much beneficial like it is much beneficial right so that is what I will do I will rather sorting this down I'll just go and find the minimum element which is four maximum element which is six now I know the minimum element maximum element with this minimum maximum I just subtract this out I'll cancel the a maximum minus minimum I'll get n minus 1 D I know n the size of the entire array because I know Ln R so I know the size which is actually r - L +1 know the size which is actually r - L +1 know the size which is actually r - L +1 so I know the size of this entire that's very cool so I can just easily go and find a d from here itself which is maximum element minus minimum element upon nus1 with this I've got the D great you have got the D itself now when you have got the D it's no issue now you can just start off with the minimum element itself whatever minimum element you have here you have minimum element four you know that the D for you is actually a one so you know that the next element should have been a five I'll just keep a unordered map or unordered set or a hash set in Java just to keep track do I have five in this input array or not do I have like next time I'll just grab out for a six but six it has already reached the end so I don't need to check for it for example in this case when I will grab the minimum element five maximum element is N9 I know the D is actually a two so I'll just go and check five is like do I have a five in here which is actually 3 + 2 do I have a five in here yeah I have + 2 do I have a five in here yeah I have + 2 do I have a five in here yeah I have okay bro cool do I have a 5 + 2 in here okay bro cool do I have a 5 + 2 in here okay bro cool do I have a 5 + 2 in here yeah bro I have do I have a 7 plus 2 okay it has already reached the end so no need to check it so with this I'm just finding the next expected number which is actually if it is a current element so next expt number is current plus d I'm just trying to check that number and if that is available bro great just get that number out and simply return or like simply get that okay I the next exped number was five it is present great move ahead check what's the next expected number if it is also present move ahead at any point of time if any number expected number is not present return of Falls let's quickly quote this up again in this we can actually optimize the space also like here in the in this case we are actually making the entire new array although it's a followup for you itself just to optimize the space which means whatsoever I have given here just use this entire input AR itself don't copy the entire array just use this because you are not modifying the input R for sure right you're just using your L and R ranges you're using your L and R ranges so the follow for you guys is I'll just modify the above code itself but the followup for you guys is just don't modify this input the just don't make this new input array rather use this array itself go and find the minimum the maximum go and find what is the D when you have found out the and for this array minimum maximum just an operation you have got the minimum you have got the maximum you have got the N which is r - L + 1 you have got the N which is r - L + 1 you have got the N which is r - L + 1 you have got all these three you have got a D now just keep track of these elements L2 R in a hash set but oh Aran keeping a hash set will actually take a space of O of n yeah that will but ultimately earlier your space was used twice o of N and O of n o of n for making a new AR and O of n for the space itself but now only o of n would be used for this space so ultimately it will still remain o n as a space but you can actually you don't need to make a new AR itself start can be follow up for your interview like he might ask okay how can you optimize the space itself not required like it will not reduce the complexity on numbers but it might actually reduce the actual complexity of the program cool let's quickly code this up um so what we'll do is we'll simply just modify this previous part which we have seen uh just sorting it out so rather sorting uh we got know that we want to find the maximum element we will initialize with inin we want the minimum element again we will initialize with int Max and you also saw that we want our entire and yeah again uh ultimately the complexity for this program which we have seen is actually o of M into n m for query and N is just because we are not simply we are not doing any sorting of stuff space is O of n again this space o of n as I showed you just one thing is because of the array which you are making and other was the unordered set you are making the followup for you guys was to actually not use this and only use the input AR itself but we modifying the input code but yeah again even if you do this still you will be using o npace because you are using unordered set to actually keep track of the elements in the range L2 R cool uh now going back we will have a ar. size uh then I'll just simply go back on all of my elements because I need to actually update my um minium element and maximum element so I'll just say uh minimum element is nothing but minimum of uh minimum element and this element and same goes for maximum element it is nothing but maximum of Maximum element comma this element now uh I also need to keep track of all the elements in this so I'll just have unordered set now in this unordered set I'll just keep track of all the elements because ultimately you saw right I want to know all the elements in this range l2r which is the ER AR for us so I just insert this element now I have got this now I want to find the d is nothing but as I showed you maximum element minus minimum element divided by n minus one but uh what if it is not even visible like visible so just have a quick check that if maximum element minus minimum element mod this value which is n minus one if it is not equal to zero bro sorry it is not even possible to divide what are you doing it is not possible to divide now you will just find the next current element which is actually your minimum element plus d and just you'll just keep on checking that while your current element is less than equal to a maximum element just keep on checking if that current element is in your set or not so I just check that if s do F uh this current uh if it is equal to s.n which means it is if it is equal to s.n which means it is if it is equal to s.n which means it is not in my input set which I have made so simply return a false else uh just simply keep on updating your current with the D and ultimately if still it never goes to FSE which means it is a true simply a true let's quickly check if it works um yep so yeah that's pretty much it watching again bye-bye
Arithmetic Subarrays
count-odd-numbers-in-an-interval-range
A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`. For example, these are **arithmetic** sequences: 1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9 The following sequence is not **arithmetic**: 1, 1, 2, 5, 7 You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**. Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._ **Example 1:** **Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]` **Output:** `[true,false,true]` **Explanation:** In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence. In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence. In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence. **Example 2:** **Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\] **Output:** \[false,true,false,false,true,true\] **Constraints:** * `n == nums.length` * `m == l.length` * `m == r.length` * `2 <= n <= 500` * `1 <= m <= 500` * `0 <= l[i] < r[i] < n` * `-105 <= nums[i] <= 105`
If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low.
Math
Easy
null
114
hello friends welcome to joy of life so today we are going to look at another medium level problem from lead code the problem number is 114 the name of the problem is flatten binary tree to link list so given the root of a binary tree flatten the tree into a linked list so it says the linked list should use the same three note class where the right child pointer points to the next node in the list and the left child pointer is always null okay the linked list should be in the same order as a pre-order traversal of a tree order as a pre-order traversal of a tree order as a pre-order traversal of a tree so to understand the problem in little more details what happens in a tree is we have a node and we have a left child and we have a right child right so they want us that you take this node over here this node and put it over here and let this be a null so you know that in a linked list what happens is we have the node and then we have the value and then we have the pointer to the next node over here which points to the next node something similar to this and the last node points to another right whereas in a tree what we have is if we draw a similar diagram over here we have the value here and we have the pointer to the left subtree over here something like this we have in a tree right so what they want that our left should always be null and we should so what we need in a linked list is a single pointer right so they want us to have the three nodes only so we'll have multiple pointer but this is always pointing to the null and this one points to the next three node so of course we can leverage a free node in order to create a linked list also so given a traditional tree something like this we need to transform them into a linked list using the right pointer and also another important point is mentioned over here that you it should be of a pre-order traversal right so be of a pre-order traversal right so be of a pre-order traversal right so what does this mean basically is when you so what we know about a tree or about a pre-order traversal is pre-order traversal is pre-order traversal is the root comes first followed by the left and right it's a pre-order right so the root is it's a pre-order right so the root is it's a pre-order right so the root is processed first so for a tree like this what we have is a left for this first node one right so we will treat this and what will if we convert this tree into a preorder traversal it will look something like two three and four so we have to take this note two three and four and put it into the right side of the tree so two three four will appear first as you see over here and then we continue to have our five six the one we have so five six is on the right edge only so there is no problem with them the problem is with the subtree of two three and four right so for every node what we should do is wherever there is a left node we are going to the right node so we are gonna move them to the right of the tree but in a pre-order traversal uh in a pre-order traversal uh in a pre-order traversal uh order right so two three and four not three two and four or not four two and three but we know what the pattern that we need to follow so this is the problem all about so do give it a try and you can check out the solution this is a very interesting problem this is another traversal thing that you can say right so do give it a try and then you can check out my solution right so let's move over to the board and let's check out the solution so what i have done is i have taken the same tree from the example of neatboot and we are going to check on this tree so this tree has many of the cases right so what we are supposed to do over here is to move the left of if we have left in any of the sub trees or for any of the node we are supposed to move them under this free so we see that one has a left right so what i'll do is let's get the problem statement over here and understand them in more details and what we know from this problem statement is that we should not have a left that is our first verse so but for node one there is a left so this entire sub tree is a problem this marks a tree has to be taken clear first right because it is on the left of one right so what if i take this subtree starting with the root node two and move it to the right of one so i wanted to move this tree over here right so what will happen is this gap so 5 will become the child of 4 right if so just try to understand that i am i have detached this link over here and i am trying to push it inside then so eventually what will happen is this tree has to come down somewhere over here right and this drop sub tree becomes the right so it will go and sit somewhere over here and then we need to reattach the link from four in order to connect them right so this will happen if i try to move this subtree to the main trees or problematic nodes right hand side right now again we see that there is a problem with three right so again we let's mark the subtree that is problematic over here so this time this is only this subtree that is problematic and this subtract should become the right of two so how do we do that so let's break down this tree once again so let's say the yellow part of the tree is the tree that is fine over here so one two four five and six right and let's say this time only our problematic guy is the three so what do we do with the problematic guy we pick it up and we put it on the problematic parent who is two in this case and previously it was one we put it to its right and reattached the remaining tree to the to this node's right so once again what will happen because of that is something like this four five six has to come down so again four has to also come down not only that and what will happen is this three should get in here right and let me need some space for these nodes and we attach this node right so this is not the tree that we want at least going by the first problem statement that is this one so we have done this part and now you see that how the second part is taken care automatically based on our approach so what we have done let's understand this over here right so we are taking this node the root node of the problematic tree and putting it under the problematic parent's right side right that means the root will come first right and then we have a right that is that was coming right that we have seen it over here so as soon as we do this we spawn a tree another sub tree which is problematic if it has a left node right so what do we do with the problematic we put them between the root and the right we put them put the new root of the problematic tree which is actually the left of the main three right so what happens based on this philosophy is root left and right this becomes our pattern right and this is nothing but this is our pre-order is nothing but this is our pre-order is nothing but this is our pre-order traversal so just check over here based on our approach how the second part of the problem that is this part was automatically taken care this is the solution to the problem that we are trying this on so we are taking the bigger sub tree to bigger problematic subtree fixing it if we have a smaller sub tree that is problematic we are taking them and we are going down and we are getting things done over here so i have taken the same three over here but i have included the null nodes as well so i have just depicted the null values over here right this is the same tree as this one so we are going to check how this iteration will actually happen and we'll see in much more details over here so what will happen is we will have the root of the tree right so this is my root right so the root is pointing to the root of the tree right initially so now what will happen is we'll try to go to our left so from here we'll come to the left and we will continue to come until we hit another so we come to root 3 then the root becomes comes to another so when it comes to a null what happens is we return from here we just return we don't do anything so we came to this node over here so what does this mean is that this node doesn't have a left right because we have got a left from our recursion and now what will happen it does not have a right so there is nothing to be done over here so we'll move back to the previous node which is a 2 and in 2 what we see is that we have a left and right so right is fine the left part is the problematic this node over here should come to my right so what happens in this case over here is we create another pointer over here so let's call that a child node so we are going to take this and put this child point over here what we are going to do is we are going to detach the right of this tree so what does that means is basically we are going to erase this line over here so that basically means that 4 is now dangling so that's the reason why i was holding this with the child so what i'll do is i'll take four aside so here we are pointing it over here right so now what we'll do basically over here is we'll call so two roots right is now free right so what we're going to do is we are going to get this 3 to the 2's right so what will happen is we have established a relation something like this and do remember that the left is still also pointing to this node itself right now what we'll do is we'll introduce a temp over here so let's have this temp and this time what we are going to do with this tempest we are going to point it to the new right of the root right and now we will iterate them until we get the times right to be null but in this case we see that times right is null right it's null so we are going to remove this null that we have over here and what we will basically do is we will attach the child back over here so what will happen is we will establish this relationship back right and in this case stamped in play played an important role but soon it will play now since our tree is now fixed but my roots left is not fixed so what i'm going to do is it is still pointing to that old node so i am going to clean this up and i am going to put a null over here and then my roots right traversal will start again so at this point we are done with this so let's get rid of the stem and the child not for the time we will keep them aside we'll need them shortly so let's keep them aside and now what i'll do is i will go to the right the root will come here it will try to go to its left so it will come here it couldn't proceed so it came back over here so it will go to its right again it will go to the left it's null it came back here also there is now it couldn't go anywhere it came back here and then again it came here and then it's now reversing back so it came all the way to here using the recursion and again it will come over here and here it will what it will see is that oh yeah i have a left node and i have to take care of my things again so what i'll do is basically i will get the child over here and mark my child to keep it safe because what we are going to do at this point over here is again to delete this mapping that so again child is taking care of my entire right subtree and i am going to move them to a safe shelter now what i'll do is i'll get the entire left subtree and i'm going to put it to my right so what will happen is it will look something like this but this left is still pointing over here don't forget about that and what i'll do is now you'll understand the importance of temp so temp will come over here and now as i mentioned that i am going to iterate time until it reaches the right null these two's right another no it's not so temp will come here is free straight and i'll no it's not is force right and i'll yes it is so what i'm going to do is i'm going to remove this relationship over here and what i'm going to do is i am going to bring back the child that i was holding and i am going to re-establish this and i am going to re-establish this and i am going to re-establish this relationship back once again so this is established back once again and now we need to take care of this node so we are going to delete this link that we have on the left side and what we'll do is we will put a null over here so now if i remove my time my work is over and i will delete my child as well so you can see that our tree is now what we wanted it to become right it's a linked list with only the right pointers so this is what exactly we are also trying to do over here the previous example that we have seen but for grammatically it will be something like this that we have just seen let's head over to lead code and try to solve this problem okay so first thing that we are going to do is if we are going to check if root is null then there is no point in going any further right so in that case we'll be returning directly right otherwise what we are going to do is we will continue to go until we find a null we will continue to go left until we find them so the moment we find the null this is going to make us return back note once we hit a null we'll come back to the note from where we went to none right so here we are going to see that does it have a left see the left is there then we have to take care of everything that we have been doing right and if not we have to anyways explode the right side right so we'll be going to the right anyways if everything has been done everything has been taken here so here we will do whatever we have discussed so here we have a right child and we are going to hold the roots um right child over here right and once we have done that so we are taking care of the light in a variable so that we don't end up using so we have successfully done the movement of the left node to the right of the actual problematic node right and now as we have talked as we have discussed we are going to have a tank and this temp will start from root dot right or root left both are same thing and we are going to go on until 10 dot right is nine so why temp the right is null because we wanted to stop when we see that we have a null on the right side that means we have came to the right place and here we are just going to do a 10 because attempt so we are continuously coming and we stop at the node where we see that okay this right is empty and there what we are going to do is we are going to assign this right child that we have been holding safely till now right and we know that things are sorted now and root left now should have a null so i have taken care of the tree and now let me just put it there okay and once we have done that if there is a right it should go to the right so there is no check required because if the root is now let's anyway is going to return back here for the termination so let's run this code and check how it goes pretty cool first time no error run impressive aha that's nice so we got a runtime of one millisecond which is faster than 35 percent of the submission which is not bad but yeah there is a chance of optimization you can definitely optimize it but once again the main intention for me is to give you the idea on the solution i hope you got the concept of how we are doing uh with over here there are several ways to do this and you can explore some of the ways to optimize it and this is one of the simplest approach and the one that is very easy to explain and easy to understand as well so do let me know what you think about this video do give it a like if you think this video was of any help to you do share and subscribe with your friends as well and yeah talking about the complexity over here if we see over here that for storage we are not doing anything we are not having anything for extra storage so for storage it will be order of one right because we have not taken any storage it's a constant storage how big your tree is i'm not going to populate something and take up space only if you don't consider the stack space so that is generally not considered if stack space is considered definitely you will have the depth of this tree in the worst case it will go up to the it will go up to n where n is the total number of nodes if you have a skew treating like this then of course your stack you are going to store up everything right so you'll go up on the stack space so yeah that is if you're if you are considering the stack space it will be order of n if the stack space is not considered then it is order of one and coming to the runtime of it yeah we are virtually touching all the nodes and we need to touch all the nodes right we have to check all the nodes we have to verify all the nodes so we are going to each and every node over here so your runtime complexity also stands at order of n so this is your storage and this is your runtime and this is going to be your stack space and this is your normal computation that you have taken right so you have not taken any extra space in order to come up with the solution so yeah this is all about the video so do let me know what do you think about the video and thank you guys once again that we have reached 200 subscribers now the channel is growing at a very good speed it's good to see so many people uh coming up with the questions or doubts or compliments but i would rather love to have that in youtube itself other than in facebook or any other channel to do make youtube much more interactive so that this kind of video reaches out to everybody like us who's trying to learn new things and understand the concept better i hope i was able to explain it to some extent at least do drop a comment if you have any doubts or questions regarding any part of the solution that we have discussed so i'll keep it shut that's all from this video see you guys soon again bye take care and be safe
Flatten Binary Tree to Linked List
flatten-binary-tree-to-linked-list
Given the `root` of a binary tree, flatten the tree into a "linked list ": * The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`. * The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree. **Example 1:** **Input:** root = \[1,2,5,3,4,null,6\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100` **Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Linked List,Stack,Tree,Depth-First Search,Binary Tree
Medium
766,1796
896
Hello everyone welcome to my channel codestorywithMIK so today we are going to do video number 62 of our playlist the question is of easy level lead code number is 896 the name of the question is monotonic are it has been asked by multiple times I think three times asked Its frequency is three. Okay, so let's see, the question is quite simple. It is monotonic if it is either monotonic increasing or monotonic decreasing. What is the meaning of monotonic increasing that either it will increase or it can also remain equal? ​​Increase or Equal will never decrease. What is the meaning of monotonic decrease? Either will decrease or will remain equal. Will never increase again. Okay, it is explained here that n is monotonically increasing if for l a l e n equa ns i is Less day is equal to two, see, less day can also be equal to, okay and what will happen to decreasing, moist is greater day in moist, greater day will definitely be there but it can also be equal to and if it is not monotonic then return false. If it is monotonic then return true then it is monotonic meaning it can be either increasing or decreasing, it can be monotonic increasing or monotonic decreasing. In those cases, return true, otherwise return false. Okay. This is a small example , look here, 2, 3, okay, this is an example, so pay attention to it, let's assume that this is index number zero, index number one, index number two, index number th. Okay, so look here, one next to this. The element i.e. aa pv is right aa pv then compare see 1 lesson if there is two then you know for sure that it is increasing, right is increasing then look now if it is increasing then further if two also comes after two then I will assume it to be an increase only, that is not right but because of this I have come to know that it should be increasing only and it should not happen anywhere that the number decreases, hence I have confirmed this from here. I have decided that this is going to be increasing isn't it because there is no lesson 2, go ahead and meet two, then it is fine but there should be no less than going ahead, there will be a problem, then I marked here that this is going to be increasing. Okay, now I will take you forward. Come here, you are here, what is the lesson? No, okay, let's see if there is a greater day, if it is not like that, then we will not do anything. It is okay because now I have started increasing. If I had found out then increasing would still be going on, okay and I had given in the question that equal to two can also happen, so for me right now it is fine, it will not happen, it will just happen, so then I will see what I will do to make the decreasing true. I will mark then what will happen Increasing Decreasing if both become true then it will be messed up Right Ok till now I have not seen any problem in i and i + 1 so i again comes here i + 1 this is 2 &lt; 3 yes So it still appears to be increasing, I am right, now i increases i + 1, it is out of bounds, so we will run the form till here, only i will run only till here, so we have not yet found such a case that increasing is also true. Yes and decreasing is also true. No such case was found. Only increasing was found to be true, meaning if it was monotonic then our answer would be true. Okay, now let's take one more example, one more small thing will become clear from there, numbers are equal to two due to demand. Let's take the false case, one is 2, 3 is 3, then two has come, okay, now see i is here i + 1, this is see here, lesson 1 is two, yes, so what have I marked this, let's go Increasing is about to happen, okay, I have marked increasing as true now, okay now that aa is here, aa pv is here, lesson 2, lesson 3, okay, so increasing is still true, f e fine, okay aa and aa Pw this is it now look pay attention is 3 take 3 no is 3 greater than 3 still nothing ok so everything is fine right now aa here it is pw here now pay attention 3 is greater than 2 so I saw that a decreasing part has also been found, so I marked the decreasing as true, okay now I can't move ahead, this will go on till this time, so as soon as I came out, I saw that the increasing part was also found to be true and the decreasing was also found to be true. And if such a case happens then return false because in this there is increase as well as decrease so it is not monotonic and if it does not happen then return true but in an example my answer is false because see Yes, there are both parts in this. If we went from one to two, we got increasing, then in future also we should get increasing either equal to two. When we went from one to two, we got increasing. tha was good, if 2 is followed by 3, then it is still increasing. tha, if 3 is followed by 3, then it is not increasing, but equal to 2, fine, but after 2, two is found, decreasing is found, then increasing is also found, and decreasing is also found, ts answer is Fall is fine. Time complex is off because all the elements are being visited once. Okay, let's code it quickly and finish it. So, let's code it quickly and finish it. First of all n it's numbers dot size is fine. I said, we will take two Boolean variables, whether it is increasing or not, we don't know right now in the beginning, so we took it as false. Similarly, we take one more variable, whether it is decreasing or not, okay, its starting variable is also taken as false because we don't know about both of them right now. It's okay for aa e 0 aa elain remember n will go till my why because after aa pv also check ok if names of aa e lesson names of aa pv came out what does it mean increasing which is going to be true It's ok and if it doesn't happen then if the numbers of a is greater than the numbers of a then what will I do, in this the decreasing will become true. Okay, now when I exit, if the increasing is also true and the decreasing is also true then we will return false if If this does not happen then we will return true. Ok, let's submit directly and see. Hope you should pass completely. You will get the Java code in my Git Hub link. If you have any doubt, please leave your reason in the comment section. We will try to help you out. See Yuga The Next Video Thank You
Monotonic Array
smallest-subtree-with-all-the-deepest-nodes
An array is **monotonic** if it is either monotone increasing or monotone decreasing. An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]`. Given an integer array `nums`, return `true` _if the given array is monotonic, or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,2,2,3\] **Output:** true **Example 2:** **Input:** nums = \[6,5,4,4\] **Output:** true **Example 3:** **Input:** nums = \[1,3,2\] **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `-105 <= nums[i] <= 105`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
1,180
so my system is having hard time to figure things out uh probably it is because i'm uploading bunch of high resolution video um with a 34 inch display and it's not keeping up well so what you're looking at right now on my screen is basically some gibberish word which is an input causing my code to fail so this is code lead code question number 1180 which basically says hey i will give you a string written me all the substrings that have only one distinct letter so that basically means that you know if you have a string like triple a b a uh the output should be eight and that uh essentially is the count uh of the substring which only had a originally right or b right like only one character at a time and if you look at my solution it sort of works for the smaller input but then it does not and then i made some changes so i will just walk you through that bit so that you understand what is going on here right so what you're looking at is like you know i create a function uh saying like hey get me all sub strings which is essentially given a string written all the possible sub strings um which we can later on you know filter and then see if it has only one character the way i was trying to do was like you know i have a string let's split it and then run a map on each character and from that character onwards find all the possible uh word um or subset it can have right and then um push it uh into an array so basically uh there's a map happening which will return aside and then there's a reduce because like you know if i'm going from a string which is similar to triple a b i'm mapping i'm at a i'm trying to figure out like hey what i can build a b and then triple a b a right so to solve that one uh level of looping i'm using map the level of looping i'm using reduce which is like you know for the left out character uh try to figure out that um how many set of combination of word you can you know create and then i'm basically on that i'm initializing with the starting value which is the value at which um the map will have right like the character which map will be looking at this essentially will return a nested array which i'm flatting here so uh the end of the story is basically it's returning all the characters all the substrings which can be created from the string s once that is done um i have also created another helper function which i'm still as you can see still work in progress is basically i'm trying to use regex to make sure that you know given a string yes can you check whether it only has one set of characters or does it have you know more than one character in that particular word and last but not the least the main function basically takes um all the uh the string input and then uh returns all the substring possible right and then just filter those upstream based on the property which is like has one character and show me shows the result so if you look in the higher level um this function becomes really readable only because we have this two functions i tested this one seems to be working very nicely um i believe we have some problem here and um i'm trying to figure out so the other problem i faced and why i'm going to look at the regret so is basically i was looking uh at uh to solve this problem using uh something called every in-array uh something called every in-array uh something called every in-array i don't think so this will be the one but if you see uh a dot every mdn i think you should get what i was trying to say i'm extremely sorry for my bad system working on it uh will be better from the next video onwards okay yeah still taking a lot of time okay this is what i was talking about so basically what it does is like a method which is basically a tester test for the all element if everything passes then only every returns true otherwise false um i was trying to do that i was able to solve that problem for a smaller set of input but input like this is causing me really hard time because this characters are not easy to solve and i'm getting some sort of um garbage collection issue basically memory overflow for the node because apparently they have a limit on top of how much memory one process can take in this particular solution which i had taking more than allowed or permitted amount of memory still don't know why is that the case if i will know i will share it with you um yeah that's about it and with this solution i'm having some trouble with like you know uh for everything it's returning false except one uh maybe my deck x is bad so i have this regex set up here uh which i'm constantly testing against i figured out one problem with my solution is basically that you know let's say there's one a this all is for it but then that be a right and then this is a match but i don't want that to be a match so what i did was uh a being a character you know i'm trying to check against a i did a plus and i did a dollar i believe right start and end yeah i think so this was a so it matches right like a the first bit of this a is matching this hey does it start with a dollar a okay it is about to rain so i can't do anything about the thunder so just please bear with me um and the dollar is essentially you know this a and a plus is like any character of a but non-zero numbers right non-zero numbers right non-zero numbers right so the problem with that is like two does not match so you can solve that um by adding a star here so it says like hey zero or two this looks good but then when you have one a this will so i believe uh i this is the solution which i should be looking at because at least it works for two uh the only thing i need to make sure that you know um when i do that uh first is like i need to remove this plus and change this to a strict the other bit is like you know i need to make sure that you the particular character has one length so if it is the one length um it has only one character right like no brainer so if uh i want to do s dot length let's just return to otherwise do all of this run this code let's see what happens okay so this got accepted wow i'm that good at it i don't know okay because man this gave me some trouble i still don't think this will solve the problem though you can see i failed a couple of times and yeah terminator call throwing an instance there's what i don't know what this means um and this is basically feeling for this one i don't have any solution to it and you know yeah there you go so i have this process out of memory book and i have no clue where is it coming from maybe it is coming from slice uh because inside a map i'm doing slides for every character to find the let left out character and running reduce on top of them but i can't say with the a lot of confidence here um and that is where my trouble is um okay let me figure this out right like what is going on okay i think probably i need to change my approach upside down because in this way i was just solving for um all the substring and then trying to filter out hey out of the substring how many of them are actually matching the requirement we have of having you know the same number of characters instead of but i believe that is not how i should be solving it anyway um yeah i don't know probably i just have to look for the solutions because um i don't think so that i would have enough time to solve this one okay this one is interesting okay left hook characters that slide selected reduce character dot push length minus one god i'm sleepy yeah that is the problem whenever i see problem which is challenging i start feeling sleepy okay so i'm running map running reduce left outside okay i believe this is the problem because for each character it is looking for the left-hand character left-hand character left-hand character and for each leftover character then it is okay i don't know how to stop that um yeah thanks for listening i think i'm done with this video oh now yeah i am not done actually i will find out the solution i will close this video nicely and then take it forward okay so what i would do is like i will take this copy to a notion you might not be able to see it but i need to do that because so that i can keep oh you are able to see it oh it is not recording that it's recording every center of the window which is not cool man okay anyway i don't mind 16 okay i was solving this one only right open this solution failed so i have a better one i believe which i will just be pasting here this okay and why not to you know improved version still fails but still yeah so um what i think we should do now is um jump on to solution or discussion and see how they have built it uh because i'm running out of ideas okay um might not require that let's look at this one uh okay this looks shamefully easy which is very strange because i thought the solution would be very hard so say a three times w two times a one time okay so it is checking for each and every combination if s of i is not equal to s of i minus 1 then this and then there is a total thing and then there's this much uh for count is equal to one plus one wow this is easy this is so easy i'm so ashamed that i was not able to solve it but tk i go to so but how so this is basically testing it s of i if it is not equal to previous one then count is one if it is equal to previous one then increase the count whatever number it was then before so if it is three a two times an a is one times uh how does that and takes into account right like that is certain triangle so you only need to know how many of this continuous letter are and then for each of them calculate the sum by adding 1 and lending the continuous letter for triple a okay it's 1 plus 2 plus 3 which is equal to this for example okay so but is it doing count total is equal to one count is equal to okay total is undefined basically right uh okay so this is one the count get increased to oh it does not get reset every day so one occurs one but w occurs twice so three times w twice i'm not able to understand honestly so you need to know how many of these continuous letters are and then each of them calculate the sum by adding 1 to the length of the continuous letter for aaa it is this in our example at the beginning of our code to make the code easier to write without considering too many edge cases i concentrated two spaces at the beginning and the end of the string then we have variables one is total that holds the sum and count as the count of the number of the continuous letters if we found i yet letter is not same as i minus one letter then we reset the counter otherwise they are the same and we add one to the contour for each time we simply add the counter value to the total and then end one had same idea find resolution your genius did it without the string concatenation okay so uh i'm feeling so dumb because i went other way around but i think yeah the whole point of it the solving this problem is to understand the pattern in it and then uh going about it so yeah let's do this in javascript sorry for any background noises okay so i have to solve it for count letters i'm not doing this okay so essentially what we need to do is to make sure that you know if so we have something called total which is equal to 0 for now and then we have something called count which is also equal to 0 for now okay now what we want to do is that for sorry let i right so um what we want to do is like if s of i is not equal to previous one right like i minus one set count to one right but i do need this bracket and stuff right because i need to go for else also okay now i need another bracket to close this else i want to do total plus equal to count and as he did his solution that he added one um string empty string at the end and the starting the reason being that you know when s is equal to 0 s minus 1 will basically be minus 1 which is not cool right so what i think i can do is um we need to make sure you know this value exists so um when i will okay so i think the only check i think we need is s minus one exist and then because that's stuff i will always be there right and then we have this total uh which we want to use uh to return total so let me check this count is zero let i is equal to zero s length minus length i plus okay check for the previous character if that exists um s of i should not be equal to this reset it otherwise uh increment the count but um i think the problem i'm having here is like increment the count by one as well right like we're supposed to do that i haven't done that yet so let's just go back quickly and see where they do it so they're incrementing the count within f else then the incrementing on top of it so yeah that is one mistake i did because i kept it here that would mean that you know it get added only in case where the character will not match so countless okay this looks better let's run this and see here this works man this is gold so as you can see a problem which you think uh is really hard might not be that hard and i have this tendency to comp over complicated problem all the time so learning for me from for this specific videos to figure out you know the problem necessarily not to be too hard uh just because it looks like one thanks for this guys thanks for your time uh it's been pleasure um solving this problem and quite humiliating as well um i hope you know we level up your time thanks
Count Substrings with Only One Distinct Letter
game-play-analysis-ii
Given a string `s`, return _the number of substrings that have only **one distinct** letter_. **Example 1:** **Input:** s = "aaaba " **Output:** 8 **Explanation:** The substrings with one distinct letter are "aaa ", "aa ", "a ", "b ". "aaa " occurs 1 time. "aa " occurs 2 times. "a " occurs 4 times. "b " occurs 1 time. So the answer is 1 + 2 + 4 + 1 = 8. **Example 2:** **Input:** s = "aaaaaaaaaa " **Output:** 55 **Constraints:** * `1 <= s.length <= 1000` * `s[i]` consists of only lowercase English letters.
null
Database
Easy
1179,1181
460
in this video we're going to take a look at a legal problem called lfu cache so the goal for this question is we want to design and implement a data structure for at least frequently used cache so implement the least frequently used cache so this class should have three uh supports these uh two methods right this one's a constructor so it takes the capacity and then initialize the object with the capacity of data structure right and this get function basically gets the value of the key so if the key exists in the cache we return the value if it doesn't exist we will return negative one and for this put function basically it takes the key and value and either it updates the value for this key or if the key is not exist in our data structure we have to create this key and then insert this value for this key right but when the cache reaches the capacity right it should indicate uh it invalidates and remove the least frequently used key before inserting a new item for this problem when there is a tie where two or more keys with the same frequency the least reason used key will be in indicate invalidated right so basically means that if we have uh insert a key right and if we insert let's say the capacity is four and we insert we already have four items in our cache then we have to remove the least frequently used item in our cache if they're if all the items are equally frequently used right then we want to remove the least recently used right so we want to keep the most recently used and we remove the least recently used if they have the same frequency so to determine the least frequency use key basically we can use a counter right it's maintained for each key in the cache the key with the smallest used counter is the least frequency use cast key right so we want to have some kind of a counter or something to keep track of their frequency that we're being used and what does it mean by frequency basically means that every time we call the git function or the put function that basically we have to increase its frequency for this key right if we call the git function that means that we have to increase the frequency for this key if we call the put function we have to increase the frequency for this key right because put function can also updates the value for this key so when a key is you first insert into cache the use counter is set to 1. so we have a frequency of one right so because we just call this put function so the frequency is one uh the use counter for a key in the cache is incremented either or it either a get or put operation is called right so the goal for this uh this question is that we want to make the get and put function run in a constant time on average time complexity right constant time complexity on average so let's try to run through an example so let's say we have uh this lfu class right let's say we create an instance of this lfu so we're gonna do is that we're gonna take we're gonna have a key we could have a value gonna have a frequency right so in this case once we create an instance of this class we're going to call this function we're going to insert one right this is the key this is the value right and then what we're going to do you can see here that um currently basically our data structure we have this data right we have our key we have our value we have our frequency we're going to keep track of that right and then we're going to insert 2 again so then you can see here we have key we have the value we have the frequency right so in this case because this one is the most frequently used right so we insert it in onto the head right onto the head uh insert first right and you can see the least frequent elements or at least recently used elements will be at the tail note or be at the uh at the back of the list right and then you can see once we get one right if we pass in the key and then we call this get function you can see that we're basically getting this function right we're using this function so in this case therefore we have to increase the frequency for this key right so once we've done this part right then we call the put function you can see here once we put we also have to update the frequency but there but you can see here the capacity for our uh you know for our data structure right is basically two right if is exceeds two then we have to if it if the current capacity is equal to the max capacity then we have to delete the least uh frequently used element right or the and or the least recently used element so you can see here that in this case if we want to insert this element we have to delete either this one or this one but we know that this one has the most frequent element frequently used so in this case we had to delete this one right so you can see that once we delete this one we have to insert this one out on here right and then once we call the git function you can see that we should return negative 1 because this uh two is been deleted right so then we call three so in this case three has a frequency of one and now if we call it we're gonna increase the frequency by one so now we have two right so you can see here we have to move this element to the front to the head right but it doesn't really matter about the order at the end we basically have to remove the either the least frequent element right uh or the least recently used element right so then we insert this four we know that one is the least reasonably used element so we have to delete this element and then we insert four onto this uh onto this list right or our data structure and then we're going to call the git function you for the key one you can see that it doesn't exist and then if in this case if we want to call three in this case three we can get three and then we have to increase the frequency for three if we get four we have to return four and we have to increase the frequency for four right so how does lease reasonably use cash different compared to least frequently used cash so i'm going to show you the example right basically for least recently used cash question right the previous question for lfu for least free recently used cash question basically we use a doubly linked list right and a hash table to make sure that we can get the time complexity and constant and we're basically going to keep the least frequent least recently used elements at the one side and then the most frequent most recently used elements on the other side for lru question right basically we have a linked list right the head node pointing to the tail node and then if we want to insert the first element right and we have a table that keeps track of the key and then the node uh as a reference right so in this case for this key is pointing to this node so that we can be able to retrieve the node in a doubly linked list in a constant time right and then in this case you can see here if i want to insert node 1 i will say key this is the key and note this is the node and then we're going to insert first so in this case we're going to insert right here this is note 1 and we want to insert 2 node 2 right in this case because we want to make sure that we keep the most recently elements right the element that we just want to insert it we always want to insert first right so we have no two right here and no one got pushed one to the right okay so then we will when we want to get one right we want to make sure that we delete okay so we want to keep sure make sure that the table is up to date so what we're going to do is that we're going to make sure we delete node 1 and then we're going to push node 2 right and then we're going to uh have no one here so node 2 is still here but we're just going to add no one at first right so we're going to append this node 1 at first so we have append no 1 between the head node and then the node two right and we're deleting node one so that node two is pointing to the tail node okay so then what we're gonna do because we just called the git function so we wanna make sure we get the most recently used elements to be at the first of our uh close to our head node right so when we want to insert node three we know that we are exceeded the capacity right so then what we have to do is uh we basically have to delete the most the least uh recently used which is note2 okay so what we're gonna do is we're gonna put no one here and then no three here right so we're gonna delete this node three okay and then we're going to um get 2 and it shouldn't return negative 1 and if i want to get 3 okay so i should have return 3. if i want to get 4 okay then in this case you can see here if i want to get 4 i have to remove in this case the least frequently used element right but we're using the approach that we did in the least recently used so in this case you can see if i want to get four right you can see that node three is being called twice right that has a frequency node 3 has a frequency of 2. but no 1 is being called just one time so in this case the correct approach is that we should remove this shouldn't be removing this right so in this case it still works right we can still like removing the one right that's no problem but you can see that we're basically didn't doing this check here so in this case if we were to insert we have to insert four right here because we're using a least reasonably used cache right so we are putting uh we're putting three here and four here right and then if i want to get one it should be negative one right and if i want to get three in this case you can see we're getting three if i want to get four we should have to get four right but the thing is you can see here is that uh we want to make we want to get the most frequently element and here we're trying to get the least frequent elements out of it right if i want to get four in this case i will remove the um the least frequent element not the least reason element right worst case scenario if they have the same frequency then we have to remove them right so in this case let's take a look at a bit more about the uh the constraints here so you can see in the constraints is that there could be a situation where we have a zero capacity so in this case if we have a zero capacity it doesn't matter if we call this function or not or this function we always should not perform anything right if we calling this put function we shouldn't insert any elements in our data structure right and then you can see here the keys they'll always be integers so in this case let's take a look at how we can be able to solve this problem in this video i'm going to show you two approaches one is we can be able to use a doubly linked list and the other way we can solve this problem is we can use a linked hash set so let's take a look at the first approach so the first approach is very similar to what we did in lru so what we're going to do is that we're going to have this lr lfu cache data structure and we're going to have two tables first we're going to have this table called key and node which takes the key right as the key and the node which is the value and then for each and every single list node we're going to have the previous porter and the nest pointer and then we also got to have the value the key and the frequency right we're going to keep track of it's every single node's frequency and then we're going to use that node's frequency to retrieve the location of that node in the frequency table right so in this case you can see here we have a frequency table and this frequency we're going to use the frequency as the key right in this case if a node appear uh is being called two times that it's going to be in the frequency 2 list right and then if this if a node has a frequency of 1 then it will be in the frequency one list right so here you can see we have this doubly linked list right so we have the head node we have node two and we have a tail node right so it's very similar to lru right you can see here basically what we're going to do is that we're going to keep track of each and every single frequency right so that we can be able to retrieve the frequency in a constant time right so if i want to say okay i want to get the frequency right if i let's say if i want to call the git function for node 2 right so we're going to do is that we're going to call we're going to check to see if node 2 if key 2 right contains in our table in this case it does we're going to retrieve the node for this key so there's no 2 node 2 has a frequency variable right and then we're going to go to this frequency right table and this table has a list doubly linked list right and we're going to retrieve the node and we're going to delete that node out of it right we're going to delete that node in this um basically in this list and we're going to because we call it so we have to increase the frequency so we have to do is we have to insert another frequency and another uh wwe linked list and then we're going to put node 2 in that list so that represents this node has a frequency of 3. now the good thing about this one is that if they have the same frequency right in this case let's say if i want to insert three or let's say if i want to insert four okay let's just say four because three is already inserted let's say we have a capacity of three so now we have to remove one item so we know that in our lru problem we know that we can use the doubly linked list to keep track of the uh the least frequently used elements right in this case the least frequently used elements will always be at the one side right and then the most frequently most recently used elements will be at the other side so in this case if i want to put this uh in our data structure so we have to delete a node in the least frequent elements right uh in this case the least frequent element in this case is one right the frequency has the lowest frequency of one so in this case if i want to so in this case you can see we have two elements so in this case if i have to remove the least recently used item now we know the least recently used item is at the tail node so we had to do is that we have to remove this node right here right and then we also have to delete that in our table as well so that what we can do is that we can be able to insert node4 okay so that we're still using the same logic in the lru but we're basically just going to have another table that keep track of each and every single nodes and their frequency and then we're going to have a frequency table that basically keep track of each and every single node's frequency and then if we want to remove uh a if our if we uh exceed the capacity then we have to remove a node that is least recently used in the lowest frequency in our table so now you can see we're basically inserting four that has the most uh in this case the most uh has a frequency of one right but the thing is that because we're just calling this get uh put function so we have to insert node4 first right so we have to insert first in the list right so you can see here basically we're going to insert node4 at first and then we're just going to return that at the end right or in this case we're basically just going to complete a function like that so this is basically how we're going to solve this problem using this kind of approach and let's take a look at how we can do this in code so to do this encode like i said this is our list node right we're going to have our previous pointer and nest pointer we're going to have a value key and their frequency so initially the frequency is one and then what we're going to do is that inside we have a doubly linked list right a doubly list so in this case in this class we supports two function one or three function here we're going to have a map to keep track of each every single key and it's mode right we're going to have a head node and the tail node initially we're going to set them to an instance right empty node and then we're just going to get them pointing to each other so in this case it supports basically three function one is that you can be able to add a node and if we want to add a node we want to make sure we add first right so you can see here we have the tail brief and the tailpaint dot nest is equal to current though so basically you can see here what we're trying to do here is that if i want to insert this node i basically just going to get the pre right the previous node for the tail node right pointing to this node instead right and then what we're going to do is that we're going to get the current node.prev we're going to get the current node.prev we're going to get the current node.prev pointed to the head node right the in this case the previous node for the tail node and then we're going to get the current pointing to the tail pointing to the tail pointing to the tail node right kernel that's equal to tail and then tail.preview is equal to the and then tail.preview is equal to the and then tail.preview is equal to the current node and then at the end we also have to insert that in our table so that we know hey this is the key and this is the node the value for this key right so and then in this case you can see we're basically inserting the new node on last right instead of first and then you can see here if i want to delete the node i take a key and then i basically check to see if it contains the interrupt table if it doesn't which would return null if it uh yeah in this case if it does we just have to get the key or get the node and then we're basically just deleting that node right like i said before if i want to delete this node all we have to do here is basically just going to remove this connection right we're going to get the uh the previous note for this current node that we want to delete pointing to the current node nest node right so we're going to forming this connection right here instead of those two connections right and then after that we have to delete in our table and then return the current node and then for returning a delete head you can see here we're basically just going to say this is the first node right we're going to delete this node okay it's pretty simple we're just calling this lino function so we're going to use this w link list in our lfu cache and you can see here we have two table just like i mentioned before right we have a key map and a frequency map and this frequency map has a key right sorry it has a frequency as the key and then the doubly list as the value right and then the key map is this in this case we have a key as the integer uh as the key right and the value is basically the node right the list node and this list node contains the frequency the value the key as well as the previous and the next point right so we're going to use the nes the list notes uh frequency to get the location uh for the frequency map right initially the current capacity is zero so we're going to use a current capacity tracker to keep track of how many uh elements that we have added or we can just basically uh get the size for the key map right so either way kind of thing and then you can see here basically what we did is we're basically in our gets function right what we're going to do is that we first check to see if it contains if it doesn't contain in our table right we just return negative 1. if it does we have to retrieve the node from the frequency list of yeah from the current frequency list so in this case we get a node in this case it returns node and we return the node's value so in this case the get node function you can see here we first check to see if the key map has it if it doesn't have it we return null retrieve the current node in this case this is the current node and then what we're going to do is that we have to update spread we have to remove the current node from the frequency list so just like i mentioned before in this case if this node right contains in this frequency table so frequency and then the value is basically the w list right w list so in this case you can see if this is the frequency right and then if i want to you know get the node has a frequency one and this is the head node and this is the one this is the tail node right so in this case what we have to do is we have to remove this node and we have to uh in this case increase the frequency for this node and then we're going to add the current node onto a higher frequency list this we're going to increase in this case if this frequency is not there we have to create this list right and then we're going to add it here right so we're going to increa update the kernel's frequency and then we add this node onto this list right and we're returning this current node and basically this function is just really like return the node and updates the node right updates the notes frequency and then for the put function you can see it's kind of similar uh we just basically just first there's two situations one is the updates the value in this case to update the value we're just going to get the node right and also at the same time this function will update the frequency and then we're just going to update the value if it's not updating the value we have to insert the value first we have to check to see if it's uh match if the current capacity right matched with the max capacity in this case if it does then all we have to do is we're just going to iterate through the key the frequency table right now you can of course you can use a variable like a min uh or something to keep track of the frequency but in this case you can see here we're basically just going to iterate through the table to find the lowest frequency that we have and then what we're going to do is we're going to get the list we're going to delete that node right we're going to delete the head node because we know the head node is the least recently used element and we're going to remove that in our table and then we can decrease the kind of current capacity and now because in this case if i want to insert an element what we have to do is we have to insert that element right so we create the instance of this current node we insert it in the key map and then we're going to inside our frequency map we're going to see if it contains this current frequency if it doesn't we're going to create it and then we're going to add the current node onto this current list of frequency right this doubling list and then we're going to increase the current capacity so basically you can see this is basically how we're going to solve the problem and the time complexity in this case is basically just going to be constant on average even though we're basically iterating through the frequency table right the worst case scenario is that each and every single value that we have in our data structure has a different frequency therefore we might have to it might cause a linear time complexity to iterate through all of them right but you can see here that it's basically just going to be constant time on average because we're basically just going to utilize two separate tables um and then as well as what we did in lru right to keep track of the least recently used elements and this will basically give us a constant time complexity but now let's jump into how we can be able to use a different way to solve this problem so this different way to solve this problem is that we're going to use this length hash set so this linked hash set is basically a set but the thing is that when we insert an element it's basically just like a cube we're going to insert it in the same order as the data structure basically stores these elements these unique elements in the same order as we add it right so let me show you an example you can see here we basically adding these elements from zero to three right and then we're going to print the list and then we're going to iterate through the list and you will notice that um the list right or this set is basically in the same order as they insert it so let me run this code and you can see that the list is basically zero one two three is basically inserted as the same order as they insert it right so you can see that if i want to print it if i want to iterate it right you can see that it's zero one two three so in this case you can see the orders uh how they store these elements is the same for the linked hash set so just like how we did it before you can see here we have three tables in our data structure right so in this case we have our classic key value pair right in our table right key value table this is the key that's the value right when we call this put function we will insert a key we'll insert a value and then we also have this key frequency table basically you can see that we're going to keep track of each key's frequency so that we can use this frequency to use to retrieve the in this case the order in the frequency table right we have a frequency table it has an integer as the key has an integer as the frequency and then the value is basically a linked hash set so you can see that we're basically just going to just like a queue right a linked list uh if i want to remove the first element i can just convert it into iterator and then the next element that we iterate in the hash set is basically just going to be the um in this case the least frequently used element right in this case you can see what we're going to do is that we're going to remove that element and then we're going to insert it into a higher frequency right or let's say if i want to just remove it because we're out of capacity right i can just remove the least frequent element it will always be at the first element right and because in this case a queue we want to insert last right and then remove the first element uh remove the first element that we inserted in our queue right so just like that what we're going to do is that if i want to call this three right if we pass in the key three and we're calling this we want to get this what we're going to do is that we're going to uh basically just going to retrieve it in our key but at the same time we have to increase the capacity and increase the frequency right so you can see that we know that this key has a value three and then this key has a frequency of two so we're going to do is that we're going to increase the frequency and now we're going to increase the three and we also have to make sure that this uh key right in this case you can see this is the key we're going to remove that from that frequency list and we're going to insert it in a higher frequency so you can see here what we're going to do is that we know that the previously right is 2 so all we have to do now is we're going to update it to 3 and then we're going to get the frequency in this case 2 and then we know that this has a list of 3 right in this case has a list and then in this case the first l uh in this case because it's a set we can just remove this key right out of this set and then we can just create a new um in this case create a new frequency and we're just going to insert three as the key the only key in the set right so we're going to add three in this set and then the frequency in this case is a three right and then if i want to add a four right let's just do another example let's say if i want to call one right in this case i know the one is in our table and then we know that one is here has a frequency of one so we're going to get the frequency here in this case the frequency is one and we'll because this is a set we can remove this element out okay and then we're going to add this one in the frequency of two right in this frequency of two list and then we're going to update the frequency for this key right sorry this now this one right here one has a frequency of two now right so you can see this is basically how we solve it and then at the end of course we want to return the value but in this case i'm just going to show you this is the get function right now let's say if i want to insert a four right in this case we know that four okay so in this case we are out of capacity because capacity of three right so what we're gonna do is that we're gonna basically just going to delete the least uh frequent element in this case the least frequent element in our table is one okay so we have a one and in this case you can see it's not empty it has the first element is basically the least frequent element right the sorry the least reasonably used element so we're going to remove that so we know that it's 2 so we're going to remove that and we're going to remove that in our table of course as well as our key frequency table and then we're going to basically just going to insert that right at the back right we're going to insert last so we have one here and then four is right here and then we're just going to add that on our table and then this key has a frequency of one right so basically you can see this is basically how we solve the problem and now let's take a look at the code you can see here we basically have a constructor that defines the capacity and then we insert the first frequency right in this case this is the frequency and then we're going to insert an empty list right empty linked hash set so for our get function what we're going to do is that if i want to get an element uh what we're going to do is that we're just going to see if this key map contains this key if it doesn't we're just going to return negative 1. if it does we're going to get the current keys frequency right like i said we have three tables we have a key frequency table and we also are going to update the keys frequency right so key frequency map we're going to increase the frequency by one and then we're going to get the list right get the set in this case in the frequency map set we're going to remove that key and then all we have to do now is that we have to first update the minimum frequency uh you can we don't have to use the minimum freq minimum variable here we can just at the end just like the previous approach iterate through the table to find the minimum but in this case we can keep a variable just to improve the time complexity right so you can see here we're going to update the minimum frequency if the frequency is minimum and the frequency has zero elements in it we can just increase the min because we know that this current element has it is the minimum frequency right so then we have to update the minimum frequency otherwise we don't um so then we're going to do is we're going to update the current keys frequency so we're going to say if the current the higher frequency right current uh keys higher frequency doesn't exist we're going to create that linked hash set and we're going to insert it onto that linked hash set and at the end we're going to return this node's value right or this keys value and then for the put function you can see here we're basically just doing something similar this is the universal base case right in this case the capacity that we define in our constructor is zero then we just return it otherwise we update the current value in this case key value map contains the key we just insert the value and then we're going to get the value basically this will just update we don't really care about the value for this key we're just going to update a frequency for this current key right and then otherwise we're going to do is that we check to see if exceeds the capacity if it does we know the min we know the minimum frequency so we're going to get the list and we're going to have we have this pull function and this pull function is just like a cube right we're just going to remove the first element that we have in our queue so we're going to have this iterator we can convert it to iterator and then the next element that we have in our iterator we're going to remove that and then return the top and this top is basically the first element that we remove in our linked hatch set right so then we're going to use that and remove the remove it in the key value map as well and you can see here what we did is we also you know insert this element right this new element that we want to insert and then insert it in the key frequent map as well and then we're also going to add this element right because now we insert elements so the min should be one right and then we also have to say frequently frequent one and add a key right and you might be thinking well there's might be something that we forgot to do is that we have to forgot we have to remove this element right here from the key frequently uh frequency map in this case we could but it shouldn't affect anything because that keys are removed right so in this case uh if we were to fix anything i would definitely just in this condition we will just remove this top element from the key frequency map right so that's what i would do but the time complexity on average you can see for this code is basically still constant time on average so there you have it and thank you for watching
LFU Cache
lfu-cache
Design and implement a data structure for a [Least Frequently Used (LFU)](https://en.wikipedia.org/wiki/Least_frequently_used) cache. Implement the `LFUCache` class: * `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure. * `int get(int key)` Gets the value of the `key` if the `key` exists in the cache. Otherwise, returns `-1`. * `void put(int key, int value)` Update the value of the `key` if present, or inserts the `key` if not already present. When the cache reaches its `capacity`, it should invalidate and remove the **least frequently used** key before inserting a new item. For this problem, when there is a **tie** (i.e., two or more keys with the same frequency), the **least recently used** `key` would be invalidated. To determine the least frequently used key, a **use counter** is maintained for each key in the cache. The key with the smallest **use counter** is the least frequently used key. When a key is first inserted into the cache, its **use counter** is set to `1` (due to the `put` operation). The **use counter** for a key in the cache is incremented either a `get` or `put` operation is called on it. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LFUCache ", "put ", "put ", "get ", "put ", "get ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[3\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, 3, null, -1, 3, 4\] **Explanation** // cnt(x) = the use counter for key x // cache=\[\] will show the last used order for tiebreakers (leftmost element is most recent) LFUCache lfu = new LFUCache(2); lfu.put(1, 1); // cache=\[1,\_\], cnt(1)=1 lfu.put(2, 2); // cache=\[2,1\], cnt(2)=1, cnt(1)=1 lfu.get(1); // return 1 // cache=\[1,2\], cnt(2)=1, cnt(1)=2 lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2. // cache=\[3,1\], cnt(3)=1, cnt(1)=2 lfu.get(2); // return -1 (not found) lfu.get(3); // return 3 // cache=\[3,1\], cnt(3)=2, cnt(1)=2 lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1. // cache=\[4,3\], cnt(4)=1, cnt(3)=2 lfu.get(1); // return -1 (not found) lfu.get(3); // return 3 // cache=\[3,4\], cnt(4)=1, cnt(3)=3 lfu.get(4); // return 4 // cache=\[4,3\], cnt(4)=2, cnt(3)=3 **Constraints:** * `1 <= capacity <= 104` * `0 <= key <= 105` * `0 <= value <= 109` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Hard
146,588
677
six seventy sevens mapped some pairs implement maps some class of inserts some methods for MF and insert you're given a pair of string integer the string represents a key and the integer represents two by the key already exist and the original key pair will be over into the new one but if it's some you're given represent a string representing the prefix and you need to return the sum of all the pairs while who's he start to the prefix okay so unfortunately just like way happenstance that this is exactly what deformed every chest did you know I mean not exactly but the data structure is exactly the same so we have some experience there so that's kind of good to a bit up basically you want to keep a try and then for every answer you just insert stuff into the try and so forth so that's yeah that's uh that's how I mean that's pretty much it really so now at least my fingers a little warmer with respect to implementing a try unfortunate but that's okay what do the inserts and the Sampson aider I could also keep track of the value but maybe it's not even necessary for say it's implicit on the edge but we could tell from the Youngs store that but yes yeah that's not have your first I guess end there's nothing in here well we have two cents like a sum or the current notes um and then also edges and then now we want to implement just an act dad help and then now and maybe I didn't work on a try which is well the insert function for the try what are we doing right well for each edge yeah we'll just go through each edges each cow at a time so let's just put key and value and now so could notice you to stop that we started to boot and then for each character in key we see if I'm just thinking about where I should go where I should put to insert functionality and no door and try hey no go ahead indeed it's basically just pythons way of doing a constructor oh yeah I mean it's a it's just how they do constructors only if you do so when you co actually here when you call no friends this cause dysfunction that's all and then it sets that up yeah no thanks for the question definitely the Python definitely has his own little charms in places yeah so let's see no thanks for file we free wood kit but yeah okay if the current edge is not incurred no edges and this is logic we could maybe put on there no but maybe that's okay no I just up see is he gonna new note and then no is he gonna turn no edges subsea but we do want to some we want to store the value so that's not before we move to node I still current no time I value and then we want to do and then this will happen every place that's actually to help mister be factors already let's go ahead get edge and then just see for character maybe that's a little bit terrible right see not in some type inches and some time catches so see is your new node and then we just return self dot edges of see okay so now we this and then just to you can't hoc and depending on the problem you might need to know like whether and each node whether you know the string - ended and whether you know the string - ended and whether you know the string - ended and stuff like this which is typical for a string close but for discipline you only need to care about the prefix so we actually don't need to do that so that's the insert function and then the other one is to some motion which is just actually retrieving the value at for us and again we start the current node in self that would the root of the try and then for each key we just took her note is you know could we just move weight at all and then what we want to return is the current notes why you at the end yeah okay and that's mostly a I believe I coming on let's see here yeah okay so now stop that try what I go insert key well and then I could just return so I tried out some of key why okay fingers crossed let's see now lips prefix I don't know I maybe we're looking at something else clearly okay oh what Oh cuz I was talking my API which is now that I look at it doesn't make sense just why would you have a lie yeah I just copied it some before mentally but the fun in Tesla you know okay looks good on the input so I'm going to submit it cuz I'm gonna go when I'm trying a little bit y'all know oh noes maybe I miss went to prom yeah okay so I did miss Rita Palmer no but I think so the only one prefixes so the prefix only have to match where hmm wait I misunderstood this is the difference oh now like I just have a issues I think I just don't know no that's just an sadness I think I just don't add after we get the edge so on the last edge we don't okay that's a silly mistake really so it was accurate in how I interpreted I just have a off by one error as it happens that's one for the Kevin given I used to code every example for maybe I was a little me backup tested a little bit more that seems like a actually a very basic educates that I have considered but uh but oh noes oh the same accent's maybe I miss well this one I think oh okay so I did misread one part of it which is that if the key already exists then the original will be over win okay so I did get that well that's fine we could change that way quickly which is that on there insert well let's we could get to some yeah we could get to some might have to play around just a little bit but some of the previous thing now yeah you are right and today it's a little bit of weird day thanks for coming and blacks also hey okay that's what I was doing oh yeah put it you get the crunchy and then the new value is just the doubter did whoops quick resolution back stand by oh no solution I'm just really bad at doing it right like we got you are right oops is self-taught so oh noes now because it gets no there's an expense hmm okay what am i doing well so it for some of AP you should get five put app gets to three and then oh okay so I guess we do have to do the thing where we talk about they're keeping track of DN and I think that's where I was a little bit yeah I think there needs to be two different sums I was thing about a little bit but well close to update you only want to get those where those are actual ends okay oops he goes forth and then let's just say when you insert at the very end you said 2n is really true and then now let's just say previous some but in this case it's not a prefix as an actual key but we do copy and paste all this so if we return it otherwise we just return zero okay prepare to actually call it first for attack to work so let's actually do that I mean I think yeah you're not wrong but okay I mean I think I'm just trying to do it like da Quan code the textbook way right but you're not well okay let's try again this time move your left side ask you about missing edge cases so that is you know a point of CAM just been careful I mean I think the first one answer what would I get going on yeah this one I just you know and off by one error on my pointer moving so something that and also that's a very obvious test I should have done that and here I just didn't read the column correctly I don't you just keep on adding to it so I do add in something to fix that well war a straight ish representation of the implementation which why and as I said before like I have my call my colleagues have given tripe arms I've seen try bombs on interviews so that definitely something to practice on and this is a well to be a fundamental version of it with just make sure you know articulate all the test cases and edge cases complexity and stuff like to have you ever try like yeah we could talk about all and this times to size a bow for bait if you need but otherwise it's mostly right actually yeah I've seen him my like my buddy was on an interview where the problem was actually worse and the from Facebook or something but I mean maybe I'm wrong but so something done like I think I was just talking to someone about so yeah so definitely practice this recommended I mean you and I got a couple of submission errors but you know but that just being about deliberate and careful how this 16 minutes I think I did watch this one a little bit but that's okay I mean but you should know if you're doing an interview you have 45 minutes make sure you take your time pace yourself a little bit
Map Sum Pairs
map-sum-pairs
Design a map that allows you to do the following: * Maps a string key to a given value. * Returns the sum of the values that have a key with a prefix equal to a given string. Implement the `MapSum` class: * `MapSum()` Initializes the `MapSum` object. * `void insert(String key, int val)` Inserts the `key-val` pair into the map. If the `key` already existed, the original `key-value` pair will be overridden to the new one. * `int sum(string prefix)` Returns the sum of all the pairs' value whose `key` starts with the `prefix`. **Example 1:** **Input** \[ "MapSum ", "insert ", "sum ", "insert ", "sum "\] \[\[\], \[ "apple ", 3\], \[ "ap "\], \[ "app ", 2\], \[ "ap "\]\] **Output** \[null, null, 3, null, 5\] **Explanation** MapSum mapSum = new MapSum(); mapSum.insert( "apple ", 3); mapSum.sum( "ap "); // return 3 (apple = 3) mapSum.insert( "app ", 2); mapSum.sum( "ap "); // return 5 (apple + app = 3 + 2 = 5) **Constraints:** * `1 <= key.length, prefix.length <= 50` * `key` and `prefix` consist of only lowercase English letters. * `1 <= val <= 1000` * At most `50` calls will be made to `insert` and `sum`.
null
Hash Table,String,Design,Trie
Medium
1333
1,022
hey guys welcome back to another video and today we're going to be solving the leakout question sum of root to leave binary numbers all right so in this question we're given a binary tree each node has a value of either zero or one each route to leaf path represents a binary number starting with the most significant bit so for example the path zero one zero 1 represents 0 1 and binary which is well 13. and if you don't know how that conversion happens i'll show you how that works okay so for all leaves in the tree consider the number represented by the path from the root to that leaf and we return the sum of these numbers okay so for example we're given this binary tree over here and we have four paths so one zero is one path and we're going to consider one zero as a binary number and we're going to have 1 0 and 1. so those are going to be our four paths where they're all going to be in binary we're going to convert that to decimal values and then we're going to add them all up which in this case outputs a value of 22. so now what we're going to do is we're actually going to see how can we get that value in this case of 22 and what are the steps we need to take in order to solve this question all right so i'll have the same so i have the same tree over here so the exact same tree as our question and these are the four parts so we have a hundred and hundred actually represents the number four then 101 one zero one and these are all of its decimal equivalents okay so let's see how can we actually convert a binary value to a decimal value or integer value so in this case we have the number 100 so what we're going to do is we're going to start at the right most so for the right most it's going to have a value of 2 to the power of 0 multiplied by whatever this is so over here it's 0. so it's going to be 2 to the power of 0 multiplied by whatever value it is either a one or a zero so we have that and each time we're going to increase the power for the two by one so right now in the beginning is to the power of zero then it's going to be two to the power of 1 and we're going to add that so we're going to multiply that with this value again which is 0. so now we have that now we add it again and now we increase from 1 to 2 so now we're going to have 2 to the power of 2 and it's going to be multiplied by this value over here which in this case is actually 1. so how does this actually work out so 2 to the power of 0 is 1 multiplied by 0 it's well 0. over here we have 2 multiplied by 0 which is 0 and finally over here we have 2 to the power of 2 which is 4 multiplied by 1 which is 4. so this is how you get the value of 4. and there's actually so using the same idea uh we can kind of do this so it's the same idea it's just represented kind of differently and using this representation is going to help us to solve this question so what exactly is this representation so what we're going to do is we're going to have a running count of our sum so in the at the very beginning our so i will represent the sum in the color of red so we have a sum of the value zero so here it starts off at zero so what we're going to do each time we're going to multiply this value by 2 so we're going to do 2 multiply by 0 and we're going to add it by whatever the root or whatever node we are on so in this case we start off at our root so over here we're going to do 2 multiplied by our sum so two into zero plus the value of our root so in this case that's one so now our value is going to change from zero to two into zero plus one which is two into zero plus one so now our sum has a value of one so now uh just for the sake of this question i'm just gonna move to the left so now let's go to the left and right now our node is at the number zero so we're gonna do the same steps so we're gonna do two multiplied by our sum so 2 into 1 is 2 and now we're going to add whatever our binary number is so 0 or 1. so in this case it's 0 to 2 into 1 2 plus 0. so our sum is now 2. so same way now let's go to the left again and over here is going to be 2 into 2 4 plus 0. so over here we get a value of 4. so this is going to what that means is when we take this entire path we end up with a sum of 4. so 1 0 is nothing else but the value four so i'll just kind of write this down over here so similarly what we can do instead of starting from the beginning from our root over here we can just start off from here so we have one we have two and we can just continue off from two so instead of going all the way here we can go here which saves time so over here what we're going to do is we're going to do 2 into 2 which is 4 but instead of 0 it's actually 1. so 4 plus 1 is well 5. so the value of this path of one zero one is five as you can see over there so we have five and same way so we got everything for the left part now let's go over here so same step so one so two into one two plus one which is three and then over here for the left part so three into two six plus zero is six so this ends up with the value of six so one zero is equal to six as you can see here and finally this is going to be seven so as you can see doing this we actually found out all of our sums and the final answer is just going to be taking these four values and adding them up so 4 plus 5 9 and 6 plus 7 which is 13 when you add them up you get 22 right so and that's the value that we're looking for so how can we actually use this in our code so what we're going to do is we're going to find this concurrent sum for everything at the left most root until we actually end up reaching a leaf so we find it over here so we get one then we get two and then we get four and four so once we reach that value we get to a leaf so we're done so that is going to be one of our values and in that case we're gonna move up one time so we're going to start off this is going to be our root and we're going to check if it has a right child and if it does have a right child we're going to go to its right child and we're going to perform the same steps but in this case so the right child is the leaf so in that case we continue the sum value here which has a value of 2 we continue with that value and perform the same steps until we reach a leaf and in this case this value is a leaf so that's how we end up with 5. so in this case right now we've got everything on to the left of the root which is one so now we're going to end up to the right starting off with this value then we're gonna go to this node over here giving us a value of three so over here we're going to go to the left and we're going to go until we reach a leaf and over here we found out leaf and in that case we're just going to stop we're going to perform the calculations and then we're going to stop since we've reached a leaf and once we reach the leaf we're gonna go one up so from here we go back up here so now we're back at this one over here and once we do that since we already checked the left we're now going to check the right and do the same steps until we reach a leaf and in this case that's with the value of one and we find its value which over here is the value of seven so we're going to end up at the ending of this recursive call we're going to end up with four and five and six and seven so first we add four and five then we add six and seven and then we're going to add them both together giving us our desired answer which is 22. so if this is a little bit confusing i try to explain the recursion if not i think it should be a little bit easier when we get so in our function what we're going to be doing is we're going to be calling it recursively and each time we call it we're actually going to give it our current uh running sum so what do i mean by that so uh right now so if you were at this value we're going to give it the current sum which is the value 2. and if you were over here we're going to give it 4 and so on and so forth so in order to do that we actually need to have another argument so i'm just going to modify this function over here and i'm going to give it that argument so i'll just call this sum underscore and we're just going to give it a value of 0 in the very beginning okay and if you don't know what this means uh by giving it a value of zero so what that means is if you don't specify a value to it and in that case it's just going to start off with uh whatever value you give it so in this case we're starting off with the value of zero unless we mention otherwise so over here we're going to have our base case so if not root and if it doesn't exist and in that case we're just going to return a value of 0. okay so over here each time we're going to change our sum variable so this variable over here so let's call it sum underscore and what is it that we did to it so what we did is i'll just go to sum underscore we multiplied this value by two so multiplied by two and then we added it with whatever the value of the current node we are on is so to do that we're gonna do sum underscore multiply by two and we're gonna add it with root dot val so this is the same steps that we did earlier to keep changing our concurrent sum okay so over here we're going to check if this uh whatever node we are on has any children so it could be a right child or a left child so for this we're going to check so if uh sorry if root dot left so we're checking if it has a left root or if it has a right root so if root dot right if either of these are true we're going to end up going inside of this x loop over here so inside of this if loop what i'm going to do is i'm going to create two variables uh just for now and i'll change that up later okay so it's going to be x and y so what we're going to do first is we're going to call this function on itself for the left node so over here we're going to do self dot i'll just copy this over here sum root to leaf we're calling this function on itself and what is the root going to be the root is going to be the left node and uh we're going to give it our current sum so in this case it's going to be sum underscore that's what our current sum is at and so this is going to be a value for x and then over here we're going to do the same thing over here and instead of calling it on the left root we're going to call this on the right fruit so over here we're going to do root.right and if this is a little bit root.right and if this is a little bit root.right and if this is a little bit confusing i'll just show you what this looks like so i'll just print it out to show you what's actually happening and at the ending of this we're actually going to end up returning the value of x plus y so that is going to be our answer so over here now we actually have two more cases that we need to account for so one of the cases is so let's say we only had a left root and we did not have a right root and in that case what's going to happen is we're just going to end up returning 0. so we already took care of that and the other case is what if we are at a leaf so i'll just do that over here else so when we do not have a left root or a right root that means that we are at a leaf so when we're at the leaf as you can see over here all we did is we just returned this value of four and that's all we're going to be doing over here we're just going to return whatever the current sum is at so once we reach a leaf we're going to end up returning that sum so what i'm going to do is let's run this code once and i'm going to be running it on our same input as the example and as you can see this is what we end up with so the first time this is the x value on the left and the right is the y value so first we get four comma five so how does that make sense so first we get four over here and then we get five over here okay so that's what we get for the first time then afterwards we get six and seven so as you can see we get six and seven and in the last time we get nine and thirteen and for the very end and for the very ending all we did is we added nine and thirteen and in that case we just ended up returning that value of 9 13. so i just assigned it to variables to kind of make it easy for you to understand and we can just save that space up by calling this at the same time so instead of putting them inside of variables let's just do this plus this over here and let's just return it directly so it's the same thing and yeah so hopefully this does make uh sense using so i tried my best to explain it and do let me know if you have any sort of questions and let's just submit this okay i don't know why i got an error i'm just gonna submit it again and hopefully it works now okay yeah so as you can see our submission did get accepted i'm not too sure why we got that error but anyways thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if the video helped you thank you
Sum of Root To Leaf Binary Numbers
unique-paths-iii
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Array,Backtracking,Bit Manipulation,Matrix
Hard
37,63,212
1,402
Hua Hai Is Style Hello Viewers Welcome Back To My Channel Ko Pyaar Doing Great Rihai Manch subscribe To My Channel Year Please Do Subscribe Every Week Test One Playlist Cover Various Categories of Problems Subscribe Research Dynamic Programming And Don't Forget To Subscribe To You Can Link Description Box Office Collection Data On Co Shak Can Ask Any Medicine One Unit Of Time Flash Light Come Question Of This Difficult Till We Dish Including Reduce Amazon Section 30 Time Of My * Satisfaction Of Returns Time Of My * Satisfaction Of Returns Time Of My * Satisfaction Of Returns The Maximum Sum Of Time And Date Dasharath Can Update Subscribe And Subscribe Taken For Android Software Give The Giver Subscribe Question Level Updates - In The 68 Places Question Level Updates - In The 68 Places Question Level Updates - In The 68 Places - 205 - Certificate Se Number Negative - 205 - Certificate Se Number Negative - 205 - Certificate Se Number Negative Porn Oh Subscribe And Information Like Subscribe And Subscribe Not Just In Time The Can The First Previous Day Celebrate Beautiful Updates Time Taken Uday Dish Including Private Security Select Roadways Subscribe And 200 Share The Post Dish Attack One Minute One Unit Certificate Unit But To Friends But What Where Is It Include Subscribe On Screen Four Subscribe Like Subscribe And Subscribe subscribe this Video give a video by aman dashrath preparing that was delighted to avoid such actions and subscribe discovered person with oo the calif me 70 like time to sentence maximum expected to return the maximum light to turn off the different types of problems will be approaching a dynamic programming ok sorry the first form Yudhishthir Wedding Android Souvenir Print Change The Celebration At A Shop In Difficult Subscribe Start Wear Look On First As Per Thursday First Name You Don't Have Seen That's Positive A In That Case To Maximum Life Like A Question To Loot Get Any Better Than 200 Subscribe and subscribe the Channel and subscribe the time from all the elements will subscribe from attachment from left to right time with that for the time set money return file not just increased late evening play list listen that Sindh P that they would assure this alert to Describe involved day they can consider them with r with negative satisfaction all tulsi effective wall rahul dravid and co tight main pramod it 5 sec or na saunf vr points 650 co tight friend personal development from bank celebrate his mother like kar but i don't repeat picture and Subscribe and Total Time Subscribe Negative Numbers Name Calling WhatsApp Number Satisfaction To All The Number Video Tree Section Swayam Calling Affairs Current Subscribe Will Be Replaced With Numbers And See The Like Share And Subscribe liked The Video then subscribe to subscribe and subscribe yes brother second element then edit morning last time try the element - 9 inch plus five last time try the element - 9 inch plus five last time try the element - 9 inch plus five is - 4 - 4 - 9 - shyam destroyed the jai hind is natak chale - 09 - 9 - - - - sid basically this and current Tax Rahul Dravid to decide on informed soon results Sudhir and satisfaction of first features shopping midding - - - Subscribe now we are going to midding - - - Subscribe now we are going to midding - - - Subscribe now we are going to start with start channel subscribe 2012 subscribe button follow the is the what minute so now the equation for this Time to time basically a look at this time e main love like platform time for introspection 500 screen ki 2.1 introspection 500 screen ki 2.1 introspection 500 screen ki 2.1 subscribe must subscribe 203 ki a person host galbe a subject but I don't like it hello viewers hour wise respect curtain understanding security service tax And Disorder Special Next Veerwal Suicide Solve Want To Buy Doing Something Subscribe Now Just That Subscribe 12345 1034 Panch Subscribe So 2810 Calling Subscribe Cigarette Diner Dash Lein Vidra Vivo v5 Hai Na Might Applied The Student Life Time Question Model Donkey Side Reaction Novel Consider All The Missions Favorite Na Udhar Withdrawal 6 day Collection Multiply 3537 More Revenue And Argument User Guide You Have Been Calculated The Like Subscribe And Share Subscribe Almost No Time Which Will Be Used In Wedding With You I Am Quite A Hai But Will How to Reduce and Selecting Few Were Going to Reduce Thursday Calculating the Time That They Can Employ the Technique of Clips Subscribe Thank You Will See What They Want to Know I'll Just Like They Introduce 3 Steps Where Quite Do the Thing This Example Amount computer se example and will go through the grid by using eclipse in the place where not going to calculate fog notification to select which 1234 super fighting with savage child died due to calculate the condition contained in the second time in words Mr. Krishna Hai 1234 Ride From This Of Words One 4 - Hai 1234 Ride From This Of Words One 4 - Hai 1234 Ride From This Of Words One 4 - One Two Star 03 President 18.85 So Without One Two Star 03 President 18.85 So Without One Two Star 03 President 18.85 So Without Limits Of Baroda Sunao Main Left Side Ka Rate Latest Current Set The Current Situation What They Are Saying They At This Location Half Inch Subscribe Now To Receive New Updates Elements Class 12 Flash Light A Previously Disha Obscene Subscribe My Channel Subscribe To What Is The Meaning Of The Day Torch Light Suna 2802 Can Not Satisfied With Karan Salt Next Update 121 That Tweet And All Should Not Reduce 103 Case No - 142 103 Case No - 142 103 Case No - 142 37 Miles - 60 Adventure Update Mac Set Up 37 Miles - 60 Adventure Update Mac Set Up 37 Miles - 60 Adventure Update Mac Set Up Flash Lights Does Not Destroy Update Sab Movie Gond Se Chaar Desh Ke Naam Video then subscribe to the Page if you liked The Video then subscribe to subscribe our Main Camera Time 8:00 am Saat Char Gautam Main Camera Time 8:00 am Saat Char Gautam Main Camera Time 8:00 am Saat Char Gautam Distick Will Like it will be using dynamic programming techniques of this a lesser time complexity please don't drink water and welcome back with time and this time and space welcome back so let's go and come put on sunao 56001 the first dob ​​set a great side effect on that first dob ​​set a great side effect on that first dob ​​set a great side effect on that aam Therefore lion the multiplication tractor illegal vehicle and ink system apps wala section 2010 and positive express - wala section 2010 and positive express - wala section 2010 and positive express - 119 bullion vid0 and positive next point two forms in its adherents of life in a positive way current amazing 20202 check non 2014 that sister amount in class bill index wife Mountain Means The Minus One Is The Last Interact With Its Not 208 Not For The Soft Subscribe Now To Receive Thursday The Positive Numbers subscribe this Video plz subscribe Unit Only But They Should Consider All Subscribe Like This That Aaj Parda Description Software Doing Or Types And Curative Invest All Things Would Stop This Thursday Subscribe Now Video then subscribe to the Page if you liked The Video then subscribe to the Page What They Are Doing Printing Rate Current Number 90 Number Plus I subscribe this Video plz subscribe Channel Please subscribe and subscribe the Subscribe Channel Thank You Arrest Sunar Malik Se N Is The Length Of The 267 Points RX100 Any Sort Expert Baking Powder Your Login Time Will Be Ordered In Law And Order On 200th Test Unlocked Plus Right And Roots Par Loot Going Through Which This Is A Friend Thank You That Kalyan Jain Sudhir Value Will Be Going To Subscribe Only One Positivity And Will Be Going All The Final 10 Subscribe Video Subscribe Log In General And Subscribe Alarm As Lord Of Love And Sacrifice For Using Any Space Express They Are Living In The End Subscribe Like And Subscribe With Constant Speed ​​Of Light And Subscribe To That Is Vitamin Questions Please Comment In The Comment Section They Will Get Back To You And Another Posts Tagged Every Politician Will Have Two Languages ​​Basically This Further And You Languages ​​Basically This Further And You Languages ​​Basically This Further And You Will Find Two Languages ​​subscribe To My Will Find Two Languages ​​subscribe To My Will Find Two Languages ​​subscribe To My Channel Please subscribe and Share and subscribe the Channel and in description Video A Continuum History Went subscribe To My Channel This Please Subscribe And Share With Your Friends Also Please Click on the Bell Icon Solid You Will Be Notified About My Videos Thank You For Watching With Problem Specific Way Was
Reducing Dishes
count-square-submatrices-with-all-ones
A chef has collected data on the `satisfaction` level of his `n` dishes. Chef can cook any dish in 1 unit of time. **Like-time coefficient** of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. `time[i] * satisfaction[i]`. Return _the maximum sum of **like-time coefficient** that the chef can obtain after dishes preparation_. Dishes can be prepared in **any** order and the chef can discard some dishes to get this maximum value. **Example 1:** **Input:** satisfaction = \[-1,-8,0,5,-9\] **Output:** 14 **Explanation:** After Removing the second and last dish, the maximum total **like-time coefficient** will be equal to (-1\*1 + 0\*2 + 5\*3 = 14). Each dish is prepared in one unit of time. **Example 2:** **Input:** satisfaction = \[4,3,2\] **Output:** 20 **Explanation:** Dishes can be prepared in any order, (2\*1 + 3\*2 + 4\*3 = 20) **Example 3:** **Input:** satisfaction = \[-1,-4,-5\] **Output:** 0 **Explanation:** People do not like the dishes. No dish is prepared. **Constraints:** * `n == satisfaction.length` * `1 <= n <= 500` * `-1000 <= satisfaction[i] <= 1000`
Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0). Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer.
Array,Dynamic Programming,Matrix
Medium
2192,2193
517
oh cool 5:17 super washing machines Jeff oh cool 5:17 super washing machines Jeff oh cool 5:17 super washing machines Jeff and super washing machines on online initially each washing machine has some choices or is empty for each move you can choose any M where m is between 1 and N 1 to n washing machines and press pass one dress of each washing machine to one of its adjacent washing machine at the same time this is one of those problem to have no relations to real life given an integer a way where we're sending the number of dresses and you tomorrow a machine from left to right on the line you should find the minimum number of moves to make our washing machines have the same time address if it's not possible we turn the grip 1 okay let's see ok seems maybe straightforward I think you just do like a linear scan and then either divided by 2 or something like that now I'll explain at the end if it happens to be right a bit bonded you know I've been doing a couple of contest is and so I've been showing my wearable name which is not great for in degrees obviously so definitely yeah not as time constrained answer negative one that otherwise it's always possible let's just say call with you this is a heart thank me I'm good we applied it's something like that over this I think this one way it needs to so it would get to Pho next one so you just plus two in it this one you need three and that's five looking at movers I think this part is valid no matter what but at the same time okay tomatoes I'm except for numbers to go way so is it just like to the forest we do it at the same time oh that just has happened at the same time excuse me if I understand just one little bit let me stay there's some like real provocation east stuff actually like that I'm I know that reminds me of something but I don't have a great articulation around it oh wait this is right but I'm just see well that's just odd but all right I have been of course that makes notes actually let's play my test cases did you say I have this heart so I just think that one de-excited my math I just think that one de-excited my math I just think that one de-excited my math wall and I could never like winter I think today I'm counting the reason why this may be works yes because the way I'm counting it propagates it forward it's almost like because I think the way I'm thinking about it when you see a current machine you're just moving negatives instead of pluses so you know that you're gonna have to take extra size from the one next to it but I don't know that I factored in the simultaneous one so that's one I feel like to be honest a lot of does it just cut and done like I feel like I've seen something similar before and that's why I'm doing this way that I can't prove it to myself or to you guys because we could so the first washing machine and just take one blue why this is - how'd I just take one blue why this is - how'd I just take one blue why this is - how'd I get no cuz this one takes - all right get no cuz this one takes - all right get no cuz this one takes - all right miss a bit and then get a wrong answer so I could see why because I can't come up with a good case okay so this is finally because I keep on thinking about one generator but this is now a case we have two generators so that their simultaneous part finally comes in a point okay I'm happy that this problem is not as silly as it is but well I don't it would be because I just couldn't I've been from one dress one machine maybe that's true but uh but yeah of course if you just even remove one side of it or maybe even just make it just two women to test and I can't do math okay so that's right but from multiple choices which I think gachy does it never makes sense for addresses to cross my so I think there's PI ways to kind of break it up to one problem that make sense like a combination like a linear combination of multiple problems and I think that probably figure it out I think that's how you would solve it and but that's an easier set statement than done because what does that mean like something that resets it to what is the Visayan condition it is fine well actually I guess whoops why don't we turn to light things okay oh hey full of destroyer welcome to swing mm-hm swing mm-hm swing mm-hm hope jab good luck on your results you know your had it already this was the only case where I called left and right on the same one which this does not occur Oh No Wow you mean like literally just had an interview oh that's uh huh I mean that's intense but I mean I said that as I'm doing it did code sir oh yeah still good luck I don't you mean like recently I'm just hacking to be honest it's missing oh wow Tammy that's great yeah I mean that you know that you should get over the initial pose because we knew that's maybe that's the way to Christopher cause I'd to peak I'm gonna try something and then maybe see if that's why I'll knows well and this is one of those I don't have a good intuition about this file like 35 so seven so I guess that's a case where you get to at the same time and this is a this one of those things where it's gonna end up being a brain teaser I am just covering two edge cases way Coast a one by one I guess I'm gonna like gesture yeah good luck definitely yeah a lot of great companies out there these days that definitely for everyone's interests hmm just head away yeah no justice sir thank us as a matter actually it's just a different way hmm this one sometimes too gives them in 2003 from like you know all right how did I get six on this four moves always brings his sex because this is George but let me just uh turned out to be abstractly hmm another from the bankers I think because it thinks is six down that's why it's doing it you could still see during the book of my face because I okay I think I got some science incorrect assumption but I think mostly was okay having yeah I'm I thought I had a pretty bit but I think so yeah so the reason why I kind of went down this Wow I think what is some of that was intuition I mean I think some of the initial like this photo extends but like you can't do it you just can't do it doesn't divide you coolly and for me it's about looking at the peak the peaks because I think it's natural to come look at each or my initial dot Willis to look at each machine that need stresses and kind of try to figure that out which is my god Cole - Joyce I think what you Cole - Joyce I think what you Cole - Joyce I think what you actually want is the other way we're like ok for each dress or each machine that has too many dresses what they have to go somewhere right and it'll take at least that many turns to go there so that's kind of how I came with Costas I don't think that explain to that welder because I still didn't fuzzy in my mind to be honest as it is two plus here so it's now this is for because I noticed an in two moves this won't be done so then it adds a little bit more because then it carries to one that's far away that makes sense however you could wonder there's a mathematical property somewhere where you also have to like still I mean two kind of weird ish intuition it's like I still think we're like this how does that work I mean obviously it works but it in notes Ted how does this oh okay I think that's the part that I got a little confused about what he's thinking of but now that makes sense because I think what I was thinking of is that okay just a - so it carries one like a okay just a - so it carries one like a okay just a - so it carries one like a ticks I don't know six or seven turns to get to the beginning because you just have one dress and now like the two is here but what actually happens is because they don't happen at the same time the last number okay the last machine passes to the second-to-last and machine passes to the second-to-last and machine passes to the second-to-last and just the one like everything shifts over so okay so that's why the peak thing works okay I mean I think I be honest I think some of that this is a way Artois had to submit three times to get wrong guys to kind of get QWERTY I think some of that is that to be honest like some of that is just gut feeling and that it is intuition in working backwards it because it's something that I felt like I've seen before we've not just a particular problem but something similar I think that's something that you get from just doing a lot of practice and you know you see me just get this a lot yeah and just have a very would be way I know I'm gonna interview because you know as you can listen to me I don't know if I could take lated that well like the reasons why I like I could like yeah I mean knowing the end knowing the code like I could explain it a little bit and maybe pretend I know a little bit more than I do and I think now that with this case I do have a live a movin into intuitive sense because I think I was just that I didn't have that light bulb on we're like well if it already reached when it needs to be then it just doesn't move their cup of other kind of invariants in there as well that I kind of thought about but maybe I don't think I talked about which is that for example for each given washer or the dresses only go in one direction meaning like it makes no sense for like dresses to cross right which i think is obvious ish but it's something to think about and that's why I like some of this you can do an event time because you know only floats in one direction and because they're only falls in one direction you could actually propagate to negative dress forward epidemic sense but it's just like passing a positive dress backwards and that's how this thing kind of makes sense I think but yeah it's and I don't even I definitely please keep on asking questions of you want me to keep on explaining it I feel like I'm seeing the same thing in different words which it's not no value it's just you know there's some value in that but I feel like I'm I don't know how much convincing people would need in general because I don't know about that convinced mmm I mean now I am more convinced an earlier but you know but definitely a tricky one no I mean I would say I like I mean well yeah I mean I don't every I would hate to have to see this on my interview I like I mean do be doing well maybe not now because I know the answer but they're enjoyable but I like it as a brain teaser because it's kind of like this er just there's a lot of like deconstructing some stuff I mean it's sad a great interview question also cause like decoding is very short so you don't get a sense of like someone's coding bar it's like this is literally like a four loop you could debate the merits of Dallas like putana and programming go si is always full juice but at least in that like you really have to understand it but uh yeah I mean I like to kind of get interest but uh yeah but yeah I mean I this is one of those brainteaser eeproms that like if you get an interview sometimes you just kind of do the best you can and you know try to grind it out try to like get hints and kind of a go step by step having on just one the good thing about that point at least in terms of working toward a solution is that there play a lot of hints you could give and a lot of them don't click unless you have them together so maybe that's a good thing but I don't know that's not my style why would never ask this but uh it's a very fun problem though I don't know yeah that's what I have for this month we're cool
Super Washing Machines
super-washing-machines
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time. Given an integer array `machines` representing the number of dresses in each washing machine from left to right on the line, return _the minimum number of moves to make all the washing machines have the same number of dresses_. If it is not possible to do it, return `-1`. **Example 1:** **Input:** machines = \[1,0,5\] **Output:** 3 **Explanation:** 1st move: 1 0 <-- 5 => 1 1 4 2nd move: 1 <-- 1 <-- 4 => 2 1 3 3rd move: 2 1 <-- 3 => 2 2 2 **Example 2:** **Input:** machines = \[0,3,0\] **Output:** 2 **Explanation:** 1st move: 0 <-- 3 0 => 1 2 0 2nd move: 1 2 --> 0 => 1 1 1 **Example 3:** **Input:** machines = \[0,2,0\] **Output:** -1 **Explanation:** It's impossible to make all three washing machines have the same number of dresses. **Constraints:** * `n == machines.length` * `1 <= n <= 104` * `0 <= machines[i] <= 105`
null
Array,Greedy
Hard
null
1,877
hey everybody this is Larry this is day 17 of the Lego day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem uh my SD card got corrupted uh while I was in uh KOB so no um no intro today or like this is the intro so hope you understand but right now I'm actually in Osaka so uh I'm excited I'm you know it's my second time here uh but first time in with any length of time so we'll see how that goes today's Farm is 1877 minimize maximum pair sum in a way all right let's see what does that mean the maximum pair sum is the largest pair sum in the list of pairs okay that makes sense given a sum of even link pair up such that the maximum pair is minimized okay I mean you can kind of do this a couple of ways you can do it with like binary search as well but I think the way to do this is kind of greedy um the thing is that okay so you want to minimize the maximum sum right so the biggest uh the idea with this greedy uh proof is going to be um what's it called uh Exchange argument right so let's say you have a c d right you know and we have dot but you know for exchange purposes it doesn't really matter and let's say this is in sorted order just to be clear so a is less than b um a is less than b less than C less than d right so of course the idea is that you want a plus D um and you want the pairs to be a plus d b plus C right why well because and then this is just like basic exhaustive thing right because if you do a plus b and then uh what is it C plus d then all because of this thing then this uh this is going to be um and you could there are a couple ways you can write this right like maximizing or sorry minimizing the maximum uh but C plus d is going to be bigger than well obviously a plus b but C plus d is also going to be bigger than b plus C and A plus d right just by definition of the order of things and then another way that you can write it is going to be a plus uh what is it a plus c b plus d but also really the same argument so this exchange argument right is that this is going to be a bigger number than all of them except so to minimize this number or this the second sum you need a plus d and that's really the way to think about it uh I think I mean obviously this isn't a hard proof but that's going to be the idea of what you to I mean you can also I know that you may have questions about like hey but what a B plus preious b plus C is greater than a plus d right like and that you could easily do something like that like one uh 100 and 101 then obviously 100 you know plus 100 is going to be bigger but then now you can also think about well in that case then you're trying to minimize this right well you can minimize this uh and maybe the other way to think about it then now is that you want to minimize a plus D minus well this some I guess this is a whatever but something like that right so you're trying to minimize this and then with that you can kind of do some exhaustive thing to kind of prove to yourself I'm not going to go over that in that much detail just because you know it's just more of the same of just going through all the cases really um right because if uh and you could just write even like um like if you're not good with proofs and I'm not I'm just saying that to myself if you're not able to good be good with proofs then um then you know then you could even literally write it out like very exhaus and what I mean by that is well I said a plus d is equal is greater than b plus c we already kind of went over it right so we have all these argument maybe even copy and pastes to here right and then now you can maybe say like okay well if B plus C is greater than a plus d then what happens right well then now you have two sums a plus d b plus C and you're trying to minimize uh you know this thing right or get away maybe it's absolute value so it shouldn't matter and then the idea here is that okay well you just exhaustively go through all the possibilities and basically the idea here is going to be that you have two signs right you can assign two negatives to here I know there's an absolute value but then now be B plus C so then is greater than a plus d so that means that now in theory you can actually reduce this to B+ actually reduce this to B+ actually reduce this to B+ C minus a plus d because you know that this is going to be bigger so this is the positive sum that you're trying to minimize right and if you do that then you can also just write it out right and then now you're trying to figure out okay well in this case um like how does this compare to I don't know B plus a like let's say you want try well I guess C is the bigger one so let's just say c plus a minus B plus d right and how does this sum compare to this sum right and so stuff like that is the general idea and you could kind of go through it right because in this case uh the C cancels out so then now you're comparing these two sums right um the minus D also cancels out obviously so then now you have these two but then here now you know that um B is greater than a so therefore uh if you're trying to minimize then this is going to be a bigger number right oh sorry yeah right oh sorry this is going to be a smaller number I think that's the general idea anyway I mean you could also I think this is uh maybe that's a little bit inaccurate but I think that's General the idea um and then when you expand it out it just really becomes something like this right so you have like a b c d and then you want to just match up e f g h because then now you could kind of do an induction e kind of thing I my apology is that today I'm a little bit hand wavy uh man I'm so tired but uh but yeah but that's basically the idea and then once you do that then you can just figure it out because you have 10 equals to uh n is equal to 10 to the 5th you sort nums and then it is just literally uh highest is equal to zero and then for I in range of n right it's going to be num sub I uh plus num sub I nus i- one and then sub I nus i- one and then sub I nus i- one and then highest Max of highest this and of course you can also just take it by half because then you know you go over with that I'm too lazy to write that out so yeah um yeah it give a nice little NCH of submit and that's pretty much it right uh I mean that's and it also works logically as well obviously because if you have just like any like if you try to group them in any other number uh in any other way you know one of them is going to be more sub optimal like for example if you swap F and D well C plus e is now going to be bigger than before oh wait no well D plus f is going to be bigger than before but c plus c is going to be smaller than before I don't know you have to uh maybe today just not proving day for L uh but yeah but obviously this is going to be unlock in uh and this is O of n so n loock and time o of n space uh and that's all I have for this one do I can I do it in someone mentioned over one space is that true well there's no structure so I don't know h apparently there's a linear one actually let me take a look real quick okay someone told me there's a linear solution in my Discord trying to think I mean yeah okay huh all right yeah why don't you also just always make an array of size of billion and then it's always constant um anyway but the but you can just create an array of size 100,000 and make it all an array of size 100,000 and make it all an array of size 100,000 and make it all one time right H don't know I understand this one I you get the max and the Min okay fine oh it's linear in the sense that uh but that's not linear and people abuse linear in a weird way I mean this to end that they're talking about is not the same as this end right the end they talking about is this end and it's linear in a sense that like it's linear in a sense that it's linear sorting but it's not like when you sort of linear sorting um with you know and there's something I'm not going to go over it I don't have the energy to go over why that's little bit inaccurate but uh yeah uh all right well with that in mind then that's all I have for today let me know what you think stay good stay healthy to go mental health uh I'll see you all later and take care byebye
Minimize Maximum Pair Sum in Array
find-followers-count
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs. * For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`. Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that: * Each element of `nums` is in **exactly one** pair, and * The **maximum pair sum** is **minimized**. Return _the minimized **maximum pair sum** after optimally pairing up the elements_. **Example 1:** **Input:** nums = \[3,5,2,3\] **Output:** 7 **Explanation:** The elements can be paired up into pairs (3,3) and (5,2). The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. **Example 2:** **Input:** nums = \[3,5,4,2,4,6\] **Output:** 8 **Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2). The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `n` is **even**. * `1 <= nums[i] <= 105`
null
Database
Easy
null
1,837
what is going on everybody it's your boy average leader here with another video and today we are tackling number 1837 sum of digits in base k this question is pretty new and hasn't been asked by any companies just yet but i can see this one being asked by a few in the future if you guys can go ahead and hit that like and subscribe button that would mean the world to me it helps my channel out a ton by giving it more exposure to people that don't know me and if you want to see another problem done just comment down below and i'll make sure to do it for you and with that all out of the way here we go so given an integer n in base 10 and a base k return the sum of the digits of n after converting n from base 10 to base k after converting each digit should be interpreted as a base 10 number and the sum should be returned in base 10. okay you know the thing about some of these interview problems half the battle is just trying to figure out what the interviewer is trying to tell you and this is just too much packed into like two sentences here um but i think the easiest way to understand this you know jam-packed problem is by this you know jam-packed problem is by this you know jam-packed problem is by looking at an example and uh you know figuring out how they got their output for the given input that you know we have and uh you know to make things a little bit simpler i'm gonna do this on the ipad so let's move over okay so i took this example that we have right here straight off of lead code and um remember what was the question asking us we had to return the sum of the digits of n which is this right here after converting n from a base of 10 to a base of k that we have is our input okay so basically how are we getting this 9 well we're converting uh n which is in base 10 so we're going from base 10 to a base k which in our case is 6 and converting 34 which is a decimal of base 10 once again to a base of six that actually is 54. and i'll explain how we get this um in a little bit but just trust me that we're going from 34 of base 10 to 54 of base 6 and all where all we have to do from here is just sum all of the digits of our newly converted number to get our output so here we add five plus four because those are the digits of our newly converted number and that gives us 9 which is the answer to this problem so the real key to solving this problem is understanding what it means to be of base 10 or up base 6 or of base k and converting from one base to another because if we can convert from one base to another all we have to do is just sum up those digits of the newly converted number okay that's what we're doing right here so what does it mean to be of base 10 well that's how all of our numbers are like usually written like the numbers that we talk about and think about on a daily basis those are all uh decimals or aka base 10. okay and there's a few key characteristics of being a number of base 10 and those are each digit can be one of 10 numbers now for a decimal what i mean by this is each digit of a number can be any number that's between 0 to 9. i mean that's how we write our numbers right like any number can be written with an integer from zero to nine isn't that true an example would be like you know if we had uh the number 999 with uh this leftmost nine being in the ones place the next nine being in the tens place and the nine after that being in the one hundreds place at each individual digit this one only has three digits right each digit can only go from zero to nine if i want to go to the thousands place i can't put a 10 at each at any of these uh placeholders right that's what i mean by each digit can only be one of ten numbers zero to nine um so this is the first you know characteristic of a number being in base ten and another thing is that like you know like we have here every multiple to the left of the ones place is multiplied by 10 or you know basically by the base that we're in and uh you know an example that we already have up here is that you know first we have like the one the ones place right here then we multiply by 10 uh to the n to the digit to the left of it and then we get the tens place then we get the hundreds place and if we were to keep going we'd have uh you know one thousand ten thousands place in the hundred thousands place and so on and so forth right so that you know these are the two big things that kind of make a decimal or a number of base 10. um without even realizing it to make sure that a number is actually in base 10 do you know how we would check that well let's just say we had you know this number 999 right the way we check that it's in base 10 and that it's an actual decimal is we would just multiply each of our numbers here by its multiplier on the bottom and just add that number together so we'd have 9 times 100 equals 900 plus 9 times 10 equals 90. plus 9 times 1 equals 9. and when we add all this up we get 999. um and you know i'll actually do this with another example just so you guys you know see which nine which actual nine this is which actually nine that is and you know which nine that is so if we were to do the same example with this example 243 well we see that the two is in the hundreds place right so we'd multiply 2 by 100 and that gives us 200 and we have 4 in the tens place so we have 4 times 10 and that gives us 40. and we have 3 in the ones place so 3 times 1 equals 3 and once we add all these things up we get 243 and that's how we represent our numbers as a decimal or a number that is a base 10. so you know this is really cool this is all you know numbers in base 10 this is all i'm sure this is all stuff that we've seen before now most cs majors we take a class where we learn um about binary numbers and a part of that curriculum of learning about binary numbers is converting a number of base 10 to a number of base 2 or a binary number and you know converting a number from base 10 to base 2 is very similar to what we do what we did before what i'll typically do when i want to represent a number in base two is uh i'll have all the placeholders written out so for it for example what i mean by that is i'll have all the placeholders but not like this right and i would have the multipliers written out for each of these individual placeholders so like we did uh for a number in base 10 we wrote the ones place to the far for the far right so i'm gonna put one right here and every number to the left of that one we multiplied by 10 and then we multiplied that number by 10 and we just kept going on like that so if i were to do the same thing in base two here to represent a binary number uh i would multiply each thing to the left of the ones place by two so i'd have 1 2 4 8 16 32 64 128. now to convert a number from uh decimal to binary we would do something very similar to how we did how we wrote you know this number 243 i would just uh you know put each of these numbers in the proper placeholder so that it can be multiplied properly and added uh and added properly to get like the number that we're looking for so for instance let's just say i had the number 100 and this would be a base 10 this would be a decimal okay to convert this number to a base of 2 how i would do this is you know if i put a one right here uh that would mean that our number is like at least 128 right it wouldn't make sense to uh put a one there uh an example would be like you know if i had like a number in base 10 uh let's say i was i were going to represent um 1000 in base 10 right so we have 1 10 100 1000 10 000 here and then 100 000 here if i were to represent 10 000 uh in base 10 i wouldn't put any number in this spot right here right i wouldn't put one here or two or three or any number up to nine in the hundred thousands place right because the second i do that we've made our number at least one hundred thousand right or if i put a two here we'd have to make sure that our number is at least two hundred thousand but if i were to represent like you know nine thousand twenty four or something like that right it's a weird four but uh let me rewrite that four right if i were to represent 9024 i cannot put a number here and i can't put a number in the 10 000 place because if i do that then you know we've instantly made our number at least 10 000. so to properly uh write this out in decimal i need to put a nine here and then you know like a zero here or two here and a four here okay so the whole point of this is we can't put any number in the placeholders that have a multiplier larger than what our number actually is so using the same idea to convert 100 to a base of 2 we shouldn't put any number in the 128 place oh and by the way since we're in binary we know that each digit can only be one of two numbers now and when we were in base 10 we had each digit could be written as one of 10 numbers you know we can have 0 1 two three four five six seven eight and nine but now in binary we can either we can represent each digit as a zero or a one so at 128 i'm going to put a zero but now uh at 64 i'm going to put a 1. since this is the biggest number that we can uh represent 100 as now when i do that i'm going to do this here i'm going to erase some of this stuff so we have a little bit more space here now when i do that i'm going to take 100 and i'm going to subtract 64 out of this and i'm going to get 36 left okay so now this is the number that we have uh left to play with so now when we look at the 32 place order we see that we can 32 is the next biggest number that we can take out from 36 and still have uh you know this number be represented as a binary number so we're going to put a 1 here instead of a 0 and we're going to subtract 32 from 36 so now we have 4 left okay so now we go and look at the 16. does it make sense to put a 1 at the 16 no we shouldn't do that uh because if we put a six if we put a one of the 16 then we need at least 16 uh you know left for this to be properly represented as a binary number so i'm going to put a zero here and for the same reason i'm gonna put a zero at the eight but look at this now we're at the fourth place right if i were to put a one here uh then that would take care of our entire binary representation because one once we subtract uh four from this number we get zero and um you know now we're done representing this number as a binary number we can put zeros for all the uh placeholders left and to double check that we converted this number properly into a binary number uh we could do the same thing that we did here where we are multiplying each placeholder by its multiplier and add it all together to see if we get the proper decimal number so uh in our case we have a 1 at 64. so i have 64 times 1 plus when we have a 1 of 32. so 32 times 1 plus a 1 at the 4 place so 4 times 1. and if we add this all together uh we just get 10 9 10 1. we get 100. so this is how we would convert a number from base 10 to a number of base 2. now you can see how tedious this process was right here right now we i gave us an easy number 100 was pretty easy to represent wasn't too bad but if we had like a an outrageous number like 52 344 or something crazy like that you know we'd have to be very careful with our multiplier like we have to make sure that you know 256 5 12 10 24 we don't make a mistake while we're making our multipliers and then you know subtracting our number uh properly like you know how we subtracted here that we need to do that properly as well it there's a lot of ways we can make a mistake by doing you know this type of conversion right here um and you know where we're like subtracting from our number to get the proper binary number but to make things a little bit easier there is a specific trick out there all right and i'm going to show you this trick and this is how we're going to solve this problem as well as uh this is this side this trick is what we're going to actually code out so i'm going to start a new page and what is this trick well we're gonna do the same thing we're gonna convert uh 100 of base 10 to uh it's binary uh binary part since we know what that number is up here then the number that we're trying to get uh trying to get is zero one zero okay now the way the trick works is you need to oh here let me write this out mod by the base you're trying to convert to and divide by the base you're trying to convert to and keep doing this until our number that we're dividing is zero okay so these are going to be our three steps now what does this mean so watch this i'm going to have my number 100 which is in base 10 and to convert it to binary of base 2 i'm going to mod this first by the base that we're trying to get to so base 2 so i'm going to mod this by 2 and what is that number that we get zero here okay now what now the important thing to uh and i want you guys to keep in the back of your head is we're gonna hold all of our modded numbers like in our head we're going to hold these to the side okay and now i'm going to divide uh 100 by our base which is 2 and that is 50. so this is the number that we're going to mod next okay so and this is the number that once it this turns zero uh we're done so now i'm going to take 50 and i'm gonna mod by two and once again we get um you know 50 divided by 2 is 25 that's a remainder of zero so 50 mod 2 is 0. now we're going to divide this by 2 and we get 25 now 25 mod 2 equals what this is going to be where we get our modulus or a remainder of one so i'm going to put one here and we're gonna do 25 divided by two and this equals twelve okay so now we have uh 12 mod two and that gives us zero and then we do 12 divided by 2 and that gives us 6. and now we do 6 mod 2 and this gives us 0. then we do 6 divided by 2 and that gives us 3. we're almost there now we do 3 mod 2 and this gives us 1. then we do two divided by two i'm sorry then we do three divided by two and this gives us one and finally we're almost there now we have one mod two and this gives us one and then we do one divided by two and this gives us zero and now we are done this is what's going to signal to us that we're done now i what i want you guys to do is take a look at all of the numbers that we get left over from our modulus and assuming that i did this correctly if we write these uh these modded numbers in reverse right what i mean by reverse is you know we started our first modded number is zero but our last model number is one so if i wrote all our modded numbers in reverse order you will find that we get the binary representation of this number so if i wrote this out i get 1 0 okay and if we look above here what do we get 0 1 0 if i look here if i were to add another 0 here we get 0 1 0. this is the exact same number that we got all the way uh up there you know and here just so you guys can see i don't know how ugly this is going to become but i'm going to copy this and i'm going to put this right here look at that same it's the exact oh boy exact same number okay isn't that so cool and i mean look i mean all we got to do is like add on another zero that's no big deal i think that's a part of the trick just add on one more zero until the end of that but uh we're not asked to you know output the converted value right all we have to do is output the sum of our converted value since we have all of the digits of our converted number held after we mod our like you know specific number and since we just add a zero to the very end we just have to have like a running sum the entire time and just you know add our modded number to our running sum and we just you know output that sum at the very end so yeah this is how we're gonna do this problem we're just gonna keep dividing and modding our number until we get zero and uh we're gonna have a running sum that we're gonna constantly add to and we're just gonna return that running sum so yeah let's move over to the code all right who's ready for some code i know i am so what i like to do when i start these problems is ask myself what are we trying to return well we need to return the sum of all our digits after we convert our number from base 10 to base k so i'm going to have a sum variable that i'm going to return at the end and i'm going to initialize it to zero okay so after we're done with our problem we're going to return our sum all right now remember what did we do we kept dividing our number n by our base k right so when did we know when to stop doing our division well when our number equaled zero or you know when we kept dividing our number up until we just didn't have a number to divide anymore because it was zero that's when we stopped so i'm gonna have a while loop all right and i'm just gonna say while n uh is greater than zero we will keep dividing our number n equals and divided by k all right and uh what were the numbers that were important for our for the sum that we're going to return you know what are the numbers that we kept adding to our sum which will be the thing that we return well it was just those modded values right so all i'll do is sum plus equals uh n mod k which just takes our current number that we're at and it's going to mod it by our k and then after we have our current number that number is going to be just a little bit smaller it's going to be divided by our k and then it's just going to keep cycling through up until n isn't less than isn't greater than zero anymore so it's literally just like these few lines of code uh that we need for this problem so once i run it let's see if i you know i didn't make any mistakes here okay great and i'm gonna submit this boom all right run time zero milliseconds faster than a hundred percent of those online submissions all right so that is how you do this problem guys and uh let's talk about the time and space complexity okay so our time complexity uh this is going to have to be an o of n where n represents the number of times we divide by k okay and our space complexity since we're not utilizing any extra storage our space complexity is just all of one here okay um so i mean yeah guys that's how you do the problem very easy i hope you guys learned uh you know something today you know kind of how why we represent uh you know decimals as decimals and how we convert a number from base 10 to a number of any base you know hopefully you guys utilize this trick uh in the future in one of your classes maybe or in an interview problem just like this uh but anyways if you guys found any value from this video go ahead leave this video a like subscribe to the channel and comment down below another problem you want to see me do and i'll make sure to do that for you guys but with that all out of the way i'll see you guys next time you
Sum of Digits in Base K
daily-leads-and-partners
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Output:** 9 **Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9. **Example 2:** **Input:** n = 10, k = 10 **Output:** 1 **Explanation:** n is already in base 10. 1 + 0 = 1. **Constraints:** * `1 <= n <= 100` * `2 <= k <= 10`
null
Database
Easy
null
303
welcome guys welcome to my lego solving section so this is called range sum query so basically somewhere to give you an integer array and you need to find a sum of the element between index i and j i know the basically is inclusive so summary zero two means that you sum this index from zero to two the number is one and the sound range two to five basically two to five uh let me see so minus two minus one yeah so zero to five is just total minus three and the problem is that uh this question will ask uh sort of the so key point that the array does not change so somebody will still be keep asking about some range okay so there are many ways the first the easiest way is that somebody ask you two uh to in this system you just compute therefore each time uh but there's easy ways that we can first sum over all the we can first create array basically some uh the first elements the zero is the first uh the az uh num suppose this already called a right so this point can be a zero and then it is a zero plus a one and a zero plus a one plus a two so basically we just accumulate all the indices uh we create a new array so i create a new array basically start from one and go to lens i just sum all the previous and then create data okay now if i is larger than one that means that your starting point is not your then your starting point is not zero right then you just use self j minus self i minus one so basically this is the same as this and then if your i zero then you just that means you just count from zero one two up to j minus up to j right so we just call it okay so then this will speed up your answer okay so it's very easy that you just first create already accumulated array that you minus the previous okay i will see you guys in the next videos and be sure to subscribe to my channel thanks
Range Sum Query - Immutable
range-sum-query-immutable
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\] \[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\] **Output** \[null, 1, -1, -3\] **Explanation** NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` * `0 <= left <= right < nums.length` * At most `104` calls will be made to `sumRange`.
null
Array,Design,Prefix Sum
Easy
304,307,325
110
complete code problem 110 balanced binary tree so this problem gives us the root of a binary tree and our job is to determine if its height balanced right so the high balance would mean that the binary tree is a binary in which deduct of the two sub trees of every note never differs by 101 so what this means is that for this case the tree is balanced right so let's look at what would look like if a tree is not balanced instead so this trade is not considered balanced because these two nodes right if you come from a root you'll be one two three right so the distance from the root to the leaf of the most left is three one two three and a little and a Distance on the Node from the root to the most right node is one right so three minus one is two which means this 3 is not balanced what should happen is that these two nodes should be moved to the right node instead right something like that but basically these three is not balanced and yeah so all we have to do is return false for this tree the distance from this node to this node is one two so two minus one is one and one is okay as long as it is not more than one okay so my solution to figuring out whether or not a binary tree is balanced is to use a depth first search method again right so we're gonna run through how my code works but basically type of search would mean to go in as uh to Traverse to into the binary tree as deep into the node as possible and then a recursion is to recurse and Traverse the binary tree to its depth first okay that's why it's called Netflix right explain more on how you also all right so I'll try it out so at first the first thing we do is uh we are gonna enter this function DFS using the root given to us so we are at we are now at this node so when we're at this node we check whether or not it's now in this case it's not zero we don't do anything and then we are checking on the left right to the left it goes to a recursion of left again right so a recursing into the left node which is over here okay remember that we check whether or not it's now again it is not so it recurs again to the left node right so here actually there's two more notes both of these notes are now so what happened is that once we enter into one of these notes uh this will return this will be null right our root is now which will mean that we have to return zero sorry so in this case our left is actually zero no uh to that one more left okay it recurs and then there's an easier after that you're right which is all here would also be zero okay after getting the left and right we are reflect whether or not the absolute value of both differences which in this case would be zero minus zero okay if not more than one so we don't need to do anything and then we return one plus the maximum of 0 and 0. if in this case would be one plus zero which is one so left right now is one after that we go back into the root node and then we Traverse into the right now all right okay once we're in the right node in fact whether or not it is now since it is not then we go back to the left node again right so here we're going to the left Loop once you're on the left note left and right notes are both now so left zero right zero then absolute this one you don't need to do anything because zero is more it's not more than one and then we return one plus two for our left is same thing with all right node over here right now over here so this will be one as well right because it is okay and then we check our absolute value right left minus right is zero is not more than one so we don't do anything here okay and then we return one plus one right maximum of left and right is one so two all right so now we are back at our root node we're about our root node over here and then we are going to check our absolute values so left minus right is one minus two absolute is one and one if not more than one right so we don't do anything here and then we return one plus the maximum of two and one which is basically two maybe three and then phase three is not equal to negative one we can just uh basically this will be returning true which means that this binary tree is balanced okay so as you can see on this note this block right here is to Traverse the Border Tree on the left side and then this block right here is a Traverse device on the right side and this block right here is to check whether or not the distance between two sub trees uh within the criteria of being heightened balanced binary okay and then this is to return the distance of that we calculated all right okay now I'm gonna try on a binary tree that is not balanced so let's start from the beginning again we start from this node so on left so there's no it's not now so we are recursing into our left all right so we refers to if not so again left and then we go to this node again left then we go to this node which again is left in this case this left is now so both of these will be left with zero right is equal to zero absolute value between the two zero is not more than one returning one plus zero which is one from class maximum of 0 which is what so left is one so remember this then we're gonna request to the right node okay so right now goes to think as the left note here so we know our right node is one as well calculate the absolute value and the differences the absolute value of the differences yes or minus one is zero it's more than one no so we don't do anything and we return one plus maximum of one which would mean we are returning to left now it is yeah with this and we're now with this so we're gonna go to the right mode now okay so on the right note since we know it's the same thing as over here so we know that the right is one right so right is one calculate the absolute difference two minus one this will be one is it more than one no so we return one plus maximum of two and one before we go so left is three back at our root note so we know the depth is three right one two three okay then we go to our right recording into this node and since we know that if you know from previous examples here this is one all right I'm not gonna do the entire thing again but this is one what happens now is when we calculate the absolute value of the differences three minus one is two and now two is more than one right which means the distance from our roots to the left node and the distance from our roots to the right node has a difference as more than one right which makes this three like not a balanced binary tree so what we have to do is we return negative one so when this returns negative one DFS root not equals negative one which means that this statement is false which means it's balanced will return false saying that this binary tree is not balanced okay that was a bit lengthy but I hope I explained well that's all I have to show thanks
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
455
Hello Everyone and Welcome Back to my Channel Algorithm Hk Today I am going to write the code and also explain to you all the algorithm to solve this assign cookies problem hk is there in lead code it is an easy level problem and can be solved using A Greedy Algorithm But Before Moving On To The Solution I Would Like To Request Everyone To Go And Hit The Like Button And Also Subscribe To My Channel If You Haven't Already And Tell Me My Proofpoints In The Comment Section Thatchi Jar Are And A Diya What's happening is s that is again an integer array now g is representing the great factor of a number of children okay and s is representing the size of some number of cookies so how many number of cookies a dot length represents the Number of cookies and G dot length represents the number of children. Now what we have to do is to provide cookies to these children but we can always provide a cookie of size equal to or greater than its grid factor to any child like If a child's Greed Factor is one, then we can provide him a cookie of one or larger size. We cannot provide a cookie of 0.5 or smaller size. cannot provide a cookie of 0.5 or smaller size. cannot provide a cookie of 0.5 or smaller size. Well, if a child's Greed Factor is two, then we can provide him You can provide a cookie of two or greater size, it is okay and to provide a cookie of that size, it should also be in this array, that is, it is okay, if it is in the array then only we will be able to provide it and otherwise we We will move on to the next children, okay, so by doing this, we have to tell how many cookies can we give to it from this size array or from this number of cookies, meaning how many children can get the cookies, okay and one to one child. You always have to give a minimum of one cookie. Okay, so like this one is an example, so what is done in this is that a child has a greed factor of one. Okay, so give him either this one size cookie or something like that. One is greater, give him a cookie of two size, it is okay and this is the second child, whose grind factor is two, either give him a cookie of three size, because the size of the cookie is more than his grid factor, either give him a cookie of two size. And what will happen in both the cases is that the answer will be two because both of them will get one cookie each which will be more in size than their Greet Factors. Okay, so the answer is two you have two children and three cookies. The Greet Factors of Two children are and two you have three cookies and their size is big enough to gratefully accept and two which were the grid factors, what cookie has been assigned to them, natu is fine then why am I assuming this because in future too I will write an algorithm in which we will provide a key whose grid factor is equal to or just immediately greater than the grid factor of any particular child. It is okay for that child, like if it is one, it is okay, then either we will give it one only or not. Either immediately greater means two will be given. It is okay if one is not present in this array then two would be given. But if both two and three are present in this array then it is okay and if the grid factor is to be given to the children of one then three is of no use. We always give immediate grater. Okay, so why are we doing this so that for the children who are left in the future, if their grind factor is more than this particular child, then there will be big size cookies left for them. Okay, we are not giving any smaller ones. Let us not waste a large cookie size by assigning it to the children of the Greet factor and we should have a solution in an optimized manner. Okay, that's why we are doing this, so basically what we will do is first of all we will sort these two arrays. Now why are we sorting so that the elements we have at zeroth index are the children in the zeroth index G array which have the lowest grid factor and in the S array are the elements at zeroth index or the cookie whose If the size is the smallest, then we can assign the smallest cookie to the smallest children. Children with the smallest grid factor, we can assign the smallest cookie. Okay, that's why we are doing this and if the grid factor of that child is the same as the cookie that we have, that particular If the index p is greater than the one we are at, then when we move forward in that array, that is, in S, then the next element that comes to us is immediately greater than our current size of the cookie, so we are sorting it, okay. Then after sorting, we will keep on assigning, okay and while assigning, what we will do is that first we will look at the grid factor, if the size of the cookie is equal to or greater than the grid factor, then we will assign the cookie and if not, what will we do? Will move forward in the cookie array and then check whether the size of the current cookie is equal or greater than the current greet factor. If equal or greater then we will reassign and if not then we will move forward again. And for how long will we keep doing this until either the grid factor array is completely destroyed or until the S array is completely destroyed by iterating it. Okay, so once we look at this example. Let's run try and understand what we are going to do. To iterate over G, we take a variable, to rate it on I and S, we take J and take an answer in which we will store how many children. Have assigned till now, okay, so now here i is zero and j is zero t means i mean now we are at the first zero index children and cookie p with zero index is so the grid factor of the children at zero index which is Is and what is at index zero is coming in less than equal to two. Okay, so what we will do is we will move both i and j forward because we have assigned this cookie to this child and because we have assigned this cookie, we have We will also move the answer forward by one, okay, we have assigned it to one of the children, okay, then when we move them forward, I will become one and J will also become one, what will happen again? The grid factor on the I index is laser. Then equal to size, which is current, zth index point, which is equal to two, is less, if the condition of day equal to too becomes true, then we will move it forward again and we will also move the answer forward, from one to two, it will be fine. Now our i from which we were doing it on G has become equal to the length of G to G. Okay, that means we have come out of this array so we will not be able to loop and continue and we will return the answer. Will give to that means both of the children get the cookies, so here also to has been returned by these people, okay, it was a very simple question but to build the concept of greedy algorithm, we have to ask such questions because if this Solve it immediately, some people are not very intuitive, some people do it, those who have practice, but to do this, mostly we need practice of greedy algorithm, so let's start, first of all we will sort both the arrays, okay then we will take the variables. int j = 0 and the answer is equal to we will take the variables. int j = 0 and the answer is equal to we will take the variables. int j = 0 and the answer is equal to 0 Okay, what are we going to iterate from j to s array Okay, then we will take it i is equal to it in g Now here what is it representing, not the index. An element that is accessing on g is representing a grid factor i. Well we could have taken anyway for i = 0 and i = 0 what would happen is that could have taken anyway for i = 0 and i = 0 what would happen is that could have taken anyway for i = 0 and i = 0 what would happen is that i represents the index through which we are accessing on g array. We are not doing this because our work can be done directly so with an easier syntax we will go Okay now while j is less than s the length is okay because from j we are adding it on top of s so always we have this Make sure that j is less than the length of a because if it is equal then index out of bounds exception will come. Okay, and as long as the size of our cookie is less than our particular grid factor, then what can we do? We will keep increasing the index of the cookie. Okay, if the index of the cookie is equal to A dot length, that means all the cookies have been exhausted, still we have not found such a cookie which we can give to this particular child, then what will we do? Then we will return that the answer we got till now is correct and otherwise what will we do then we will assign this cookie to that child, that means one index will move forward in the cookie and because it has been assigned that is the number of satisfied children. If this is the answer, then we will increment it by one and finally, when this loop ends, what will we do? Will we return the answer? Let's run it again and see that the sample test cases are being run. Let's see by submitting and submit successfully. Bhi ho gaya hai butt jaane se peeve please like the video and subscribe to my channel and tell me my improvement points in the comment section it's for the video Radhe
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
1,897
hey what's up guys so let's solve this uh legal story in section uh one eight nine seven redistributed characters to make all three equals so you're given a string a word and then basically you need you can swap any two indices basically you can swap any two uh indices and uh make another words right so for example you can make a to the right hand side so we can abc and you need to return true if you can make every string worse equals you need any number of operations okay so this problem is very simple right because uh you can see that in this case that you can move one a to b a b c right so simply speaking you can count there are three a's three b three c's and then if you uh then these guys this is possible right because once i know there are three a3 b3c i can just distribute it okay and for this one you cannot right because two a and one b so basically the idea is that you first count how many words you can create dictionary and you count each words and each characters and how many of them and for each uh for each values right for example this is three for each values you check that for these values divisible by the length of words right because if it's divisible by length or words then i can just distribute in it so although uh so i written force if you if there are some links you cannot like for example in this guy there's a 1b and uh there are two words right so one is different not divisible by two so there's no way if you bypass all tests there isn't true so basically you just count how many words and uh it's all how many characters and then you check that if all the frequency of the character is divisible by uh the number uh the lens of course okay that's it so i'll see you guys next video
Redistribute Characters to Make All Strings Equal
maximize-palindrome-length-from-subsequences
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_. **Example 1:** **Input:** words = \[ "abc ", "aabc ", "bc "\] **Output:** true **Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ". All the strings are now equal to "abc ", so return `true`. **Example 2:** **Input:** words = \[ "ab ", "a "\] **Output:** false **Explanation:** It is impossible to make all the strings equal using the operation. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of lowercase English letters.
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
String,Dynamic Programming
Hard
516
124
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 124 binary tree maximum path sum even though this question is marked as hard it's actually not that bad i would personally rate this question more of a medium the question the solution isn't really that complicated i think that it's very intuitive and makes a lot of sense i'm not sure why it's rated hard either way let's read the question prompt and work through an example so 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 nodes values in the path return given the root of a binary tree return the maximum path sum of any non-empty path non-empty path non-empty path so if we see this tree here with nodes minus 10 9 uh 20 15 and 7 then the maximum path sum is actually going to be this uh tree here where we go from the 15 to the 20 to the seven remember that we don't have to pass through the root of the tree so it's not an obligation to do that so we can see that you know 20 plus 15 plus 7 is going to equal to 42 right and let's verify that works uh you know if we went 7 20 minus 10 so that would be 27 so minus 10 so 17 plus 9 um that's going to be 27 so we know that path you know going here to here would be 27 which is not the maximum what if we went you know 15 to 20 so that would be 35 minus 10 so 25 plus 9 so that would be um you know 25 plus 9 so that's going to be 34. so obviously that's not greater than that um you know we could just have the path for example just 7 and 20. that would be 27 we could have this which is 35 we could have you know just this path which is 10 we could have this path which is one we could have this path so we can see that you know those are all the possible paths and the best one is actually going to be 15 to 20 and then 20 to 7 so basically this like little sub tree here so how do we actually want to solve this because we can see that you know we have negative numbers so we can't just assume that you know it's just going to be the sum of the entire tree right if it was all positive then you know the maximum path we would just easily be able to optimize that but because negatives are in play then sometimes we have to cut a path um by not taking it because you know if it flips negative then you know it could potentially not be the global maximum and one other thing that we have to notice here is that you know say we're at this 15 and seven and we choose you know we're at this 20 we have the choice of either connecting the paths so 20 to 15 then connected with seven but that means that we're not able to go um you know any higher in the tree right we can't go like you know minus 10 to 20 like this would have to be the root of that tree so at any point at any node we have to make a choice between its left and its right subtree if we want to go higher up in the tree or we can choose this you know node here to be kind of the root of the tree and then we were allowed to take both the left and the right subtrees so we do have to take that into account uh when we're doing our you know processing so now let's go into the code editor and write out the code and we're gonna see all the possible cases for this particular problem and how we're actually going to derive our most optimal solution because there are a few edge cases here that we do need to basically think about and i guess this is probably why the question is marked hard because there are some edge cases that may not be obvious um at first so i'll see you in the editor and we're going to write the code okay we're in the editor let's write the code the first thing that we want to notice is actually that our root can be given to us as an empty node which would be the case that you know we're not given a tree which means that we simply have to return 0 because obviously the maximum path sum of nothing is nothing so we return 0 in this case because our answer is gonna you know looking for an integer so we're going to say if not root we want to return 0. now we want to basically account for the fact that our tree may only have a root it may not actually have any left and right children it's just going to be a single i guess like stump node so what we want to do is we want to set that equal to our initial maximum path sum in the case that we don't have you know any other nodes in the tree other than the root um you know the maximum path sum should just be whatever the roots value is and that's what we want to return and we're going to keep track of you know the maximum path sum in a global variable and we're going to have you know a recursive dfs function that's actually going to perform the checks along all the possible you know routes in the tree so we're going to say self dot max path sum is going to be equal to whatever the roots value is and now what we want to do is we want to call our dfs function on the root to basically compute what the maximum path sum is inside of the tree and at the end what we want to do is return you know the maximum path sum that we've seen so what we need to do now is actually define the dfs function that's going to do the majority of the work so let's do that so we're going to say def dfs and we're going to take self and a node so obviously if we have an empty node here there's nothing we can do we have to just you know return zero there's we can't sum anything over a null node right because it doesn't have a dot vowel um you know property so we can't actually access it so if it's null we're just going to return zero so we're going to say if not node then we can simply return zero because remember we're going to be summing over the tree so we don't want to return null here because if we try to add you know null to an integer it's going to blow up and it's not going to work so that's the case when our node is um you know zero now what we wanna do is let's handle the case where we're at a leaf what happens when we're at a leaf right we know that leafs don't have children which means that you know we don't have to add anything uh to its child you know check that it's what the route from the children was uh we can just return whatever the node um value is so we're gonna say if not node.left and not node.right so node.left and not node.right so node.left and not node.right so basically this means that you know the node that we're at is a leaf we can simply say let's return whatever the value of our um node is and what we need to do is also check that our current node value is not actually greater than the maximum path sum that we've seen so far it could be the case that our leaf node you know has like a value of 1 billion whereas the rest of the tree is actually negative numbers so any path sum that we may have seen um so far you know would be negative and this node is actually the greatest uh in the tree so we do have to make a check whether or not this node's individual value is greater than the entirety of the maximum path sum that we've seen so we're going to say self.max self.max self.max path sum is going to be the maximum whatever the current maximum path sum is and the current node.val and the current node.val and the current node.val and then we're simply going to return node.vowel here node.vowel here node.vowel here now that we verified that okay we've checked for a null node and we've checked for a leaf node uh otherwise it must be a node that's not a leaf and that isn't null so we're going to go into its left and right subtrees so we're going to say you know the path sum from the left is going to be self.dfs self.dfs self.dfs node.left and we're going to say the node.left and we're going to say the node.left and we're going to say the path sum from the right is going to be self.dfs node.right so as you can see we self.dfs node.right so as you can see we self.dfs node.right so as you can see we are performing this in basically a um you know post order manner so we're going to go into the left sub trees before we go into the um into the right sub into the parent right we're going to go into the left right and then we process the parent so this is a post order traversal um now what we wanna do that we've processed the left path sum and the right path sum we have to make a decision of whether or not we want to continue up into the tree or we want to use the current node as basically kind of you know the root of whatever our tree is and use that to basically compute a path sum so there's a few options here that we can choose so you know our maximum path sum at this point is going to be the maximum of you know whatever the current max is we always want to check that and what are our options so if you remember here right if we're at this node 20 and we visited you know this subtree in this sub tree you know the left would return 15 the right would return seven remember that we have the choice of either taking you know the path between 15 20 and seven or we can take the path from 15 to 20 and then go higher up the tree in the hopes of finding a better path or we can take 7 20 and then go higher up the tree or we can say actually we can just take 20 if these were both negative we don't have to take these paths we can simply just take the 20 and then go higher up the tree so those are our options so the maximum at this point is going to be the maximum path that we've seen so far the current nodes value the current node plus the left path sum plus the right path sum then it's going to be the node dot vowel plus the left path sum so this is the case that we're ignoring oops this should be our path some so this is the case where we take you know both paths and we don't go higher up in the tree and you know no dot vowel here is if we're ignoring the left and the right and here we're taking the left but ignoring the right and the only thing left is to take the right and ignore the left so we're going to say no double plus our path sum and that's going to be the maximum path that we can form at this current point you know given our left path sum right path sum and the value of our node now we need to decide how we actually want to proceed up into the tree right we have to return something from this function because some other function is called you know dfs on us and it expects a left path sum or a right path sum depending on where we are in the tree so we need to return something to the next level and essentially what we're going to do here is what we want it very similar to what we did before and that we need to return whatever the maximum path we can take but remember if we go up the tree that means that you know we're not able to take you know 15 to 20 to 7 we have to make a choice between 15 or 7 we can take one or the other we can take none of them but we can only take one or we can just take the node value or if this value is actually you know small enough we can just return zero we can just not take anything so those are our four options right we can return sorry this should be the maximum of you know node.val of you know node.val of you know node.val we can do node.vowel we can do node.vowel we can do node.vowel and we can take the left path up sum oops we can do node.val plus we can do node.val plus we can do node.val plus the right path sum and then we can also just do zero in the case that you know if this node and this node were all extremely small numbers so basically negative really small negative numbers then it could be the case that we just want to ignore all of them we don't want to take it um because that could screw up our maximum path some you know globally if we were to take that so we want to take whatever the biggest thing we can in a greedy manner so that's gonna be the code for this problem let's submit it make sure that it works and it does cool so i think at this point it's good to walk through an example to see exactly how this is going to work so let's start and kind of draw out this code here so we're going to start and the first thing that we do is we check okay we're going to work with this tree here and we're going to say all right well we're given an empty tree no right we were given a root here so we know we do have some processing to do so the initial maximum path sum is going to get set to whatever root.val is to get set to whatever root.val is to get set to whatever root.val is so root.val as we can see is -10 so our so root.val as we can see is -10 so our so root.val as we can see is -10 so our max is going to be -10 is going to be -10 is going to be -10 and at this point we need to call the dfs function on our root and process it so we call the dfs on this node -10 and so we call the dfs on this node -10 and so we call the dfs on this node -10 and we can see okay does this node exist yes it does so that means that you know we have to go to the next level is this node a leaf node no it has a left and a right tree so that means that it's not a leaf so that means we need to call into its left sub tree and its right subtree so obviously the left gets processed first so what ends up happening is we go into the left sub tree and we see okay now we're in this dfs function again and we're at this nine so this nine happens and okay does it exist yes is it a leaf yes okay so now we need to update our maximum path sum with the maximum whatever the current max is and our node value which is nine so obviously nine is greater than negative ten so our new max becomes nine so at this point you know we try to go into its left sub tree but obviously it doesn't have one so we just return zero uh it's right actually no we don't even get to this point sorry we return node.val here point sorry we return node.val here point sorry we return node.val here because it's a leaf node so the 10 is going to receive a 9 from this side cool now we need to do the right side of 10 so let's call you know our dfs function on the right side of 10. so we're at this 20. so 20 exists and it's not a leaf so that means we go into its left subtree and we get to this 15. so 15 exists so we don't do anything here and 15 is actually a leaf node so we again fall into this statement here so now we need to double check okay is our maximum um is 15 greater than the maximum we've seen so far which it is because obviously 15 is greater than nine so we're going to update our max so it's now 15 and we're simply going to return node.val so from its left sub tree this node.val so from its left sub tree this node.val so from its left sub tree this 20 is going to return 15 is going to get a 15 right but we still need to do the right path some so we go into the right tree and we see okay this seven node here exists but it is a leaf node so let's do our check again is you know the value seven greater than our maximum 15 no it's not uh so we don't do any update here but we do return node.vout here but we do return node.vout here but we do return node.vout so now we're back at this node 20 and you know from the left we've received a 15 and from the right we've received a seven so now it's time to check our maximum path sum so remember that the maximum path sum is going to be you know the maximum of what we've seen so far it could be you know the maximum of just the node value or we could take the left and the right or we could do the node value plus the left or we could do the node value plus the right so obviously here the maximum path is 15 no dot val is 20 no dot val plus left path sum plus right path sum is going to be 20 plus 15 plus 7 which is our maximum so this is going to be you know 42 so we update our maximum path sum to now be 42 and what we need to do now is return the maximum of whatever our no dot vowel is or no dot vowel plus the left or no doubt vowel plus the right or zero in the case that you know everything was negative but in this case they're all positive so nothing happens there so what's the maximum here well we can see that the maximum is going to be 20 plus 15 so 35 so we're gonna return 35 here so now we're back at this 10 and remember from the right side we saw that the um you know we received nine from that dfs call and then from our right side we just saw that we returned 35. so now we do this check again so what is going to be the maximum so we're going to try to you know take the maximum of whatever the current max is our node.vowel which is minus 10 our node.vowel which is minus 10 our node.vowel which is minus 10 or minus 10 plus 9 plus 35 which is going to be 44 minus 10 so 34 or you know minus 10 plus 9 which is 1 or minus 10 plus 35 because that's the right side um which is you know 25 so we haven't found a better maximum so our max is still 42 so no update happens here and then what we do is we return the maximum no dot val so the maximum of minus 10 or minus 10 plus 9 which is 1 or minus 10 plus 35 which is 25 or zero so obviously 25 is the largest so we would return 25 here but since this is the root we return and now our dfs is actually finished so we don't have to worry about anything more so now we're here and all we have to do is simply return the maximum path sum which we saw was 42 so what is the time and space complexity of our algorithm here well time complexity wise we have to traverse the entirety of the tree and we're doing a post or a traversal here but i guess the traversal method doesn't really matter we have to test every single node in the tree and you know perform these computations all of these you know internal computations are going to be constant time calculations but the fact that we have to visit every single node in the tree means that our run oops our run time complexity is going to be big o of n space complexity wise we're not actually defining any variables other than our maximum path sum here although this is going to be a constant space allocation so the space complexity is going to be big o of 1 if we're not counting recursive stack space otherwise it's going to be big o of n so if we're counting the recursive stack space so this is always something you want to kind of bring up to your interview or be like well do we want to count the recursive stack space because you know technically it is a memory cost so you know that's going to be our time and space complexity for this algorithm like i said it's not the most complicated problem it is marked as a hard although i think that it's not too hard to wrap your head around the solution i think it's very similar to a lot of you know uh dfs type uh problems that you're gonna see on leak code the pattern is very similar right this is just a standard post order traversal i think the difficulty of this problem just comes in seeing a few of these edge cases here in terms of like setting the maximum path sum and also what to return to the next level because remember that you will have you know negative numbers which can skew your computation so sometimes you may not actually want to take um a node value and uh i think we already submitted it but just to double check yeah okay we did uh so yeah our solution works um like i said it's gonna be big o of n on the time and constant space uh in the space or big o of n on the space if we want to count the um stack frames anyway if you've enjoyed this video please leave a like comment and subscribe let me know if there's any other videos you'd like me to make any topics you want me to cover i'd be happy to do that for you guys just let me know in the comment section below and i'll get back to you otherwise happy elite coding
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
198
hey guys welcome back to another video and today we're going to be solving the leakout question house robber all right so in this question uh we're a professional robber planning to rob houses along a certain street each house has a certain amount of money stashed the only constraint stopping you from robbing all of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into at the same night and obviously you don't want to get caught so given a list of non-negative integers representing the non-negative integers representing the non-negative integers representing the amount of money each house has determining the maximum amount of money you can rob tonight without alerting the police all right so how can we actually go about this question so let's take a quick example so over here we have this over here we have one two three and one and what that means is that uh let's say the first house has one dollar the second house has two dollars third house has three dollars fourth house has one dollar which we can drop now the problem is if we rob this house over here that means that we won't be able to help rob the house next to it the adjacent house so we won't be able to rock this house similarly if we rob the house number three we won't be able to rob house number one and so on and so forth all right so in this case we'll see what they did so what they did is they first robbed house one and then they robbed this house over here getting us a total of four dollars and that also abides by all of the rules which is one and three are not adjacent to each other so we are not going to get caught by the police so this is a basic dynamic program and question and let's just see how this all plays into each other okay so over here let's start off with the base cases so let's say that we have zero houses okay so over here we're just going to have our nums array and in the beginning it's just going to be an empty list so in that case how much money can we rob and the answer to that is when we have zero houses you can rob zero dollars right there's nothing you can rob there's nothing to rob now let's say there is one house and that house has three dollars in it so whether you like it or not you are going to rob how much ever that is so in this case that's three dollars so when you have one house you're gonna just rob how much hour that amount is now let's say we have two houses one house containing one dollar and one with two dollars which one do you choose and you can only choose one because if you choose both of them the police is going to end up getting alerted so what are you going to choose well you're always going to choose the maximum between these two numbers so in this case the maximum is the number two so we're going to choose the maximum which is two so these three over here are kind of the base cases on top of which we're going to build up our logic so now let's say we have three houses so uh we have one house here and one house here so let's look at the possible combination so one of our possible combinations is that we can rob this house and this house without alerting the police or we can only rob this house so how are how do we know which house to rob and to find that out we're going to be using dynamic programming so let's just fill this up with some random values so let's put this as one three one obviously this option is going to give us the maximum value but let's see how we can get to that so what we're going to do is we're going to have an array over here which is just going to be completely empty so three empty spots and what we're going to do is we're going to start filling this area up and what each of these positions means is the maximum amount we can rob on let's say on this house so what is the maximum amount we can rob when we're at house one and the answer to that is when we're at house one the maximum we can rob is this over here so currently the maximum we can draw given only house one is one val one dollar right so now let's say we go to house two what is the maximum we can drop at our second attempt interesting house two at our second obtend what is the maximum amount we can run and the answer to that is the value three or the value one we can only choose either one so if we actually robbed this over here we wouldn't be able to rob this value here since we can't draw adjacent houses so in this case what we're going to do is we're going to choose the maximum between these two values right so similar to this case over here we're doing the same thing so in this case the maximum is the value three so we're going to end up choosing three okay so now we go on to our third attempt and now over here we can rob the house over here but if we do rob that house we're going to not be able to cash out on the value 3. so what we're going to do over here is the same step again we're going to choose the maximum between this value and what is the maximum well the maximum is three right but just for the sake of this question let's just change it up and let's say that this value over here had a value of four so what are we going to end up choosing well in this case we're actually going to end up choosing four so this would actually consist of four but remember that each step that we're going we're calculating what is the maximum amount we can rub and the answer to that is not four is how much we get by robbing this one health but what is our cumulative amount and to get that cumulative amount we're going to go to four we're gonna go back two houses so currently we're over here we wanna go back to houses so one and two and we're gonna add whatever this amount is to whatever we draw up over here so this over here is going to end up giving us four plus one with a value of five so this means that the maximum amount we can rob is the value five so all we're doing is we're cumulatively finding the maximum number we can rub and the reason we added the value 1 is because we want to consider the previous houses we wrote and the reason we did not add the value of 3 so when we had this case of 1 3 and 1 why didn't we add 1 in that case and the answer to that is because if we added one we would have adjacent houses so when we're choosing the previous house which in this case is the value three then in that case we're not going to be adding anything to it because we already have the maximum cumulative sum so hopefully that makes sense and what we're going to do now is we're going to go over two solutions so one is going to be uh the more step-by-step approach the more step-by-step approach the more step-by-step approach and the second solution is going to be using the same concepts but a lot faster all right so let's take a quick look at this all right so let's just go step by step so first we're going to check if we actually have any houses to rob so if not nums in that case that means we have an empty list and in that case we're just going to end up returning 0 since we can't rob anything now over here we're going to check if the length of nums is equal to 1 then in that case we're just going to return the value we have and if the length of nums is equal to 2 then we're going to take the maximum between uh the two values we have so instead of doing two different if statements we can just do that in one so if the length of nums is equal to or less than the value of two so in this case one or two since we already accounted for zero and in that case we're just going to return the maximum in our nums list so that accounts for that case and now if we get past of this if loop that means sorry now if we get past this if statement that means that we have a minimum of three houses to rob or at the very least and over here we're gonna define our dynamic programming area and this is where we're storing the cumulative sum of the maximum amount of money we can steal all right so what is this area gonna consist of so we're just gonna uh give it a value of zero or you could give it none i think both of them should work and it's gonna have a length of how much ever uh how many other houses we have so it's gonna be zero multiply the length of nums so we're just defining our area over here all right so after this we're gonna initialize a few things so we wanna initialize the zeroth element and the zeroth element is just going to stay the same so in the beginning uh we're always going to rob the first house since that is the maximum value so in this case they're just going to go to nums and whatever zero that element is same thing and similarly we're also going to define whatever the whatever is going to be at the first element and the value of the first element is going to be the maximum between numbers 0 and nums 1. so we're taking the maximum between the 0 at the index and the first index since we can only uh rob either one of those and now that we have those two defined we can build up on this using a for loop so what we can do is we can do for x in range so where are we gonna start from so we already accounted for 0 and 1. so we're going to start off from the value 2. so we're going to start at 2 and we're going to go all the way up to the length of num so that's just all the way until the ending all right so over here we're going to go to dpx right and this is going to be the maximum so what are the two options we have so the first option this pretty simple one is choosing the one right behind us right before us the house we just robbed so in that case that's just going to be dpx minus one and uh we're going to dp since we have a cumulative sum over there so that we either have that option or the other option we have is to rob this house and if we rob this house what is the amount of money we're going to get so the amount of money we get by robbing the current house is nums x and we want to add this to our cumulative sum so to do that we're going to go to dp and then we're going to go to x minus 2. since we're going two houses prior and that's it so at the very ending we're going to return whatever the value of the very last element is so dp negative 1 gives us the last element and if you submit this it should work now the only problem with this solution is the so it's accepted okay so the only problem is the fact that we're taking up a lot of extra storage um which is not really necessary so instead of using a dynamic programming area what we're going to do is we're just going to store these values inside of variables and at the ending we're just going to return uh the current value that we're holding so let's just look at that solution real quick all right so this is going to be our second solution and the only difference is that it's using the same steps it's just a lot faster and we're not using an area to store our values instead we're doing that with variables so we're going to start off by defining our previous element value and the current value both of which are going to start off at zero and then we're going to iterate through all of our numbers and temp uh so it's going to be a temporary va variable which is going to hold the value of the previous element and over here we're going to make the previous element the value of our current element and our current element is also going to change to the maximum between num plus temp or the previous value and this is the same as doing the steps that we did earlier like nums x plus uh dp x minus two right so it's the same step as that uh and that's all we're doing and this is just a lot easier and a lot faster and at the ending of this for loop we're just gonna end up returning our current value and if we submit this should also work alright so that should be it for the video and thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if the video helped you thank you
House Robber
house-robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 2:** **Input:** nums = \[2,7,9,3,1\] **Output:** 12 **Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 400`
null
Array,Dynamic Programming
Medium
152,213,256,276,337,600,656,740,2262
41
you guys mess you the party for this problem at equaled first missing positive given a nice order integer array find the force missing positive will be the third and why do 0 return 3 4 - 1 return to their wagon shell 3 4 - 1 return to their wagon shell 3 4 - 1 return to their wagon shell traitor should run in both end time and use is constant space so here - the thing we can the talhah r so here - the thing we can the talhah r so here - the thing we can the talhah r and eddie which could have made the problem much easier so how much it is just loop through the array by defining the loop and then this hello while loop inside this which is act well numb at I is greater than 0 because we go over 0 and neck at the bus and announce at all this rather than knowledge length actually should be small n equal to because main X can be so the index H will be one less than the value of the variable and this first William this define the bound this is the name crux of the or logic that noms i minus 1 what is noms i minus 1 basically num nums i minus 1 is the index of the number right is it and of salted kind as here they go from 1 2 and minus 1 with one number missing so we can do this that this is not equal to num z i it says swap our numbers numbs i minus 1 and i basically what this is doing is it's sending the ayat number two words current approach correctly location and to basically putting the element one at a time and you know basically the logic will try to swap one number twice so it's two-way so off and after it's two-way so off and after it's two-way so off and after system will have for loop and I equals 0 to I less than nouns length I trust us if knowledge I not equal to I plus one we're just I returned I touch one and if you reach the end of the Aryan Kevin found many none missing number then you can safely say that and then plus 1 will be less than this compiler statement 5 ok the top function is better so here we'll swap long and gums ai my papi the bucketful okay let's all measure and accept that thanks a lot thanks
First Missing Positive
first-missing-positive
Given an unsorted integer array `nums`, return the smallest missing positive integer. You must implement an algorithm that runs in `O(n)` time and uses constant extra space. **Example 1:** **Input:** nums = \[1,2,0\] **Output:** 3 **Explanation:** The numbers in the range \[1,2\] are all in the array. **Example 2:** **Input:** nums = \[3,4,-1,1\] **Output:** 2 **Explanation:** 1 is in the array but 2 is missing. **Example 3:** **Input:** nums = \[7,8,9,11,12\] **Output:** 1 **Explanation:** The smallest positive integer 1 is missing. **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
Array,Hash Table
Hard
268,287,448,770
1
how to do it's a very well-known how to do it's a very well-known how to do it's a very well-known problem they said that they will create five new problems but I guess it's not one of them submit speedrun give me the second problem where can I find the problem I don't know if you ask yourself this question a lot of times but for sure leet code users do there is a whole conversation below announcement of April 30 day challenge where people just ask anyone can find the problem or not how to join this church where can I find the problem and so on and the best thing about it is that forever each of those comments I got an email update with information somebody posted where can I find the problems people really cannot read block announcements challenge will start 1st of April this time in Pacific Standard Time everybody assumes it's their time I guess anyway let code announce that every day in April there will be a single problem to solve you have 24 hours if you solve all the problems or at least 25 of them in time then you get some random price or lead code points whatever my plan is to participate and when every 24 hour period ends I will post a video on YouTube with my explanation or at least recording of my coding and something about the problem if you are interested in that of course consider subscribing to the channel not to miss the future videos I believe the first problem has already started so let's try to find it together is there any link click here to be redirected to the challenge expert card seems promising single number I wonder what the statement can be given a sequence find a single number hard to guess every element appears twice except for one find that single one I think I know how to do it's a very well known problem they said that they will create five new problems but I guess it's not one of them submit speedrun give me the second problem believe me or not but I didn't look at this problem today though I saw it in the past the issue is with memory here that you can of course sort numbers or do some frequency arise something like that there or you can create a heart set if the number appears then insert it said but if number appears again so it's already in the hair said then instead to remove it there are a lot of solutions like that but the simplest one is involves XR maybe a hint for that first is what if the sequence would just contain zeros and ones then you could come to zeros and ones if it's array of boolean values then we can do it and what follows from this is that we can figure out parity of the answer in this sequence of numbers every number appears twice except for one special number that we need to find it are we able to find the parity of that special answer without any card sorting anything like that something simple where we can go from left to right and just count even and odd numbers every time we encounter even number we increase the count by one even count for odd numbers odd number odd count by one we would count that the number of even numbers is free the number of odd numbers is two and we do that without any hash that one insert in constant space and from this I will say that apparently those can be paired because this is even this is not even so this cannot be part so I will say answer for sure is even if you will get that the number of even numbers is hundred and the number of odd numbers is 95 then I will tell you that this those cannot be part so answer is odd this is how we can figure out a single bit of the answer the last bit the last least significant bit but actually we can do the same for every bit every int can be represented as 32 bits and the last one was we figure out it 0 if the number is even but the same way we can look at this one we can go through all the numbers may be again count how many of them have one here in the second last position second last bit how many of them have 0 this will become stand space and this wave will figure out what bit will be there because we will see 7120 zeros so one and so on and XOR is able to do all of that for us at once we don't need to do every bit separately because XR does all the bits at the same time now I see that I for some reason to some icons here and that's really it I hope you enjoyed this not really very interesting or brand-new problem but interesting or brand-new problem but interesting or brand-new problem but hopefully the next ones will be better see you tomorrow same time bye
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
1,689
hi guys welcome to tech geek so today we are back with another lead quote question that's the daily need for problem basically i try to discuss each and every link problem with you all and give the best of approach that's helpful as well as easy to understand even for the beginners uh before beginning i'd like to request you all please like share and subscribe and in case you have any queries regarding any subject interviews questions or any oa rounds or anything please let me know i'll be there to help you out with the preparation as well as the experience so the question for today was partitioning into minimum number of deci binary numbers okay that's a desi binary number it was a liquid medium question so basically it's uh waiting if you ask me how it should be around three by five okay so if you know how to do it go for it's quite easy let's see what the question is the question says we have a decimal number okay it's uh called desi binary if each of its digit is either zero or one so in short they okay first let me then i'll give you without any leading zeros for example one zero one and one zero are sc binary numbers while 1 2 and 3 0 1 are not so any deci binary number they'll just have 0 or 1 without having any leading numbers given a string n represents positive decimal integrals we are working on positive decimal integers first of all then return the minimum number of positive deci uh binary numbers needed so that they can sum up to n so let's say we have been given this number we have to find all the sort of positive messy binary numbers that sum up to this number okay like 10 plus 11 plus now why they are decimal because they are just made up of zeros and ones okay let's see uh okay i have taken this example we have one five four and three and now first of all the basic concept is you should know what is a deci binary number that's the basic thing right so if you know that sc binary number you will be like this was such an easy question right so let's take for one okay for one the decimal representation is just one for two we have two for three we have three then coming to four we have so i hope uh you guys can see one thing the number of ones is equals to the number that's uh the digit actually not the number so if you know this concept i guess it's easy to form any desi binary number right now coming to the fact these were singular numbers and we have to find the deci binary numbers that sum up to this number so we have a condition here now what we'll do let's take this example now what we'll do with 154 the very first thing is we'll find the deci binary number for each of the little so that is 1 5 and what is the tessie binary number here it is the maximum so maximum is 5 right so what we'll do is write 5 why i'm writing the largest number because for the others the leading should be zero sorry not leading uh the ending should be zero because in decimal uh leading is always one again for one so this is one so the rest of the digit should be zero keep that in mind that for this it should be zero okay again that's four one two three and four again the rest of the digits so here there was just one digit this should be zero now coming to the fact how to sum this up i don't think like this if you sum up this will give you any sort of number that's 154 no what we need to do is we need to group them in this way okay so first number should be 1 plus coming to the next one next column zero one again zero one plus again 0 1 plus 0 1 c okay now add this up and check 1 plus one two three four okay let's take the middle ones one five the first one that's one so this sums up to 154 how many numbers were there five now let's take another example and uh maybe one trick to you so that you won't be required to even find this up now we add an example of 32 let's see the same okay for three it's 1 for 2 it's just 1 0. again 11 plus 10 that was only given in the example that was the same gives up to 32 now see here it is three so number of sums required is three here it is five can you see the maximum digit is the result we are getting because we are taking that number of once and according to that number of months only we are giving the result i hope this is fine so what we need to do is we need to check the same so instead of finding these ones dc binary in short they are asking you to find the maximum digit is the maximum number of samsung point right let's see the solution that i have for you guys before that i'll request you to please find your at your own see what we are doing we are finding the maximum according to the length we are taking over digit finding the maximum that's uh subtracting the sky number and the resulting so whichever is maximum we'll consider that this particular approach is actually order of n where n is the length of the num because it is traversing it and once you know the maximum then obviously you can directly give the result now let's have a look at one of the solutions that was there one of the questions let me give some basic 3 7 9 6 8 or a very big number so what you have to do i have to check for the maximum here is 9 so the result should be okay i hope this solution is clear if there are any queries please let me know in the comment box anything that you couldn't understand any particular approach you have a different approach for the same problem please let me know for any particular test case that you feel won't work in this then please let me know thank you and please keep calling thank you
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
1,051
foreign students are asked to stand in a single file line in non-decreasing order by file line in non-decreasing order by file line in non-decreasing order by height so let this ordering be represented by an integer are expected where each element is expected height of ith student tree line so you are given an array Heights representing the current order of the students are standing in so each height element represents the height of height student in like zero indexed and written the number of indices where height of first array original array is not equal to the expected array so the given question is they have given the height array and all the students are standing in this formula so first student has a height of one second is one and then third as four to one three you have to make them to stand in a now in decreasing order by height that means it's in an increasing order so you have to copy the same array Heights to the another are they called expected create another called array called expected but in the expected array this element should be in the non-decreasing order so should be in the non-decreasing order so should be in the non-decreasing order so that you are making the students to stand in a ascending order one comma four two one three this is the height array and you have to make the standards line uh stand in you have to make the students line uh stand in a non decreasing mode that means one comma one two comma three comma four all these elements represent height of the I tell you once this is done now we have to return the number of increases where height of I is not equal to expected of 9. it means you can see first element in both the X are equal here also it's equal one and one here it is four and one so yeah this is one index 0 1 truth index it is then here also it's equal here it is not equal so this is 15 fourth index two three four then here I'll still not equal so this is 50 index so total number of indices is two four five two four and five that is nothing but three hence you have to get to the number of index indices where the did you tell that students are not in the increasing order in the original array the point at which so you could say four two four five do not match so you written three as the output similarly for this as well so here you can see online this is corresponding indices in each array do not work that's why you written five then if you go into this problem one two three four five and yeah it's already an ascending order so all of them matches so you need not to better anyway you can be zero so how do we solve this problem so at first if they are given height you have to make a copy of the file direct to the expected new Oracle expected so create a new Oracle expected and copy elements of height direct to the expected array copy of arrays Dot copy of height so while performing a list of copy of I can't be performed just like treatment of new array is equal to height well it existing if you do this is doing nothing but a referenced and expected that the expected array is pointing and reference to the height array so whatever changes you do uh yeah this height is referencing and uh what referencing the monitor to the expected array so if you do any changes in expected array it will reflect in the height so this is not what we want to copy the elements of the height array to the expected array so that is done using this condition so once this is done now you compare you just run the initialization account equal to zero and earn the volume so at each foreign count equal to 0 then let's initializer because then you are required expected there is nothing but arrays. opy of what Heights installation so once this is done along with Heights you have to mention the height length as well so comma you need to cut hides Dot so we are copying all the elements of height to the expected foreign if Heights of file is not equal to expected of I you then not equal then increment the value of count yes please finally okay after copying the element of the height to the expected area only then you get this sorted of the heights uh so other stuff sort of expected and successfully submitted if you have any doubts please stop put in the comment section will comment with another video in the next session until the description of the channel thank you
Height Checker
shortest-way-to-form-string
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `ith` student in line. You are given an integer array `heights` representing the **current order** that the students are standing in. Each `heights[i]` is the height of the `ith` student in line (**0-indexed**). Return _the **number of indices** where_ `heights[i] != expected[i]`. **Example 1:** **Input:** heights = \[1,1,4,2,1,3\] **Output:** 3 **Explanation:** heights: \[1,1,4,2,1,3\] expected: \[1,1,1,2,3,4\] Indices 2, 4, and 5 do not match. **Example 2:** **Input:** heights = \[5,1,2,3,4\] **Output:** 5 **Explanation:** heights: \[5,1,2,3,4\] expected: \[1,2,3,4,5\] All indices do not match. **Example 3:** **Input:** heights = \[1,2,3,4,5\] **Output:** 0 **Explanation:** heights: \[1,2,3,4,5\] expected: \[1,2,3,4,5\] All indices match. **Constraints:** * `1 <= heights.length <= 100` * `1 <= heights[i] <= 100`
Which conditions have to been met in order to be impossible to form the target string? If there exists a character in the target string which doesn't exist in the source string then it will be impossible to form the target string. Assuming we are in the case which is possible to form the target string, how can we assure the minimum number of used subsequences of source? For each used subsequence try to match the leftmost character of the current subsequence with the leftmost character of the target string, if they match then erase both character otherwise erase just the subsequence character whenever the current subsequence gets empty, reset it to a new copy of subsequence and increment the count, do this until the target sequence gets empty. Finally return the count.
String,Dynamic Programming,Greedy
Medium
392,808
897
hey everybody this is larry this is day three of the december league day challenge hit the like button hit the subscribe button join me in discord let me know what you think about tracepalm uh if you're new to the channel um usually i explain my thought process from beginning to end uh and i record everything live so i might get to the actual solution a little bit slow feel free to watch this on faster speed or just skip ahead uh and let me know what you think um because it's different from how usually other people do it today's problem is increasing order search tree okay so basically okay you want to convert it to your century a linked list from a search tree um okay um i think the question is whether hmm and then uh so i mean i think conceptually in terms of understanding uh it should be okay n is only 100 anyway um so for these problems the tricky part is just trying to figure out the invariance of a problem uh and an invariant is something that doesn't change as things change right um other things change obviously and i know that sounds great but what those things are depending on the problem uh and to be honest uh if i was doing a contest or something like that i might be tempted to you know just create this um create a second copy and then just like you know do it regular in order and then just um do it that way and you could do that in like five lines of code i don't know if that would have to do it in place it doesn't mention anything about the space complexity and also given that it's a hundred node inferior i probably wouldn't care um yeah but for now i am going to try to up solve it uh by trying to use uh everything in price in constant space um or constant extra space minus in place which a lot of times i um i will complain about doing things in place because it's just so artificial but for something like this maybe it's okay um yeah so basically the idea here is that giving a binary search tree you want to give another a linked list essentially but a tree in order so then the awareness that we want to get the smallest value and to get the smallest value in a binary search tree um it's just you do an in-order um it's just you do an in-order um it's just you do an in-order traversal right so that's kind of let's start doing that and then we'll try to figure out how we do the actual connections because i think this is um and this is what experience gets me is that it just comes down to case analysis and you have to be really careful i don't think conceptually there's anything hard once you are familiar with in-order traversals are familiar with in-order traversals are familiar with in-order traversals and just linked lists and trees in general uh in terms of algorithm uh in terms of because you know you could draw pretty pictures and just like change the pointers right but of course the implementation is going to be the tricky part for this problem so uh so yeah let's kind of walk through it together um okay so let's say we have you know if node is none we just return because that needs to know what is done maybe we may have to return something uh but for now we'll return nothing so then we just do in order of node.left of node.left of node.left uh do something with process node uh in order of know that right okay so what do we want to do though so that is the environment that we try to get so we want to get so what does this what should this function return um and i think something that i get stuck on sometimes is that um i try to make this only return one thing when it could maybe return multiple things but yeah so basically we want this to return we want so we want in order to return the biggest element because basically okay so maybe i would have to rewrite this a little bit but basically we want from the left side we want this to return to the biggest element from your left side you connect that to your current node and then you want to get the smallest element from your right side and then connect that right so that means that we want to return two things one is the uh smallest element and one is the biggest element so we can do that um we might not use both of them but we can write our code in such that way um now and right now i'm just thinking about whether i want to split into two different functions um but the problem with two different functions is that if you're not careful this would become n squared instead of n um but i know that in this case it doesn't really matter because n is 100 but in terms of up solving that's what i'm thinking about so okay let's actually change this or be clear with this definition of disorder okay this function we or this method maybe returns um the leftmost which is of course the smallest element uh and the rightmost the largest element oops let me just put this on a different line uh in the subtree okay so then now here we if none is with node is none then we can just return none uh here then we can return what we want is left um so we from the left we want what we do is say we want the biggest right so left biggest naming is tough for me still so you know i hope you okay and we could ignore the smallers i think um we might not and if that's not the case then you know we'll change it right smallest uh is in order to know the right and then now uh actually not we do need the left smallest just because we need to return that later i mean we actually might not use it i think to be honest but no we might actually so we'll see uh but and let's just tinker the largest instead of breakers because i think that's more grammatically correct so then process no what is there to process right well now we want the left largest uh to point uh right they want the right yeah only right child right to this note so left largest dot right is equal to node and then node that right is equal to right largest right uh and this will of course have to be afterwards otherwise um uh we don't get the answer from this but we might have to think of i might have to think about whether that messes up the answer to be honest so we'll see um okay um and then now we return the left smallest which is the smallest of the sub node and then the right largest from here uh also i messed up i think so hang on this should be right smallest of course um i think this should be close i'm not confident about it to be honest but this is why i want to um when they want some test cases to help me of the visualization sometimes i draw it out um but you know this may help me uh yeah this will help me kind of just visualize it in general uh and of course in this case actually i just forgot some stuff which is um keeping in mind that all of these could be none so hmm which one of these can be none okay well if this these have to both be at least one element or they're none so we could just check if light left largest dot right is none or is not none but now i think we have some possible um possible how do you say this um possible um hanging things so we'll kind of see uh and this doesn't have to be right and what i mean by that is that um it might we may not comprehend the list but this is where uh to be honest this is really tricky to be careful you may draw a visualization uh the way that i try to show it here is by running the code so that we could visualize it together uh clearly the enter is wrong but oh and i don't change anything that's why um got this uh we don't change anything because we don't ever return anything useful um because if this is none then we don't return it right so um if let left smallest oops if left smallest just none then we set this to a node if right largest is none then we said right largest equal to node um so we should definitely be closer to the truth but and how am i able to visualize is just because of years of experience and a lot of practice in debugging how i think right so you may take a while debugging and i would recommend you know doing print statements or just writing a debugger on your local machine uh okay so yeah we found a psycho that's not great obviously um so that's not good visualization but oh um the reason is because we don't get rid of nodes oh sorry we don't get rid of the links so basically oh yeah uh well actually we could just probably do something like the left is we go to none uh no doubt left is equal to nine we definitely don't do that let's see if that gets us closer uh there's a lot of trial and error because like i said it's gonna be a lot of case uh um case analysis so it's gonna be a little bit sketch um we do get rid of too much we kept it up to the left uh so what's 517 uh oh yeah so there's a visualization here we get rid of the left for some reason so that's not great oh no this is i think this is actually okay um but i am not handling this correctly which is that um instead of returning the root we actually want to start from the smallest element right so the smallest so yeah so i am forgetting a lot of things so i apologize uh this but you do get to see me live and you get to see my process as i debug them so hopefully that helps um yeah uh this still actually looks good but i'm not confident still because well look i was wrong for like five of those test cases so we kind of built this one by one um and even though i am a little bit confident but i'm still not 100 confident um this has to be a binary search tree so wait was this a by name or tree yeah uh oh right um and then maybe just uh do to do because yeah the reason why this is one is because we want to uh start doing this at the smallest and not at the root uh it's just that it's um it's a force of habit that um yeah it's a force of habit that you know i usually in a lot of other problems you just want to return the route so uh cool uh so we did find a wrong answer why is this what is the tree correct uh yeah the tree is correct so it is good that's why we test some more um smaller should be one so here i am just walking through the code this the right is none so the right is going to be the right largest is going to be the node um this is going to be none so oh i don't set the node to left is equal to none if we um yeah because that is a tricky nuance and now i'm trying to think about it um because we have to process the current notes left and when we do an order we should process everyone's left so it should be okay but this is why we test and that's why now i'm a little bit uh i want to check more cases let's just say five uh four three okay so that looks okay i'm gonna give a submit usually i would um if i'm on an interview or something like that i might do more testing because i'm still not 100 confident but uh but just into interest of time i'm just gonna give and then see if i get any test cases okay accepted cool um so what is the complexity of this right so it's gonna be of n because for each node we only call this function at most once and so for every node we call it once so it's going to be o of n because this only takes over one time assuming that you know each of these is going to be all one um yeah and that's pretty much it i think it's just a lot of book keeping and when i say bookkeeping i mean just keeping track of where every note is and if it helps i would recommend you know taking a piece of paper and just draw it out and make sure you get all the cases right uh here i if you watch me i actually visualize by uh looking for the code and seeing what my code does uh to be honest we're not super always recommended it takes sometimes it does go wrong spectacularly and takes a long time but and you know it takes a lot of uh experience to both know the code which obviously you know is you know like you just know the code and see what it does but two is also just know how you write code right like sometimes some like some people just mix the same mistakes all the time uh like me i make certain type of mistake all the time so i definitely like know what to look for right so that's why i'm able to debug faster and that's why i always advocate that when you um have issues with the right answer try debugging it yourself and see where your logic was wrong right for example for me like i had a loop logic here and i'm like huh you know this is a and you know i try to distill the test cases to be as small as possible so that when i reproduce i'm like oh this is wrong but why is this one for just one note oh because we never said left if this is because this has no relevance to this is uh this way so these are some examples that i would do but yeah that's all i have for this problem let me know what you think it's a i mean i think infuriated algorithm is not hard but it is a lot of implementation possible mistakes and you can tell by just the number of if statements i have and there's a lot of like asymmetry that's a little bit weird um but yeah okay cool that's all i have with this problem let me know what you think uh and i will see y'all tomorrow bye
Increasing Order Search Tree
prime-palindrome
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9\] **Example 2:** **Input:** root = \[5,1,7\] **Output:** \[1,null,5,null,7\] **Constraints:** * The number of nodes in the given tree will be in the range `[1, 100]`. * `0 <= Node.val <= 1000`
null
Math
Medium
2202
12
in this video we'll be going over Elite code problem 12. integer to Roman here's the problem description Roman numerals are represented by seven different symbols i b x l c d and M here's a table with the respective symbols and their values for example 2 is written as I in Roman numeral just two ones added together 12 is written as x i which is simply x 10 plus II the number 27 is written as x v i which is X x 20 plus V 5 plus I 2. Roman numerals are usually written largest to smallest from left to right however the numeral for four is not i instead the number four is written as IV because the one is before the 5 we subtract it making four same principle applies to the number nine which is written as I X they told us that there are six instances where subtraction is used I can be placed before V 5 and x 10 to make 4 and 9. X can be placed before l 50 and C 100 to make 40 and 90. and C can be placed before D 500 and M 1000 to make 400 and 900. so here are some examples so the number three we want to write the number three in numeral Roman numerals our output should be the string I if our initial number is 58 our output string should be l v i where L is equal to 50 V is equal to 5 and I equals 3. and then finally if our number is 1994 our final output should be m c m XCIV where m is a thousand cm is 900 XC is 90 and IV is equal to 4. so let's take a look at these examples in a little bit more detail here we have the number 58. and I've listed here the entire table of all of the different symbols and their values so the question here is how do we break down 58 into a Roman numeral string now here it might be easy to see okay we have a 50 so we have this 50 over here and we can grab this 50. and that would give us I'll write the string up here l and then we can see okay now we have to make this eight so maybe we'll grab this five and we'll add that so that's a v so we grab that and then we'll grab some ones three eyes now it's pretty easy to see this for this one number but we want to think of a systematic approach for how to deal with any number so let's just erase this for a second and take a look at how we might do that so one option you might think of is maybe we can just start with the smallest number over here and start to build it up and then we'll move on to this 50 over here so in this case we're going to start by trying to build up an eat and we might go here and say okay let's look at what values we have and we said okay we see that we have I equaling one a value of one eight can be made up of eight ones so you might think okay let's just add eight eyes over here and that takes care of this eight great so then all we have to do is get this 50 so we would look down here maybe we'll take this l and get something like that unfortunately this is incorrect and the reason this is incorrect is we always want to try and use the largest possible value or the symbol for the largest possible value to decompose a number so that we can make the number as condensed as possible and so here's the way to look at this let me erase all of this trying to build a number like 58 what we want to do is we want to actually start at the bottom of our symbol table and find which value can we put into 58 that fits and that is the largest possible value so if we do that we can start with this a thousand we see that a thousand doesn't fit into 58 so we'll skip it then we'll go to 900 doesn't fit into 58. we'll skip it we'll skip 500 400 100. 90 and then we get to 50. and all of a sudden we see 50 does indeed fit into 58. so what we'll do here is we'll say okay we've used our 50 here we can see is corresponding to L so let's add our l and then we keep going so now we can keep going say okay we've used this 50 the spell why don't we see this 40 fit now here is where it kind of becomes a little bit more interesting this 40 technically does fit into 58 because 40 is less than 58. the thing is we already said we were going to use this 50 over here to build up our 58. so what we need to make sure to do is as we build up this number we need to subtract anything we've already used so in this case we want to subtract the 50 and now we just try to build up the remaining so now all we have left to build up is eat so now our new number in a way we can think of it our new number is no longer are we looking at this 58 we're now just looking at the speed over here so let's keep going now that we know we're looking at eight we look at eight let's no it doesn't so we'll skip it does nine fit no it doesn't so we'll skip it the question is does five foot five is indeed less than eight so five does fit so we're gonna use that so we're gonna add our V up here and then again we need to subtract five to indicate that we've used this five so if we subtract five we will get a total here of three so now we have three left and then we keep going so let's keep going does four fit into three no it doesn't and then all we have left is does one fit into three yes it does we're actually going to need three ones and so then we can add our three ones over here and now we know that we can actually use some blue subtract a three and now we kind of have finished our number so there's nothing left so this is going to be our final answer here so let's take a look at another example we're going to follow the same process and see how it works so in this example we're looking at the number 1994. so again we're going to follow the same approach let's start down here start with a thousand does a thousand fit in 1994 yes it does a thousand is less than one thousand nine hundred and ninety four so again what we need to do say okay we're going to use this a thousand so what we need to do is we need to make sure we subtract out that thousand that we used so let's do this got see that in blue and our new number now becomes 994. and because we use this a thousand we want to just note that we use this m so let's put this m up here and then we keep going so let's keep going now we check does 900 fit inside of 994 because remember this is our new number we're looking at and yes 900 does fit so we're going to use this 900 so I'll write it down here 900 and then what we're going to want to do again subtract so that's going to give us 94. so now we can indicate that we've used the CN so we'll write CM up here and then let's keep going so now we have 94 as the value we need to build up so let's see does 594 no it doesn't this 400 no it doesn't does 100 no it doesn't how about 90 Yes mine does fit inside of 94. so what we'll do here is we're going to again just subtract 90. to indicate that we used this 90 over here and so now that we've subtracted 90 C running out of space a little bit now that we've subtracted this 90 over here we want to indicate that we use this XC so let's add this back and this is going to give us a value of 4. so now our new value we're looking at is this 4 over here and then we just repeat the same process does 50 fit inside of four no it doesn't 40 fit inside of four no it doesn't neither does 10 neither does nine neither does five but four does indeed fit inside a four and so our final answer here is we're going to use this I feed and our final answer will be this so that's the process of actually moving through so again just to reiterate what we want to do is we want to start with our original number so in this case 1994 and then we want to move from the bottom of our table all the way to the top and find the biggest numbers that can fit so let's take a look at how we might code this up so I'll be coding this in a C plus and let's start by actually building up some sort of table to allow us to do this access and to actually check the different values in their samples now one clever way of doing this is we can actually use two vectors in order to store the entire table and so what I'll do here is I'll start by actually storing a let's change that the vector of ins I'm going to call it values and what I could do here is I could indeed just store the values kind of starting at the bottom so I could do one then five then ten then 50. I could do that but there are two things you want to remember one it's going to make our life a lot easier if we also store these additional values that have special symbols inside of our table so that's going to be the first thing the second thing that's going to make our life a little bit easier is if we actually store the values in reverse order given we need to iterate from quote unquote the bottom of the table to the top it might make sense to store the largest values first I would look as follows so instead of starting with one and then going to 5 10 and 50 let's start with a thousand and then let's move to our next value in this case is actually going to be 900. and then we'll go to 500 from our original table then 400. then 100 then 90. and 50 40 10. 5 oh this one nine five four and lastly one so now we have all of our values here and then the next thing we want to do is we actually want to create another Vector this time it's going to store strings which are going to be the symbols so the corresponding symbols here so that'll be n and then we'll have let's see what's next cm and then empty CD see and then 90 is X C keep forgetting to put these in quotes XC then we have let's see done actually so l then so then that gives us the XL then we need to do X so you'll just take Extra Spaces and we have X and that will be 10 so now we need just nine so that's going to be IX then V then IV and finally just I so now we essentially have recreated our table using two vectors so all of our values are now here let's add this in quotes and all that's left for us to do is to implement this so what we want to do is we want to follow the same approach so remember what we said we would do is we're going to actually go through our values and try to find the first one that fits inside of num so I will just iterate through I less than and this is going to be the values dot size and then I plus so iterate through this entire vector and then what we want to do is we want to check if the value here which is going to be values at I think it's less than num which is our original value that we're trying to convert then we actually have found something we need to append our string so what we can do is let's actually declare our output string so I'm just going to call it output and we can have it as an empty string to start out so if values is less than num we're going to want to pent our output string so we know that the value is going to fit inside of num but the next question is how many times does say a thousand fit inside of 3 000. so we're going to want to do is I'm going to call this repeats so we're going to calculate repeats by dividing num by whatever values that I is values at I so it's going to tell us the number of times we need to repeat the simple so now that we've done that what we can do is we can actually call this one J repeat the symbol the given number of times so J is less than repeats and then J plus and now all we need to do is we need to append to our output string each time we just want to append whatever symbols at I is so symbols at I so what this is saying is let's say our number is right now three thousand we see that a thousand fits into three thousand so then we wanna and we see that it fits in three times so that's this it repeats and so we want to append three M's to our output string once we've done that so once we've kind of repeated um or appended our repeated symbol what we want to do is again we want to indicate that we've actually used a value and so we want to subtract from num so what we want to do is we want to do something like this num equals or non-minus equals and here what we're non-minus equals and here what we're non-minus equals and here what we're going to do is just repeat time values at I and we'll keep doing this and this process should return what we're looking for let's see if we've missed anything so here's our output string we're going through each one if values at I is less than and we probably want to say less than or equal to none then we want to figure out how many times it repeats and then append the symbol that many number of times and then just subtract however many kind of value how much value we just added to our string and then eventually we'll just return output so let's submit this and see how it does awesome well thanks everyone for watching and feel free to comment if you have any questions
Integer to Roman
integer-to-roman
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. Given an integer, convert it to a roman numeral. **Example 1:** **Input:** num = 3 **Output:** "III " **Explanation:** 3 is represented as 3 ones. **Example 2:** **Input:** num = 58 **Output:** "LVIII " **Explanation:** L = 50, V = 5, III = 3. **Example 3:** **Input:** num = 1994 **Output:** "MCMXCIV " **Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. **Constraints:** * `1 <= num <= 3999`
null
Hash Table,Math,String
Medium
13,273
338
hello guys welcome to another video in the series of coding today um let's do the problem it's called counting bits you are given an integer n you have to return an array answer of length n plus 1 such that for each i answer of i is the number of ones in the binary representation of i okay so what do you have to do in the question so let's say n is equal to 15 in the question what they are asking is you have to create a vector right you have to create a vector which is from 0 to 15 and in each of the numbers you have to tell how many ones are there in the binary representation for example in zero there are zero ones right so you have to write zero in one there is one right so you have to write one in two there is one so again you have to write one in three there are two ones so you have to write two in four there is one again okay so left right one in five there are two ones in the binary representation of six there are again two ones in the binary representation of seven there are three ones in the binary representation of eight there is one for nine it is two for ten also it's two for eleven it is three for twelve it is two for thirteen it is three for 14 it is 3 and for 15 it is 4 and so on right so you have to build this vector and once you build this vector you have to return this as the answer okay so let's see how we can solve it in the brute force approach so what is the brute force approach just write all the numbers from 0 to n okay for example n is equal to 15 write all the numbers from 0 to 15 and for each such number for each number find out what is how many ones are there in the binary representation how are we going to find the number of ones for example let's take an example in seven let's say you have the number seven how are you going to find how many ones are there in the binary representation of seven it's very simple right it's very simple to find the number of ones what you're going to do just take the last digit is it a one it's a one then increment it and count okay so the last date is a one right so till now i have found one okay after you find the last date what are you going to do just remove the last digit okay then your last digit gets shifted your last date gets shifted now see this digit is it a one yes it's a one so again increment your count okay and then what you're going to do you're going to remove this okay again then what you're going to do similarly check this date is it a one or it's a zero it's a one again it's a one right so your count is going to become equal to three then what you are going to do you are going to remove this last date also till the number becomes zero you will keep on doing this so finally the count is three so in the binary representation of seven you have three months okay now let's uh quote the brute force solution and let's see what is the problem in the brute force solution okay so let's start the brute force solution is very simple so we'll start from zero to n and okay so what is the number that we have is i right we have i so for example okay for example let's take us let's take a bigger example just to be clear okay let's say you have such number like this you have to find how many ones are there in this binary representation right so how will you find till the number is non-zero right find till the number is non-zero right find till the number is non-zero right till the number is non-zero because a till the number is non-zero because a till the number is non-zero because a zero number does not have any ones okay so till the number is non-zero what you so till the number is non-zero what you so till the number is non-zero what you will do first of all you will check if the last date is a one or not so how will you check that just do number two if num or two if it's if the last date is one what is number two will be one if the last date is zero if the last date will be 0 number 2 will be 0 okay that's how you can check so if num mod 2 is equal to 1 that means that last date you have a 1 right so you can simply give a count variable let's see int count is equal to 0 and you can increment the count by just doing number two okay after this what you will do so you have let's say last date is up one right so till now my count is equal to one next time what do you want to move remove this one you have already taken its count is equal to one so now we will remove this so how can we remove this just do num is equal to num by 2 okay that's it if you divide by 2 if you so this was the original number that we have if we divided by 2 what we are doing we are just shifting it so we are removing the last digit and this will become your number now again we'll come here what is the count now we will again check if this digit is a one or not here in our case this date is also a one so count will increment by one okay then next we'll again divide the number by two next this is our number now the last date is zero so count will not increment so count will increment by zero okay count will remain same again we divide the number by two again we check if this digit is a one this did it is a one so our count will increment by one okay and then we divide the number by two now this digit is zero so our count will increment by zero again we divide the number by two again now this digit is one that means what that means that we can increment by one and now if we divide this number by two number becomes equal to zero so while the number does not become equal to zero we can keep doing this operation when it becomes equal to zero it will exit the loop okay and now what you can do so you have made we have let's make answer vector let's make an answer vector in answer n plus one and 3 okay now answer of i will become equal to whatever count is there and you can return answer okay so this should work but what is the problem with this brute force approach is its time complexity so this will work we'll submit and see it should work but its time complexity is large we will discuss what is the time complexity of this so see we are running this for loop right so this will run n times but inside the for loop we are also doing this work okay now how much how many times are we doing this work we are dividing it by two right so in the worst case okay so what's happening since we are dividing it by two this log base two right we are doing log base two work and uh what is the maximum size so n so if you have a number uh the last number will be n right so you can this work will happen it will take log of n work right and you are running this loop n times so if you write the time complexity it will be n log n okay the time complexity will be n log n because this inner loop will take log n okay in the worst case and this will run n times so this is the problem so we want to do it in just o of n we don't want to do this while loop this is a while loop which is giving you extra time complexity so we will remove this and let's see if we can just do it in o of n okay we'll just do it in a single for loop and in single pass and in just of n okay now let's see how we can do it in just o of n okay so now see you have to find the number of ones right now observe something so to find the number of ones see let's say let me remove all this okay let's say you want to find the number of ones in a number six okay in a number six so let's say okay let's say i start building the solution let me write the solution already up till 5 okay let me write the solution up till 5. so up till 5 let's say i already have my solution right i have built it now i want to find the answer for n equal to 6 how many ones are there in this i want to find now observe something what is this is 0 1 0 right this is 6 is 0 1 0 okay in 3 also ok so this is 3 so 3 is just left shifted okay three just left shifted so this is the binary representation for three and this is the binary representation for six so this is a binary representation for three this is a binary representation for sixth see both of them are just same the binary representation both of them is same it is just that three is okay if you shift if you left shift three you will get six okay because three into two by left shift what we do see if you have any number okay let's let me take one more example if you have any number right and you want to find the binary representation of 2 times that number what you do you just shift this number right what you do you just shift this number and you will be able to get the binary representation of ah 2 times n okay so that is what the binary position of 3 and 6 are very similar okay except that this piece has got shifted and come here okay so this is very important to understand this piece was in the last this piece has got shifted and it has come here okay that is what is happening in the binary representation okay so binary representation of three and six is very similar why am i telling this because number of ones already we have calculated in three now i want to calculate number of ones and six so it's very similar see three also has two ones six also has two ones number of ones are same because the binary representations are just the same but it is just left shifted but by left shifting you're not changing the number of ones are going to remain the same right so 3 and 6 have the same number of ones okay let's see this for other cases let's see this for other case okay very simple see what is the number of um let's say i want to find the number of ones in two okay now let's let me look at the number of ones in one also has one and see this is just getting left shifted so observe the binary representation of one and two carefully if one just gets left shifted you are getting two so the number of ones in both of them are remaining same one has one and two also has only one okay now let's look at the next case let's say i want to find the binary representation of four so i will just look at the number of ones and two both of them will have the same number of ones because what is happening observe two and four very carefully only one left shift is happening nothing else is happening number of ones is remaining same right so number of ones in four and two is also same so let me fill it here okay similarly let's say i want to find the number of ones in six okay i will just look at the number of ones and three okay number of now three has two ones so six will also have two ones okay so it's very simple see three has two ones so six will also have two ones okay because what is happening only this portion is getting left shifted nothing else is changing okay so that's it now okay so six also has two ones now similarly let me try to find the binary representation number of ones in eight now let me just look at number of ones and four as one so eight also has one okay now let me try to observe this for all other examples okay let me try to observe if i can make a pattern for all other examples okay let me take any random number now so let's say i want to find the number of ones and twelve what will do i look at the number of ones and six because see what is 6 is just this if i just left shifted this will become 12 right this is 6 this is 12 but number of ones are going to remain same so both of them have two ones okay let me take another example let's say i have 14 what is the number of ones in fourteen this is fourteen number of ones in fourteen is three now let me look at seven what is seven this is seven because this portion has just got left shifted okay so this is seven and this is fourteen okay so number of ones are same both of them have number of ones three okay so the logic is very simple okay logic is very simple number of ones how can i calculate if i have a number i just i already have calculated the number of ones previously when i had see if i have a number n i have already calculated the number of ones previously when i calculated n by two and the number of ones are going to be same in both of them okay so this will be valid for what for all even numbers this will be valid okay it will not be valid for what it will not be valid for odd numbers let's check for the case n equal to 15 so whenever you have odd numbers what happens see whenever you have odd numbers n is equal to 15 if you do n by 2 that is equal to 7 right n by 2 is equal to 7 was the binary representation of 7 0 1 so what is happening what is the difference between 15 and 7 see what is happening you have 0 1 right and you are left shifting it okay if you left shift this you will be getting 14 but you need to add one extra one to make it to 15 okay so if you just simply left shifted you will be getting n equal to 14 just triple 1 will be 14 but you need to add one extra one to make it 15 okay so what is happening see very simple let's understand it again let me take one more example okay let's say you want to find the number of ones in n equal to 11 okay what is n equal to 11 is 1 0 1 how many ones are there three ones are there so what we'll do we'll look at n by two because we have already saved the answer for n by two so we will save we need not calculate the answer again we already know the answer for n by two what is n by two is five for the binary representation of five one zero one okay so how many ones are there in five two ones are there in five so what we will do we are just left shifting five right we are just left shifting five we get this value but in the end okay so this is n equal to 10 it also has two ones because 5 also has 2 1 so 10 also has to ones but if we add one more one we will be able to reach what we will be able to reach 11 so whenever you have a odd number right look at n by two but also add one extra one okay that is a simple logic okay now let's build a simple code what is the simple code you have to find the binary you have to find how many ones are then binary implication of a number n it will have the same number of ones as n by two if what if n is even okay it will have this it will have same number of ones as n by two plus one if it is odd that's it these two line of code is the entire code okay so let's quickly code it so now we will just do it in o of n time complexity okay so what we are doing we are building the answer vector right we are building the answer vector so what we will do so what is answer of i very simple just look at answer of i by 2 and if okay so this will be what this will be for even numbers what is happening answer of i is equal to answer of i by 2 okay if i is ok if i is even so if i mod 2 is equal to 0 then it is just this ok else answer of i is equal to answer of i by 2 plus 1 okay that's it this is simple logic now let's submit and see if it's working so what is the best thing about this the time complex is just o of n okay it's working thank you for being patient and listening
Counting Bits
counting-bits
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:** \[0,1,1\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 **Example 2:** **Input:** n = 5 **Output:** \[0,1,1,2,1,2\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 **Constraints:** * `0 <= n <= 105` **Follow up:** * It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? * Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
Dynamic Programming,Bit Manipulation
Easy
191
142
what is up YouTube today I'm going to be going over linked lifecycle - it's a going over linked lifecycle - it's a going over linked lifecycle - it's a continuation of the first link list cycle problem it's a medium problem link code I started a slack channel I have to invite link below where I post daily leak Co problems so join if you guys want and lastly you check out my channel subscribe now let's get to it then reads given a linked list return the node where the cycle begins if there is no cycle returned also its continuation the first problem we got to first determine if there's a cycle and then if there is we have to determine where the cycle begins this part just explains what's going on under the hood the input we don't really need to know that we do not modify the linked list so we return the same we will actually we don't return the linked list we just return the position so we can't modify it so right here we see - is where the it so right here we see - is where the it so right here we see - is where the cycle starts so we would just return its position which is 1 another example is negative if they pass to say there's no position equals negative 1 means there's no cycle so as you can see there's no cycle so we return no in that case so there's two parts to this problem basically I'm gonna go over the first part on the whiteboard on first parts the same thing is the first problem we just determine if there's a cycle so we have the slow and fast pointers so I labeled them here for you fast moves two notes at a time and the slow moves one at a time and when they equal each other then we if they equal each other we know we have a cyclist if fast or fast on next ever equals no we know there's no cycle and we can just return null so I'm going to juice fast first so 3 4 5 6 7 8 9 10 11 so if you think about it slow is all we gets gonna match the number in node in my example that's why I labeled them in order so we could immediately determine after we do fast well when it's 11 it's also on the 11th note so that's where they're going to intersect basically so just to show you guys if I keep going with slow e 9 10 so they equal each other here so we just determined that they do have a cycle that's where the intercept is so let's code that out first that's going to be a separate function so I'm going to have this over this node intersection and let's just pass it head and we're gonna have create our pointers slow equals head we started him off at the same place fast equals head and Wow fast does not equal no and fast dot next does not equal no fat slow equals so we're moving slow one at a time and fast two at a time and if slow equals fast we can just return either pointer that we just determined that there is a cycle so let's return slow and if we break out of the while loop then we know there's no cycle so let's return no okay and so then the second part of the problem would go over on the whiteboard as well we have to they just clear these and so we're going to now have start and intersect so we want to start the intersect where we found the intersect so that's gonna be right here we're gonna label at 1 we're actually gonna move these at the same time start set to start the head so if we notice start is 1 2 3 4 5 6 nodes away from the start of the cycle right here intersect is also going to be 6 nodes away 1 2 3 4 5 6 so we just have to when they equal each other let's move them at the same rate and when they equal each other then that's where the start of the cycle is so let's just code that so let's do our base case first so if a head equals a knoll or head dot next equals no microphone so far away we're just gonna return null and then let's get the intersects so we're gonna call the function and if the intersect is null then let's return know as well that means there's no cycle okay so now let's create the start equals head and Wow yeah wall head does not equal start or not head intersects sorry we're just going to move them along at the same pace start equals start dot next and intersect equals intersects dot next and then finally when we break out of that while loop that means we found the beginning of the cycle so let's just we can return either pointer again so let's just return to start and that should be it so let's run it sweet and it works hundred percent really low memory usage because we it's actually over one space of complexity we're not creating a new linked list like the problem said we're just creating two nodes so oval in space complexity of n run time we're just looping through the linked list so that's it so if you guys liked this video please hit that like button I'll see you in the next video
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Medium
141,287
139
hi everyone today we are going to solve the little question World break so you are given a string s and the dictionary of strings while dict return true if s can be segmented into a space separated sequence of one more dictionary words note that's the same word in the dictionary may be used multiple times in the segmentation so let's see the example so you are given like an e to code string and a while dictionary read and code the output is true because so this part is the same as read and the code this part is the same as code so return through because the leader code can be segmented as a date and the code yeah that's true so that's why output is true and let's see the example too um so in this case we should return true because we have apple segmentation and ping and then uplogging yeah so that's why we should return through okay so to solve this question the easiest way to solve this question is to use um dynamic programming I believe and first of all I initialize arrays with lengths of input string plus one and the first value should be a true and the other values or false so in this case a little code is a has like eight character so from 1 to 8 1 2 3 4 5 6 7 8 is false and uh plus one so and then only index zero is true and uh this is a input what dictionary that did in the code and this is a string input string and every time uh we check the current index minus current wall equal true and then end of string I so before I equal current one in the case we should return we should change the value from false to true so let's begin and first of all so we already changed the value to True out in Excel so we start from index 1. and index I minus okay let's check with a lead but uh now index is one and the length of lead is four so one minus 4 is my negative 3 so in the case we don't do anything and check code is also links length of code is also full so 1 minus 4 is -3 so we don't do anything 1 minus 4 is -3 so we don't do anything 1 minus 4 is -3 so we don't do anything and then update oops index to next and then also move next again 2 minus 4 is a negative 2 and 2 minus 4 negative two and we don't do anything so update next I'll play next again three minus four and three minus four we don't do anything and then update next now I is pointing C and then index is 4. so 4 minus 4 and I look at index zero so that is true so it looks good I minus length current what is true looks good and uh one more thing n of end of s column index I equal W so in this case uh this index number is not included so before I so in this case so now index is pointing C so before I so that means this range so lead so end of string I should be D equal lead so what is a lead in the case so we find the lead so we change the value from false to true so now index 4 should be um true and then maybe next so we should break because we already find the uh the world so then next five and then five again five minus four is one and take one so but it's false so we don't meet this condition so we don't do anything and the code also five minus four one fourths and we don't do anything so and then now in index I pointing all and then move next so move next six so 6 minus 4 is 2 and the false and the six minus two six minus four is two and we don't do anything and then with next and uh again seven minus length is four and there's check three false and that's all we don't do anything and again seven minus length 4 is 3 4 and so we don't do anything and then update next updater next eight minus four is four so check four so true that is true and the end of s column I equal the current bar according to what so now index I is 8 here so the length of word before I is lead called this area so check the end of the word and the code but the current what is lead so this condition Falls so we don't do anything and then check with what code and 4 is 4 true so this condition me we meet this condition and check the end of the string before I so code is yeah exact same as this code so end of s column I equal current world code in that case we meet this condition so in the case we should change value to true and then move next but there is no name so we finish installation let me summarize my explanation so when I reach the length of 4 . we check the first four character of . we check the first four character of . we check the first four character of string and we have exact same string in the word dictionary so we can confirm the first four characters uh two so that's why I change index 4 to true and then from in a length of five to eight so which means the this area uh again we have a same string in the word dictionary so that's why from lengths of five to eight we confirm that we have same strings so that's why we should uh change the last index to true so after that all we have to do is just return the last index of array so in this case too yeah that's why uh in this case we should return true so that is the basic idea to solve this question so with that being said let's jump into the code okay so let's write our code first of all DP equal to Plus and pause multiply length of string so as I explained earlier and therefore I indents and start from index 1 to length of string plus 1 because we want to check length of string so that's why we need to press one and then for word in word picture so we check each word and if current index minus length of Y is greater than or equal zero and DB and uh current index minus X of what position is 2 and is so range of a string before index current index and ends with what in the case update current index with true and then break spirit after that just return last value of DB so DB minus one yeah okay that's it so let me submit it looks good and the time complexity of this solution should be uh one square multiply m so N is a length of string so we iterate through all characters of s and every time we check the each one so m is a number of word in word dictionary and then another thing we iterate to um s string again here so I guess uh n multiply M multiply N I think so that's why our o n Square multiply m so that is a Time complexity so let me summarize step by step algorithm this is a step-by-step algorithm of wild this is a step-by-step algorithm of wild this is a step-by-step algorithm of wild break step one initialize array for dynamic programming the first value should be true and the other values are false step two start iterating string in the step one when current index minus the length of each word is equal to 2 then check if we have the same word in word dictionary Step 2 change false to True at current index if we have the same word step 3 repeat step one and step two and step three return the last index of array 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
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
253
equal question 5 253 here meeting room 2 and it's a median legal question basically they give you a meeting array intervals where you have two number first one is the star and the second one is the end of the meeting return the minimal number of cons conference room that is needed looking at here zero i have a meeting run from zero time to 30 and another meeting from 5 to 10 and 15 to 20. so visually that we can see here easily you need one meeting room for 1 to 30 right and then the second meeting room to 5 to 10 and 15 to 20. it's pretty easy to see here your goal is to write a function to process this to return the output s2 so here 7 to 10 and 2 to 4 and you can see that the thing is not um they're not overlapped with each other at all because 4 is actually smaller than seven so in the end you only need one meeting here uh one meeting room and here's some constraints here and the company asked this question in the last six months a bunch of questions a bunch of companies asked this question definitely a great question to get familiar with and the best way to solve this question is actually using a structure called minimal heap and let's take a look at the example maybe um this way we'll do it uh i get see it more clearly visually and let's say a meeting start from uh 0 to 30 and there's another meeting room to 5 to 10 and 15 to 20 right how do we know it needs meeting room one here meeting room two here right that's what the minimal heap data structure is for uh i'm going to show you how to do this and basically the minimal heap is the result and i'm gonna store all these numbers to compare all these numbers for the beginning and starting time and if um in the end whatever i processed in the minimum heap the length the count of the numbers will be the meeting room that is needed and i will explain to you why when we go along each different numbers and you can see very clearly is that if my star number is smaller than the end number that means i need another meeting boom right because it's totally different um i'm not able to do the two meeting in one room at the same time and if my end time is smaller than the start time of the next meeting that means they're not overlapping and then they can totally use the same room that's why the minimal heap is so useful let's start processing all these numbers and one key factor is like if they give you numbers like this you want to make sure the uh rate that they give you is sorted so that it's it will be easier and accurate when you compare these numbers so after sorting the array will become 2 4 7 10 so that you can compare the number between 4 and 7 and you know 7 is bigger than 4 and they are not overlapping if they're not sorted then you will not get an accurate result right so in the first example 0 their first number is already sorted you can see 5 is bigger than 0 15 is bigger than 5 so which is good already so i'm not going to shuffle the sequence but i'm going to show you how to process this numbers together so in the minimal heap what i'm going to do the most important thing is i'm gonna append the second number which is the end time for the first meeting in a minimum heap first because so that i know when the first meeting will end for the first meeting then i can compare it with the beginning of the second meeting time in this case when we look at five is smaller than 30 so that means that they are overlapped they would not be held in the same meeting room it's purely impossible if five so we're gonna compare the first number in this in the second element right and if five is smaller than 30 that means that i need another room and so that means i need to append this set into my minimal heap remember the length of the minimal heap basically the count of the element is the answer that we need the meeting room that we need right so if five is smaller then i'm gonna append this value to um to this um minimal heap but the thing is when i append right i don't append the beginning of the start time if i pan append the start time how can i compare with the next meeting right when i append to the minimum heap i always want to append this number which is the second number the end time of the meeting just like how i append the end time of the first meeting right so that i can compare with the beginning time of the next meeting so since five is smaller i'm gonna append the end time here so 10 right and one really nice thing about the minimal heap is that when you append 10 to the minimum heap it will automatically change the sequence and the shuffle pop the minimum the smaller value to the top of the minimum heap and then when you actually pop then the value it will start popping from the most the smaller one that's what's nice about the data structure and then so it the queue currently looked like this right by this time we have already processed the second meeting 510 and now we're gonna process the last meeting which is 15 and 20. and if you look at a 15 is 15 smaller than the first number in the minimum heap no it's not it's bigger if it's bigger that means i can hold the meeting in this room right i basically don't care about um i don't need to remove anything because it can be hold by the same meeting room if this number is bigger than this number what i'm gonna do in this step is that i'm gonna pop this value basically pop this 10 and i'm going to append the ending time of the meeting so which is 20. so the minimum heap will look like this that's how it works and after i process the third meeting that's all from the array right and then if i look at the minimum heap here it's 2 the length is 2 20 and 30. there are two meetings here and for example if i have another meeting 35 to 40. um so i have a 35 to 40 and i always compare with the smallest number is 35 bigger than 20 yeah it is so i'm gonna replace this 20 with 40 and when i add 40 to the minimum heap it will automatically shuffle to something like this and so when i pop next time it will try to pop the smallest number if i have a meeting at 30 uh 36 or something like that it will try to add the add to the 30s meeting room and then if you look at the end result you basically only need a two meeting room for this case i hope it all makes sense to you and then i'm gonna show you how to do this in code is pretty straightforward so we're just gonna if not intervals we're just gonna rule out some edge cases and then if no intervals at all we just return zero room because there's no room needed one thing really important i mentioned at the beginning is that we need to interval star sort we need to sort the array first right so that we can compare the beginning of the second meeting with the first meeting more accurately and then i'm gonna set a result that's basically the minimum heap that i'm gonna pop from and i'm gonna say peep cue and heap push i'm gonna push the first um so i'm gonna push the second number in the first uh number set in the array to the minimum heap basically push to the result first that we either way we will need a meeting room right so intervals and that's 30 is basically the zero set the index for the 30 is the first basically index zero and then the second element index is one right so it's intervals uh zero one so by this time i already appended the 30 to the minimum heap and then for i in range of 4i in intervals i don't need to set range or anything i want to start so i'm going to process 4i i is basically this set and this set right so i'm going to process every single pair starting from the index one for the rest of the elements pairs in the intervals um array right and then so things are already uh so are i start from one so the first one i'm processing is actually i is this 5 and 10. so what i did was if the result 0 because it's a minimal heap the smaller number is always on top of the minimal heap basically if the first number in the minimum heap is smaller or equal to i0 that's the second case like when we have the 10 here if the result is smaller the 10 is smaller than i zero is the first number 15 right if it's smaller than the 15 what i'm gonna do is i'm gonna start popping from the uh the minimum heap kill dog heap pop hip hop rest um hip hop found the result so that's why the tank got popped and after i pop the 10 i'm going to append update a minimal heap with the end value in the 15. even it's not smaller even it's bigger like in the second case i'm still going to update it so that's why i'm going to do heap q dot heap push and the result and i'm going to append i1 that's basically the second number in the pair that we process every single time right and in the end i'm just going to return the length of the result because that will show us how many meeting room that we need that's basically it okay i hope this is helpful let me know if you have any questions and please like my video and subscribe to my channel and i'll see you soon bye
Meeting Rooms II
meeting-rooms-ii
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** 2 **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 104` * `0 <= starti < endi <= 106`
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied. If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
Medium
56,252,452,1184
322
hello everyone my name is Horus and in this video we're going to be going through leak code number 322 coin change for this problem we're given an integer array called coins and this integer array represents coins of different denominations and an integer amount which represents the total amount of money we want to return the fewest number of coins such that we can make up this value amount and if that amount of money cannot be made up using any combination of the coins then we want to return -1 and we can assume that we have return -1 and we can assume that we have return -1 and we can assume that we have an infinite number of each of the coins so we can use as many ones as many twos and as many fives as we need for this example so starting off with this example we want to see which is the minimal comat combination of coins such that we can reach the amount seven well what is one approach to do this we can start off with one approach which is to be greedy now being greedy means that we take the highest number coin that is available such that the amount is not negative and I'll show you what I mean we can start off with the largest number coin first we can imagine there's some pointer here now the largest coin that we can see right now is five and five is going to be less than the amount so we know that we can fit at least 15 into the amount so we can go ahead and say that we use five coin then the amount we want is 2 which is simply 7 - 5 so then we can 2 which is simply 7 - 5 so then we can 2 which is simply 7 - 5 so then we can see that five is going to go over the amount so this is not the value that we need then we move the pointer backwards and see the next largest coin which is two and we check to see if we can fit two in the amount and this is exactly the amount that we need so 5 + 2 is the amount that we need so 5 + 2 is the amount that we need so 5 + 2 is going to give us the amount 7 and this is going to be the minimal combination of coins such that we reach the amount value and the reason we know that this is the minimal amount is that we can take a look at a different combination of coins for example we can have something like 5 + 1 + 1 and this is also seven but here + 1 + 1 and this is also seven but here + 1 + 1 and this is also seven but here we're using three coins instead of two another option is to use seven $1 coins another option is to use seven $1 coins another option is to use seven $1 coins so we can have 1 + 1 so on seven times so we can have 1 + 1 so on seven times so we can have 1 + 1 so on seven times and that's going to equal seven and this is going to use seven coins so we can see that as we move downwards in the coin denominations we get a higher coin amount that we need so is the solution really that simple can we just be greedy and solve the problem that way well that's not really the case because we can find a counter example to using the greedy algorithm so we can take a look at this arrangement of coins that were given and the amount is still seven so let's try being greedy and take the largest coin value that we can so first we can take a five and the amount becomes two that we need well we can take a four because four is greater than the amount we can take three because three is greater than the amount and but we can take coins of the one denomination so we can take two of these coins and we'll get seven and this was one of the solutions before we didn't really change anything by introducing different coins so now this is one of the solutions but is this the optimal solution well no because we can see that there exist one solution here by taking a $3 coin and a $4 coin and this will a $3 coin and a $4 coin and this will a $3 coin and a $4 coin and this will give us seven and this is using two coins while the example above is using three coins so clearly this method is going to be much faster but we did not use the greedy algorithm so we have to find a different approach to solve this problem we can take a look at a Brute Force approach to solve this problem and that's by listing out each of the possible paths that we take from the amount so let's say we start from the amount 7 and we can either use a coin of one a coin of three a coin of four or a coin of five so we can kind of draw pads like a tree and each of these pads is going to have some denomination so this is path you taking the $1 coin this is going to you taking the $1 coin this is going to you taking the $1 coin this is going to be the path taking the $3 coin four and be the path taking the $3 coin four and be the path taking the $3 coin four and five and then from each of these values so let's say we took the $1 coin it's so let's say we took the $1 coin it's so let's say we took the $1 coin it's going to be the amount minus that value so it's going to be 7 - 1 which is 6 7 - so it's going to be 7 - 1 which is 6 7 - so it's going to be 7 - 1 which is 6 7 - 3 which is 4 7 - 4 which is 3 7 - 5 3 which is 4 7 - 4 which is 3 7 - 5 3 which is 4 7 - 4 which is 3 7 - 5 which is 2 and then we can continue this for each of the resulting options so let's take a look at the amount of three we have again four pads we can either take the $1 coin the $3 we can either take the $1 coin the $3 we can either take the $1 coin the $3 coin the $4 coin or the $5 coin so 1 coin the $4 coin or the $5 coin so 1 coin the $4 coin or the $5 coin so 1 3 four and five and if we take the one we'll get a value of two and then if we take the three we'll get a value of zero this is very important if we take four then we'll get Negative 1 and if we take 5 we'll get -2 and it's very important to notice the -2 and it's very important to notice the -2 and it's very important to notice the negative values these are indicating that we've gone too much over in the amount so these are already not possible however we also see that we have a zero value and this is exactly what we need and as we saw before the combination of 4 + 3 is going to give combination of 4 + 3 is going to give combination of 4 + 3 is going to give us seven and it's only going to use two coins so this is one solution to solve the problem but the time complexity is going to be very high because we're Computing a lot of these same values again and again for example if we compute the value two here we won't need to compute it here if we just store this solution or the number of coins to get to two in some cash and this is exactly the approach that we're going to use something known as dynamic programming and the way we will cach all of the resultant values is we're going to keep some array and this array is going to be called let's say DP and it's going to have all of the values so let's say the DP of Zer is obviously going to be zero we can start off with that and let's say to get to uh a sum of one DP of one is going to be one and so on now this approach is something that's known as bottom up since we're starting off with the zeroth value and we're going outwards until the amount value that we want so I'll write out the DP array values and then we'll calculate DP of s so now that I've written out all the DP values until 7 let's go ahead and calculate DP of 7 since we've already calculated everything before it and the amount of coins that it's going to take to get this sum then we can just use that cached value so DP of whatever and then we just add it to the coin value so we can get the current DP array value so I'll show you what I mean and you can see that DP of zero is going to be zero since to get to a sum of zero we need zero coins to get to a sum of one we can use one of the one $1 coins to we can use one of the one $1 coins to we can use one of the one $1 coins to get to a sum of two we can use two $1 get to a sum of two we can use two $1 get to a sum of two we can use two $1 coins to get to three we have a $3 coin coins to get to three we have a $3 coin coins to get to three we have a $3 coin to get to four we can use a $4 coin to get to four we can use a $4 coin to get to four we can use a $4 coin to get to five we can use a $5 coin and get to five we can use a $5 coin and get to five we can use a $5 coin and then to get to six we need a $5 coin and then to get to six we need a $5 coin and then to get to six we need a $5 coin and a $1 coin hence why it's two so each of a $1 coin hence why it's two so each of a $1 coin hence why it's two so each of the values here represent the amount of coins that we need to get to this sum so to actually find DP of seven we need to check the value against all the coin denominations plus the DP value minus the amount so what that means is that let's say we take coin one well then we're going to have to use one $1 coin we're going to have to use one $1 coin we're going to have to use one $1 coin plus the remaining sum which is going to be DP of 7 - 1 which is just 6 but we've be DP of 7 - 1 which is just 6 but we've be DP of 7 - 1 which is just 6 but we've already calculated DP of six right here and that's going to be 1 + 2 so that's and that's going to be 1 + 2 so that's and that's going to be 1 + 2 so that's going to take three coins if we use a $1 going to take three coins if we use a $1 going to take three coins if we use a $1 coin this way but let's say we use a $3 coin way but let's say we use a $3 coin way but let's say we use a $3 coin instead well then we want to instead calculate DP of four and DP of 4 is 1 so then we have 1 + 1 which is 2 and this then we have 1 + 1 which is 2 and this then we have 1 + 1 which is 2 and this is currently our minimum value that we have so then we continue to check the other coins so let's say we use a $4 other coins so let's say we use a $4 other coins so let's say we use a $4 coin this is going to be DP of three and DP of three is 1 and we again have 1 + 1 DP of three is 1 and we again have 1 + 1 DP of three is 1 and we again have 1 + 1 which is two so this is going to just be the minimum so we don't have to update anything and then if we check and use a $5 coin well then we can check this and $5 coin well then we can check this and $5 coin well then we can check this and then we see that we have DP of two which is going to take two coins so 1 + 2 is going to take two coins so 1 + 2 is going to take two coins so 1 + 2 is going to be three is not less than the minimum so this is exactly the amount of coins that we're going to return in the final amount so we can just return DP of 7 in the end and this will be our answer and if we talk about the time complexity for this algorithm well it's going to be Big O of the amount times the number of coins so let's say the Len of C which is representative of coins so this is going to be the time complexity since we have to calculate the DP values of all of them using each of the coin denominations so the space complexity is going to be Big O of amount since we have a DP array going to amount + one so we start at going to amount + one so we start at going to amount + one so we start at zero and we go to amount so this is going to be a space complexity of Big O of amount so with that being said we can go ahead and write the code for this algorithm okay we're on Le code and we can start writing the code for this algorithm we can start off by initializing the DP array so this is going to let's say have a maximum value of amount + one since we want this value of amount + one since we want this value of amount + one since we want this value to be higher than any of the coin values that we can get and this is going to be helpful when we're returning the final answer we can verify if it's not less than or not equal to amount + one than or not equal to amount + one than or not equal to amount + one because it's going to be updated otherwise so we can times so we can multiply this by amount + one and this is the number of amount + one and this is the number of amount + one and this is the number of elements since we have to go to from 0o to amount + to amount + to amount + one then we can put in the zeroth index for the DPR array which is just going to be zero then we basically want to Loop over from one to amount + one since over from one to amount + one since over from one to amount + one since these are the values that we're going to basically add to the DP array so for let's say amount in or a in range we'll start from one and go to amount + one this is going to be amount + one this is going to be amount + one this is going to be exclusive so it's going to go to amount then we can say then we want to basically Loop over the coins so for C in coins and we want to check if we can take that coin as a potential value this means that subtracting the coin value from the amount will not be non- from the amount will not be non- from the amount will not be non- negative so if a minus C is going to be non- negative then we can use it as a non- negative then we can use it as a non- negative then we can use it as a potential value so DP of the a value is going to be the minimum of the DP of amount which is what is currently stored there or it's going to be 1 + the DP there or it's going to be 1 + the DP there or it's going to be 1 + the DP a minus C and this one value comes from the coin that we're using this uh a minus C coin and then DP of a minus C is just the amount minus the coin so this is the remaining sum that we want to find and then check how many more coins we need to get to that value then finally we want to return DP amount or yeah DP amount if the DP amount is not equal to what we initialized it before so amount + one initialized it before so amount + one initialized it before so amount + one otherwise we can just return NE one that means that it was not updated so there's no correct value or no way to get to this value and this should be the answer so we can submit it and yeah it's accepted and you can see that it runs perfectly fine and this is the optimal dynamic programming solution running in Big O of amount times the length of coins time and has a space complexity of Big O of amount so with that being said hopefully this video helped you and you learned something and I'll see you soon
Coin Change
coin-change
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`. You may assume that you have an infinite number of each kind of coin. **Example 1:** **Input:** coins = \[1,2,5\], amount = 11 **Output:** 3 **Explanation:** 11 = 5 + 5 + 1 **Example 2:** **Input:** coins = \[2\], amount = 3 **Output:** -1 **Example 3:** **Input:** coins = \[1\], amount = 0 **Output:** 0 **Constraints:** * `1 <= coins.length <= 12` * `1 <= coins[i] <= 231 - 1` * `0 <= amount <= 104`
null
Array,Dynamic Programming,Breadth-First Search
Medium
1025,1393,2345
1,774
hello so today we are going to solve this problem called closest dessert cost and the problem says we would like to make a dessert and we are preparing to buy the ingredient and we have an ice cream base flavors and m types of toppings to choose from and you must follow these rules um when so basically we have a couple of rows three rules here that we must follow in order to make our dessert right one of the first one is must be exactly one ice cream base we must exactly use one we can add one or more types of toppings or not add any toppings at all and we have at most two of each types of toppings and then we have an array for base cast and rave toppings cost and the target and the goal here is to make a dessert with a total cost as close to target as possible and we want to return the closest possible cost of the desert to target there are multiple we want to return the lowest one the lower one okay so it seems like here the main thing is that we can add one or more types of toppings or have no toppings at all this one is easy since we only need one but here we can add one or more of one type of toppings we can't have we can't add more than two for one topping but we can have multiple tappings depending on the cost so if you take a look at this example one seven and this type of cost if we want to make target 10 we went the closest possible we can make 10 by taking first the base the second base and then topping cost of the first one and then zero of the second one right now take anything of the second one okay um okay so let's see how we can solve this problem the first idea that came to my mind was maybe using binary search over the possible cost and seeing if i can find a function and then see if i can find something close to it the close the closest one to target just using binary search but um i don't think that one is good because like these rules here are complicated for bad research to find them so i think instead i'm going to use backtracking here or just some recursion approach right so maybe um let's say if i go through the base costs right and then for each whole base cost i want to just check if i can get some cost there that's close to target right and so i will need to get result let's say we initialize it to just the first one right because we can just take the first base and without taking any topping ends at all so we can start with that and then we can now try with maybe have a function here a helper for possible right where we give it remaining so this is the remaining whatever remaining of x of the cost and i which is the topping we will be looking at so ram uh remaining of the cost and then i is the topping we are examining um and that would mean here i will start trying those so i will check possible uh if for the cost what would be what the cost would be that's yeah actually i want something and check that it's close to target so not possible here that i'm looking for yeah so the reminder maybe is yeah maybe not that so let's call it as the sum so far or maybe cost c so c is cost so far right and then here you just call it cost well let's just help her right so what this would mean is this here well i could just take b right or i could just take b and take one topping right so it'll start with zero here right so this is going to be just max of res and starting with that and here i would say if i so nt which would be the length of i think cost um and then here what i would do is um if i is equal to nt then we should just turn 0 if um otherwise i can either take one so take choices out big zero of topping i um or i can take one of typing i or i can take two of topping i right and okay maybe it's easier to just do like a helper on b upper on b plus so here maybe we could do c and just go to the next one we can maybe do c plus topping that i so typing cast at i or we could take two and go to the next one right so the rules here um but what do you want to do with these three here um and here i want to just start off with zero now if it's equal to nt then i want to say so it's called this soft dot is i want to say so diverse is equal to the max well to like get best okay and then i would just pass the res and i'll define best here so we'll get a cost see okay so we get across i want to check if it's the best so far okay let's password is the best so far so this is so far and then we have the new valley now we need to check if the absolute value between the difference we want the one with the minimal difference with target right and so minus target and so if it's smaller than the c is smaller than this so far minus target either that or we have the other case so here then well self.res is going to so here then well self.res is going to so here then well self.res is going to be equal to c otherwise if we are here we want to take if there are multiple we want to take the lower one so which means if they are equal and it's lower which means c is lower than uh best so far then we wanna say sub.rs is equal to then we wanna say sub.rs is equal to then we wanna say sub.rs is equal to this so far or actually you can just return it that way we don't need that to access soft batteries here and we have it um and then yeah the other chords will terminate and they need to and then here i could just return salt daras yeah backtracking recursion it's very similar i'm just trying the candida so it should be some more so here i'm doing i plus 1 in both cases and nt is just the length of topping cost so why doesn't it end up finishing here so we start with zero right okay let's print this wow seems like eyes never tell me what okay that's a little bit strange since the length is just two all right so it should have it's okay that's surprising what is the okay so should have worked it but for some reason i reached two but didn't stop oh i didn't return sorry about that's my bad why okay yeah no that's not possible to see okay so it's cold with nine some point four best so far which is very strange never been on um unless oh okay so there is a case where i'm returning nothing here so in this case just returned but so far right okay let's try the other cases so that's that one the other one is this and topping quests and teaching okay i think this should pass okay so that's cool um yeah i think this is good enough yeah that's it for now thanks for watching and see you on the next one bye
Closest Dessert Cost
add-two-polynomials-represented-as-linked-lists
You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert: * There must be **exactly one** ice cream base. * You can add **one or more** types of topping or have no toppings at all. * There are **at most two** of **each type** of topping. You are given three inputs: * `baseCosts`, an integer array of length `n`, where each `baseCosts[i]` represents the price of the `ith` ice cream base flavor. * `toppingCosts`, an integer array of length `m`, where each `toppingCosts[i]` is the price of **one** of the `ith` topping. * `target`, an integer representing your target price for dessert. You want to make a dessert with a total cost as close to `target` as possible. Return _the closest possible cost of the dessert to_ `target`. If there are multiple, return _the **lower** one._ **Example 1:** **Input:** baseCosts = \[1,7\], toppingCosts = \[3,4\], target = 10 **Output:** 10 **Explanation:** Consider the following combination (all 0-indexed): - Choose base 1: cost 7 - Take 1 of topping 0: cost 1 x 3 = 3 - Take 0 of topping 1: cost 0 x 4 = 0 Total: 7 + 3 + 0 = 10. **Example 2:** **Input:** baseCosts = \[2,3\], toppingCosts = \[4,5,100\], target = 18 **Output:** 17 **Explanation:** Consider the following combination (all 0-indexed): - Choose base 1: cost 3 - Take 1 of topping 0: cost 1 x 4 = 4 - Take 2 of topping 1: cost 2 x 5 = 10 - Take 0 of topping 2: cost 0 x 100 = 0 Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18. **Example 3:** **Input:** baseCosts = \[3,10\], toppingCosts = \[2,5\], target = 9 **Output:** 8 **Explanation:** It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost. **Constraints:** * `n == baseCosts.length` * `m == toppingCosts.length` * `1 <= n, m <= 10` * `1 <= baseCosts[i], toppingCosts[i] <= 104` * `1 <= target <= 104`
Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head.
Linked List,Math,Two Pointers
Medium
2,21,445
146
um hello so today we are going to do this problem which is part of Fleet code daily challenge so today's problem is lru cash so we want to implement a data structure um called lru cache where the lru cache has a capacity and do initialize with that capacity um which is a positive size right and we have two functions that we need to implement to get which gets a key and we want to return the value of that key if it exists otherwise when I return -1 and it exists otherwise when I return -1 and it exists otherwise when I return -1 and then put which is just putting at that key putting this value so we update um if the key exists um and if the number of elements in the capacity exceeds capacity value then we want to evict the list recently used key so when I removed that at least recently used key in that case okay um and get input must each run in all of One average time complexity so the our implementation needs to be of one okay so that's sort of the idea um now how do we tackle it so the easiest first way that we can do this um sort of straightforward solution which is using this order dictionary in Python now this is our potentially your interviewer may say that this is not allowed right because you are um you are using like a standard Library data class or class that almost in internally implements everything for you but nonetheless let's see how it works so we can just have our cache um basically we can just initialize it as another dictionary so basically if we just take a look here at what order addict is so basically it's just a dictionary that has methods that allow you to arrange elements in the dictionary order okay and essentially here what we are interested in are these two functions so move to the end basically move the key to the end of another dictionary right so in our case here when you access a key with a get here we wanna since it's just got used we want to put it at the end so that what we remove from the front and put the ones that I just got use it to the end so that they are the latest to get um to be removed right so basically we'll pop from the front um so maybe Z here and so maybe X1 or something in this Excel and so every time if xn is just the element that we just um added then we'll put it to the front so for example when we add this key we'll put it to the end here and then when we want to pop remove an element because we are we um we have more elements than the capacity then we can just pop from the front and so you can see here the elements that were added last won't be removed until the end so that's the idea behind order dict okay and these two functions um okay so now with that what should we do for um we definitely need to start capacity as well right um so let's just call that equal to capacity and then here of course if the key does not exist then we want to just return minus one that's what the problem says now otherwise we want of course to add it okay so we want to add we want to just return it sorry but here we want to update to make this key most recently used sort of right anyway and so to do that we can just um use self dot cache so remember this is um another dictionary that has moved to the end which does exactly what we want so move to the end what do we want to move this key okay um and that's pretty much it now for put um we are told that if the key is in self cache right we need to consider put as if it's um as if it's a recently used and so here because it exists already we need to updated to the most recently used so we need to do something like this okay and then self.cache for key we want to assign the self.cache for key we want to assign the self.cache for key we want to assign the value so it's this and then we want to pop from the front like we said here um from the front if we exceeded the capacity so if the length of the cache is bigger than capacity then we want to remove pop basically the least recently used and the list recently used is the one in the front in our order dictionary and so we can just um take our soft.cache and then pop the take our soft.cache and then pop the take our soft.cache and then pop the item from the front which is zero so it's what this is doing okay um and then that should be it so let's run this um except this needs to be solved that capacity looks good there and looks like it passed yes so it got accepted okay so this is sort of the order dictionary solution where we use the dictionary functions to do what we want to do but what if we are not allowed to use this other dictionary how can we solve it um okay so how do we tackle this so the main idea for this solution is to use the linked list now I know this is a little bit of a weird choice but why well what we need anyway in this lru cache to be able to implement it we need a way to access the least recently used right so we need to access least recently used and then we need to append the most recently used so when someone once when a node just gets accessed we need to add it to the end of the we need the pointer to get access to it essentially right to get access to the most recently used so that we can point the new one after it to the end basically so that we can sort of form a chain right in the order of most recently in the order of least recently used so that when we exceed the capacity remove this one and then if we add another element here and then when we exceed the capacitor again we use this one so we need to keep this order and you can see this is already a linked list approach but in our implementation here we need two things we need a way to be able to remove the list recently used but we also need a way to add to the end a new a newly accessed elements right so this tells us we need two pointers we need the pointer to the head of this linked list and then we need a pointer to the tail of this linked list okay so that's the idea here now for the values themselves of the keys in the cache we can just still keep a map so we can still just keep a cache like we did in the previous solution where we just assign the keys to the value okay however this is actually not enough right because um how do I explain this so um we don't need just a normal linked list we need to double your linked list so we need this to point here um now you may say why well because when we add an element here right what we want is we want the telt to point to sort of a dummy node so that we can always identified and when we are inserting a new node we'll insert it in between the tail and the one that was the tail was pointing to okay so let's say when I'm here and I have to tell like this so let's say I have the tail here which is just a domino with minus one and the head also is initially just at a minus one okay so what I need is I need a way to access this element to be able to insert this new element why because I want this next here to point to this one so I need to get access to this and the only way for me to get access to this with using the 10 is to have a previous pointer and then now this can point here and this will remove these two uh tell is still pointing to the one with -1 but we still pointing to the one with -1 but we still pointing to the one with -1 but we did insert the new node so that's the idea here okay and so when we want to remove um a node here what do we do so we want to remove head points to this dummy node this node that doesn't represent uh one of the values but it's just a domino to keep the pointer there then when we want to remove the list recently used we want to remove the one that had dot next points to and so to remove it well we just take so that you can think of this like we have a pointer here but we also have a pointer like this so when we do this what we want to happen is we want to remove this here and point it to the next one we want to remove this one and point it now to this one that way this one we got rid of it okay and basically with this way it should be very easy to do because when we do a get right when we do a get then we want to the new node we want to remove it sorry now remove it but when we do a get um we want to insert it to the front here right to represent that it just got used but we also want to remove it from wherever it was so let's say we wanna we get we have here key a and we get a then we want to remove this node so of course making this point here and then we want to put a here okay so that's what needs to happen forget now what about for put well for put if the capacity we haven't exceeded the capacity then it's easy we just need to set the cache key of course right but if the key was already in the cache then we need to just update the value but we also need to update here so let's say for example we had a link like this and let's say maybe this was here we had B and we just had put that makes key B have a new value maybe here it was five before okay so what do we need to do well what we need to do is um we need to remove this B here with the five and add a new B here right with the three okay and so we remove this node and then just insert to the right the new node and then additionally if add regardless of whether the keys in the case or not when we add a new key that is not in the cache and that makes it so that we exceed the capacity that we have then in that case we just moved we just removed the most recently used the sorry the list recently used which is the one that hit that next points to so hit that next in this case will always point to the list recently used and tell the previous oftel will always be the most recently used node okay so that's the overall idea of using linked list to solve this problem we know how to use it forget we know how to use it for the put function and both of them will be of one operation um and so that's pretty much it so let's implement this solution um okay so let's see how we can um implement it with this solution so we of course just need to put cash here but we said that we need a node right that has um a key value um and also next and previous okay so first we're going to just put the values in um and then this would be Val like that and then we need to have self.prev initially is none and the self.prev initially is none and the self.prev initially is none and the pointer to the next which is initially none as well okay so that out of the way what do we need here we need a pointer To The Head and the pointer to the tip so we said that each of them will have a domino and we need a similar one for the tell and since there is no node in between them we want to link them right so of course head needs to point to tell and we need a reverse link for prev from tell to head right so how do we do that well we need head next to point to tell so head down next to be equal to self data okay and then we need the previous foretell to be had so we need the previous four tail to be equal to head okay so with that initialization out of the way we can now update our get function to use the new thing so this here stays the same still right because cash is still just a dictionary just a map um we need to move the key here to the end so let's just create a function for that so it's called move to end and let's pass to it just the key so we need to take this node um that was the you know position in the linked list and move it to the end so that it's the latest one that's going to get removed um it will get removed after all the existing ones in the linked list um so here though there is um what we need is we need to say um here the nodes needs to have has both the key and the value so parameters so we need to pass both so let's just do that um and so here we need to move this to the end um the other caveat here is that our self.cache you will see it in a second self.cache you will see it in a second self.cache you will see it in a second here what we want to put is the node actually and so here what we want to put is the node for key and Val okay let me just move the rest out um okay and so here that means this is to get the value here that will return as an integer we need to do Davao okay and of course we need to Define this function we'll Define it in a second so we get the key but ideally here we want to get the node and so to get the node we can just say self.cash and using the key we will get self.cash and using the key we will get self.cash and using the key we will get the note um okay so now our get function should be complete let's do continue output function um so we want to update to the most recently one used one here um so for we want to just remove this one and then add it uh here because we will need to add it regardless if it's in the cache already or not we need to it will get updated if it was in the cache and then here um if it's a new one it will just get added again and so to do that we can just remove it right away okay and so let's create a function to remove um and what we want to remove is the node so we can just remove that okay um and now here what we want to do is we want to add the node if the queue is already there we'll add it because we just removed this from its previous position but if it's a new key then we'll just add it anyway right and so here we want to add cache the updated one okay this one um and so these two functions we need to Define one is for removing a node and the other is for adding a node I will Define them in a second and now with this what do we want to remove lists recently used if we exceed a capacity so that's what we want to do here so we want to check first if we exceed capacity which basically means that the length of the cache is bigger than the capacity we have okay so in that case we want to remove the list recently used how do we get the list recently used well we said head points to the node just before the list recently used because head is a domino which means basically if we do a head that next that will give us the list recently used node and so since our cache is filled we want to remove one element so we just removed the list recently used so to do that we just do use this function remove and then we remove the least recently used okay and now we want to of course remove the node from the cache right because we want to delete it and so we want to delete the node from the cache so this will completely remove it from our dictionary um okay so now with this put normally should be complete we just need to Define these two functions so first for move to end to move a node from somewhere to the end we need to First remove it from where it is and then just add it because add here adds the end okay so just before subtitle because sub.tell is the dummy subtitle because sub.tell is the dummy subtitle because sub.tell is the dummy node that we want our pointers to stay at okay so that it's we to access the previous the most recently used one we can just do sub.tell.prev so here first can just do sub.tell.prev so here first can just do sub.tell.prev so here first we remove it the node and then after that we add us all move to the end does um and now let's do let's define our um add and remove so for remove let's say you have a node um let's say you have a node like this and then you have an hour node here and then you have y and now of course you have your previous pointers um here and here so how do we remove this node here okay so first we need the previous node to get this one we can get it by node.prev okay so let's call that pref node.prev okay so let's call that pref node.prev okay so let's call that pref and to get this node this is just node.next right node.next right node.next right so let's call each of the because the outcome that we want right the outcome that we want is basically X pointing to Y and of course we also need um the prev pointer that's the outcome and so what do we need here so prev is this x next is this y okay so it's actually just to name them okay so how do we uh so this would be prev and this would be next just to make sure this is super clear and so what do we need well we need prev dot next right we need the prep Dynex to point to this one but we also need next.prev to point to but we also need next.prev to point to but we also need next.prev to point to this one right next uprev to point to this one and so to do that we just say next um dot prev will now point to prep and that's it so that's it for insert really um now let's do add here let's do the add so remember here we want to add so we would have self.tell so we'll always would have self.tell so we'll always would have self.tell so we'll always call it tell pointing like here and then there is some node X here what we want is we want of course there is the prep right what we want is we want prev sorry we want X to point to node and node to point to tell which of course would mean that we'd have our prev node here and then we would have our X node the previous of node 2.2 x the previous of node 2.2 x the previous of node 2.2 x right so how do we do that well the first thing we need to get access to is this x here what is that X well that X is just the previous first tail okay and so let's call this pref okay let's call it prep here as well and let's call it prove here okay and so once we have it what do we need to do well we know we want prevda next right prep that next to point to node right to point to this node here and then we want um the previous of node to point to pref so node.prev to point to prep so node.prev to point to prep so node.prev to point to prep okay and then we want the next of node to point to tell like this so we want node.next to point to tell but we also node.next to point to tell but we also node.next to point to tell but we also want to tell the previous Chords it's actually some data we want to tell to prev to 0.2 node so that means we want prev to 0.2 node so that means we want prev to 0.2 node so that means we want soft.tel.prev to point to node here okay soft.tel.prev to point to node here okay soft.tel.prev to point to node here okay um so we'll do that like this so with this liquid list um operations what's really good about it is that once you draw it out it's really easy to write it down you just can't do it um it's really hard to do it just in your head just draw out the previous state the outcome you want it what needs to happen for that to happen okay and so if we're on this hopefully it looks like there is a problem with um valve somewhere here because its value okay it looks like there is a slight problem so let's see um okay so there is a problem here so what we want to delete is the least recently used key not the key of the node that we want to add that doesn't make sense because then we will just override this right so we want to error you but to get the actual node you want to get the key okay and since this is a node we have the access to the key so that's one error there and looks like that was the only one call let's submit and looks accepted okay yeah so this um linkage solution is a lot better because here this is of one right even move to end here it's just remove and add and each one of them is of one so get is of one uh put is also this is of one as well and so both Solutions are of both the functions are often so all operations would be all of One um yeah so that's pretty much it for this problem please like And subscribe and see you in the next one bye
LRU Cache
lru-cache
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. * `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, null, -1, 3, 4\] **Explanation** LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 **Constraints:** * `1 <= capacity <= 3000` * `0 <= key <= 104` * `0 <= value <= 105` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Medium
460,588,604,1903
309
hello everyone welcome to my YouTube Channel programming with DP Wala today we are discussing the very interesting and the famous interview problem that is already asked in many interviews the name of this problem is best time to buy and sell stock with cooldown so in this problem we are given an array prices where prices of I if the price of the stock on that particular day in this problem we need to find the maximum profit that can be achieved we need to uh see some of the concern that they have given first we need to buy any stock and we need to sell that stock and after selling that stock there is one condition that they have given that you cannot buy the stock on the immediate next day because that day is the cooldown day so we need to maximize the profit and uh calculate the maximum profit that can be achieved so let's discuss this problem with the help of an example so here we are given in prices array which consists of the price of that particular stock on the particular day the price of the stocks are one two three zero and two the array starting from the index 0. and we need to calculate the or we can say we need to maximize the profit and print that maximum profit say here what we can do is that first we will start with the index 0. so what are the choices we have first we need to buy the stock here selling is not possible and cooldown is not possible as we haven't or we can say we haven't buy any stock so here we need to buy the stock there are two choices that whether to buy it or not buy it so here you can clearly see that whenever we have two choices what we do we simply apply dynamic programming as in my earlier videos as well I have explained that whenever they whenever we need to calculate any maximum or minimum thing and we are having two choices whether to take it and not take it at that time we simply apply dynamic programming so if you are having any queries I have explained in my earlier videos as well that when to upload dynamic programming so here we can simply apply dynamic programming first what we do first we build our recursive solution which will uh calculate all our values but there is a possibility that there is a condition uh where overlapping some problem case is there so to handle that overlapping sub problem we apply memorization technique which is a top-down dynamic technique which is a top-down dynamic technique which is a top-down dynamic programming approach so in this problem first we write the recursive solution and then after that we will optimize it with the help of memorization technique which now our solution become dynamic programming solution so let's discuss what is the approach behind this problem so for this particular test case here first at the 0th index we will buy or we can say we will buy the stock so we need to give uh one price to buy the stock so I after that what choices we have we need to sell the stock so we need to sell it but they uh here there are two choices to us that whether to sell it or not sell it so at that time here what we can do we can sell it so we can sell it and now as we have failed it we can calculate the profit so here what we can do 2 minus 1 is our profit and as in the question mentioned that after selling the stock uh after it's immediate in the immediate next day we can't sell or we can't buy the stock because it is a cooldown period so at index 2 we can't do anything so we simply move uh to the next index here at the index 3 uh we can buy our stock the price of that stock is zero so we buy that stock similarly now what the choices we have is that we need to sell the stock so here after that only one index is left and only one element is left so we simply need to buy or sell the stock so we sell at index for at the cost of debt selling is two so as we have sell the stock we simply a counter profit the profit is 2 minus zero selling minus by two so at last we have Traverse all the array or we can hold our whole array so the total profits we got is one plus two that is three so this is the only maximum profit that can be achieved from the given array so we will simply return 3 and we will print our answer so in this problem what we have done is that we have recursively checked that if uh buying is possible at that particular day or not if buying is possible then we have two choices that whether to buy it or not buy it if you buy it then uh after in the next upcoming days we need to sell that stock so there's no choices of buying again so uh at that time we simply made the recursive call for that similarly for the cell uh position at that time we have two choices that at the time of selling we have two choices that whether to sell it or not sell it if we sell it then we need to calculate the profit if we do not sell it so then after in the upcoming days we have choices of selling uh selling it so and one condition we have means that I have mentioned here that in the question they have uh said that after selling the stock he can't buy the stock in at the immediate next day because this is the cooldown pay so uh at that cooldown period we need to skip that day so we simply increment our index by 2 so that we will we can successfully Escape that day so in this way we will made our recursive call and this is the whole recursive approach for this question so but uh after writing the required solution there are possibly there is a possibility that many uh such calculations we are doing uh again and again so to avoid this we will apply the memorization technique to follow its optimization so let's see how we can make the recursive call and how to go move forward with the DP solution so here I have made the recursive calls that we need to do so uh there are two choices as I have earlier mention that if we can buy at that particular day then there are two choices that if you buy it successfully then we here I have mentioned that minus prices of idx mix we need to give the cost to the customer as we are buying it so after buying it uh we need to make the record we need to make the recursive call for the next index but at that time our uh buying is zero means we can't buy it because now this is the condition of selling after successfully buying it we need to sell it in the upcoming days or if we haven't buy it then uh we haven't paid anything so we simply made the recursive call for the upcoming day and they're the choices of buying it but similarly if we have by the we can say buy the product at that time uh we need to sell it in future so if this statement is false then we move towards our health part means we need to sell that shot at that time there are two choices whether to sell it or whether to know Australia if we sell it then we got the prices of IDs means we got that particular price for selling it so after that selling we are having two choices we are having the choices that we can buy the stock in the further upcoming day but here as the in the question they have mentioned that in the immediate next day we can't buy the stock so that this is the cooldown period so here we have made idx plus 2 means we are incremented our index to the two position as we need to skip that particular next day so for this we have handled this case and suppose if we haven't uh sell the stock and on that uh day so we need to sell our stock on the upcoming days so we simply made the recursive call for that here uh zero is there because we can't buy it because this is the option of uh now we need to sell the stock so after idx plus 1 or we can say we made the idx for idx plus 1 equals for the upcoming days so that we can we need to sell our stock on that particular day so in this way we have made our record few calls so now let's see how to approach this problem and how to write a dynamic programming code for this particular problem let's see so this is the approach or we can say the code that I have written for this particular problem so here what I have done here I have created the global DP vector 2dp vector where I will store uh our final answer for its optimization I have created a 2d DP vector and there are two changing parameters one is the index and the second one is the weather to check that whether there is a buying position or not whether to buy it or sell it there are two changing parameters so here I have made the recursive call 0 is the starting index we will start with the zero index of the array then at the first as in the starting we have only one choice with the uh to buy it and this is a size n is the size of that uh prices array and this is the price that I have passed so here this is our base condition that whenever our index reaches at our ending position or whether it is about out of the outer bound condition at that time uh we will simply return zero here I have made the recursive calls as I have mentioned in the explanation part that if the buying is possible at that time we have two choices that whether to buy it so if we have buy it then we do not buy it again we uh so we will made our buy as zero but if we do not buy it at that time in the upcoming days we need to buy it so buying is possible here I have made the recursive call for that and we will take the maximum of it similarly if the buying is not possible there and there's a chance or we can say there is a now we need to sell the stock so at that time what we need to do call the same two recursive calls but here as we are selling so plus prices of index we will do and as we know that after next particular day we will do not win we can't buy the stock again as easy to cool down period so we will increment it by two as we need to skip that particular day so after selling it successfully we have the choice of buying it again so we'll be set our bias one again but if we do not sell that stock and that particular day so then we need to sell that stock on the upcoming days so buying is not possible so here I have done the opposite of this uh in this case so we'll take the max of it here as we can see that I have passed the three manometer as I explained one is index second one is the buy third one is the side of the uh prizes array and the prices so here after doing all these things we need to do the optimization so here I have made the optimization condition that whenever suppose I as I've filled my DP table with -1 whenever I feel that whenever with -1 whenever I feel that whenever with -1 whenever I feel that whenever I calculate that value I will fill that table suppose in future if we get the same value again we simply written that value no need to calculate it okay and at the time of every recursive calls we will simply store it in our DP table so that in future if we go uh get the same recursive call for that particular day will simply return it here no need to calculate it okay and at last we written that DP value or we can say that particular value we got at the final or we can say the maximum profit we got so in this way uh the whole code is written for this uh particular problem and in this way I have successfully applied dynamic programming here so to approach dynamic programming problem first you need to be very clear that where to apply the DP and where to not apply DP and put four to five things in your mind develop doing the dynamic programming question as many students face problem in uh approaching dynamic programming problem they face that where to apply DP so you need to solve as many problems related to DP and consider four to five things in our mind that first Whenever there is a possibility that we need or in the question they have mentioned that we need to calculate the maximum or minimum type of thing and there are two to three two choices are there that whether to take it or not take it or we can say the question related to uh the particular standard question of dynamic programs such as zero and knapsack all such things are there and at that time we are simply applied DP and my one suggestion to all the viewers is that people saw approaching this problem let's try uh the its previous questions that is best time to buy and sell stock one two three and four it's four part because after solving that previous question it will be easier for you to understand this problem in a very efficient manner hope you like this video and hope this video is helpful in understanding this problem if you watch this video till this point please don't forget to like share and subscribe to my YouTube channel and stay connected for more such lead code check code force and daily lead code problems analysis thank you happy coding
Best Time to Buy and Sell Stock with Cooldown
best-time-to-buy-and-sell-stock-with-cooldown
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[1,2,3,0,2\] **Output:** 3 **Explanation:** transactions = \[buy, sell, cooldown, buy, sell\] **Example 2:** **Input:** prices = \[1\] **Output:** 0 **Constraints:** * `1 <= prices.length <= 5000` * `0 <= prices[i] <= 1000`
null
Array,Dynamic Programming
Medium
121,122
1,688
hey everybody this is larry just me going over q1 of the weekly contest 219 count of matches in tournament so this is a little bit tricky but actually you know just to make sure that it gets correctly especially if you're trying to do it quickly but you're given the rules it is a little bit strange but it is also very kind of natural so you just have to count the number of matches and by counting the number of matches you do the simulation uh the tricky thing is that you know for odd numbers you might have some weirdness but as long as you follow the rules and be careful you should be okay uh this is my code basically as long as we have more than one person left uh well we play n over two matches which is given here uh it's odd then it's still n over two matches it's just that one of the person will go to the next round automatically which is what happens so after one round and end of the two people gets eliminated and if there's an odd number if there's an odd person left then we he or she can get to the next round automatically so that's basically it uh and you keep on going until n is less than one and that's pretty much it um in terms of complexity this will take roughly speaking linear in the size of the input which is the number of bits uh so o of log n which is linear right um that's all i have for this problem uh let me know what you think you can watch me solve it live during the contest now ah another stone game are you kidding me do yeah thanks for watching uh let me know what you think about today's prom and just let me know what you think hit the like button smash that subscribe button join my discord more uh so you can chat with me and people and ask questions and uh i will see y'all next contest next farm whatever bye-bye
Count of Matches in Tournament
the-most-recent-orders-for-each-product
You are given an integer `n`, the number of teams in a tournament that has strange rules: * If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` teams advance to the next round. * If the current number of teams is **odd**, one team randomly advances in the tournament, and the rest gets paired. A total of `(n - 1) / 2` matches are played, and `(n - 1) / 2 + 1` teams advance to the next round. Return _the number of matches played in the tournament until a winner is decided._ **Example 1:** **Input:** n = 7 **Output:** 6 **Explanation:** Details of the tournament: - 1st Round: Teams = 7, Matches = 3, and 4 teams advance. - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 3 + 2 + 1 = 6. **Example 2:** **Input:** n = 14 **Output:** 13 **Explanation:** Details of the tournament: - 1st Round: Teams = 14, Matches = 7, and 7 teams advance. - 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. - 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. - 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 7 + 3 + 2 + 1 = 13. **Constraints:** * `1 <= n <= 200`
null
Database
Medium
1671,1735
494
so today we would be solving lead code question number 494 that is Target sum so what our question really means is that we are given with an array of numbers and we need two positions plus and minus in such a way that we are available with our Target sum 3 like for example and we need to print how many plus and minus in what way we can print in what way we can arrange these plus and minus so that we can get R sum as three so like in first example uh I can I want my target sum as three and it says there are five possible ways of getting three so what are those five possible ways of getting three so what we can do is firstly position A minus here A Plus here plus here so what the sum totals is 2 3 we can get a plus here A minus here and again we can see that we can we are getting some three same goes for this and the same goes for this the positioning of plus and minuses is the number of ways through which we will get our Target sum 3. okay so uh I think we should straight away jump to the code I will declare my answer function that would get obviously okay that would obviously be getting my target value I would be treating something with my indices and at last there would be some value that would be carrying current sum till now so I think that is pretty much it okay so my plan is to take all of the sums 1 plus any X number like let us not take one let us take X plus y plus Z Plus w so my plan is to take each and every pattern of plus and minus what we can get so I would be going through each and every number and assigning it a plus once and assigning it a minus ones and then calculating the sum and then seeing if my sum is really equal to my target sum or not okay so I know that my base case at some point of time would be if my I goes Beyond nums dot size then in that case there are two conditions which arise and those two conditions are if my current sum is equals to Target so in that case just return a one that means this is a way this is a possible way else just return a zero that we are not getting anything as our Target sum so just return a zero okay the things after this are pretty simple taking a positive value in the front of a number and taking a negative value in front of a number end positive is equals to answer nums Target as it is increment by I and add nums of I to my current sum okay add nums of I to my current sum that is pretty much it and what will be a negative way of doing the same thing answer nums Target I plus 1 go on for seeing more numbers and current sum and then simply take the negative of numset I of that number okay return the possible number of ways through which we would be getting positive is a possible number of way negative is a possible number of way their total number of ways would be through positive and negative and hence we have done this we would be calling our answer function saying I'll give you a nums I'll give you target and I'll give you in this starting as 0 and total current sum for now as 0 give me the answer and it says okay so it says positive I think negatives spelling is okay pause the tip sorry positive and this is it I goes greater than or equal to now dot PSI sorry okay I think this is accepted yeah if I submit it I think this would be accepted or this will be accepted this is accepted but the TC here we can see goes up till 2. 4 times 2 milliseconds we can reduce this by using some auxiliary space okay so I would be taking a map of pair end comma end as DP okay I would be saying if DP dot find this pair that is the pair of I and current sum is already available and that is not equal to DP dot end then just return BP at the DPA of this pairs value okay and at this point of time I would just do that DP of this pairs value is equals to positive plus negative and I think we are again good to go this is accepted and this would again be accepted and I think I have reduced TC a bit so yes RTC reduce from 2 to 2 milliseconds to 411 millisecond and this is a huge achievement so thanks for watching guys this was a recursive and a memorized approach of uh Target some question 494 lead code thanks again for watching and have a nice day and please do comment down your thoughts about this video and let's meet in the next video thanks for watching bye
Target Sum
target-sum
You are given an integer array `nums` and an integer `target`. You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. * For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and concatenate them to build the expression `"+2-1 "`. Return the number of different **expressions** that you can build, which evaluates to `target`. **Example 1:** **Input:** nums = \[1,1,1,1,1\], target = 3 **Output:** 5 **Explanation:** There are 5 ways to assign symbols to make the sum of nums be target 3. -1 + 1 + 1 + 1 + 1 = 3 +1 - 1 + 1 + 1 + 1 = 3 +1 + 1 - 1 + 1 + 1 = 3 +1 + 1 + 1 - 1 + 1 = 3 +1 + 1 + 1 + 1 - 1 = 3 **Example 2:** **Input:** nums = \[1\], target = 1 **Output:** 1 **Constraints:** * `1 <= nums.length <= 20` * `0 <= nums[i] <= 1000` * `0 <= sum(nums[i]) <= 1000` * `-1000 <= target <= 1000`
null
Array,Dynamic Programming,Backtracking
Medium
282
898
hey guys welcome back to my channel and i'm back again with another really interesting coding into a question video this time guys we are going to solve question number 898 bitwise awards of sub array question before i start with the problem statement guys if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications of more such programming and coding related videos and let's get started so basically guys we are given an array of non-negative integers and we want to of non-negative integers and we want to of non-negative integers and we want to find out that for every contiguous array let's understand what is a contiguous array first of all so for example guys you can see that we have got an array like this it's a non-negative integer like this it's a non-negative integer like this it's a non-negative integer array one comma two now if you do uh want to find out the continuous of errors and continuous values are those of areas which have a let's say a of i and a of i plus 1 to a of j should be greater than equals to i so what i mean by that is that the contiguous array cannot be 1 and then this 2 okay it can be only 1 comma 1 it can be only one comma two it can be singular one singular two or it can be one comma two basically it has to start from left and go towards right and taking into consideration only continuous elements in such a way so that you can see that i goes from i plus 1 to a r j then i should always be less than equals to j okay so this is called as a contiguous sub area in this case and once we find out those contiguous sub arrays then you have to bitwise or all the elements of that sub array and once you do that you will find out a result of all the bitwise ors and this resultant area of bitwise ors you want to basically find out only the unique results from that and return the number of unique results okay so let's understand this by this example so for example in this case all the possible contiguous sub arrays are listed here so one singular two one comma two and one comma two now if you bit wise or all the elements in these continuous sub arrays and you will get six results so obviously for the singular elements you'll get uh the single element values itself like one comma 2 if you are 1 with 1 you will get 2 if you are 1 with 2 you will get 3 and if you are 1 with 1 and 2 you will again get 3 ok so there are 3 unique values out of all these bitwise or results which is only one two and three so that's why the output is three here okay so we just want to return the number of unique results another example which is pretty straight forward guys it's the same as that of the above the constraints are also straightforward the array length goes from 1 to 5 into 10 to the power 4 and the value of the arrays go from 0 to 10 to the power 9 okay now let's understand the solution approach for this problem okay as you can see on my screen guys i already have a bit of a text written for you guys to understand a bit better let's start to dry run our solution approach with this so the first thing you can see here that i have actually created uh two sub-arrays sub-arrays sub-arrays three sub-arrays uh one is called as three sub-arrays uh one is called as three sub-arrays uh one is called as current and one is called as previous okay let's just keep it like this so there are three uh three data structures i have defined sorry not subways three data structures i have defined uh unique result this is going to give us the unique bitwise or values another data structure is called as current so current is basically going to hold the bitwise or of your current element for example in the let's say my current element is one it is going to hold a bitwise order of my current element with all the previous elements of that sub array that contiguous sub array so for example in this case the previous element to one is also one so it will have the uh it will have the or result of one with the previous one and also the one itself okay so that's our current subset then we have so that's our current set now the previous set is actually just going to have the bitwise or results of all the previous operations so for example in this case let's say i am at index 2 okay let's say i am on the last element i am at index 2 then previous set will have the bitwise or results of all the previous elements so it will have the bitwise or of one itself the second one also and the bitwise or of one with one because these are the only combinations we are left with right so it will have the bitwise or results of all these combinations which are prior to the current element okay obviously guys all these three data structures have to be hash sets because we only want to store unique results we don't want to store any duplicate results so we are deliberately taking hash sets so that our problem is resolved in that manner okay now let's go with our algorithm a bit how we are going to go forward so the first thing which we are going to do is we are going to traverse all the elements okay let's say my ith value is zero so i am at the first element i am at one so my current element becomes equals to one my current set is now having element 1 okay now my previous set is not having any elements so i will not be doing the bitwise or of 1 with anything ok so once i increment my i so now i can go to the next element but before i increment my i will assign my current set the whole current set to my previous set okay what will uh what will happen is that now the previous set is having the bitwise or results of the current so now the previous is having the bitwise or results of the current element so the current element was one so previous will have the previous set will have now one okay now i will increment my i to one so now my current element becomes equals to index 1 element which is also 1 in this case so now my current is 1 and my previous set is now this time having some value which is a bitwise our result of my previous element 1. so now what i will do i will take my current element i will current take my iath element and i will put that so i will have my current element and i will or that with my previous elements all the previous elements so what will happen if you do the or of current element one so already you have got one in your current set okay now if i do or of one with this one whatever i will have two okay uh or of one with one is two right yeah so now i will have two in my current set okay so now my current element uh one also is there in the current set and the bitwise or value of current with the previous element is also in the current set now i am done with this iteration i can increment the i to 2 but before i do that i will have to assign this current result to my previous set so i will do now in prior in my previous set i will have 1 comma 2 okay so i will have 1 comma 2 in my previous set now my index value is 2 so i am at the last element so now my current set is only having two okay now my current set is only having two but my previous set is having the previous results previous or results of uh the elements which are prior to the current element so i have to or my current element with all these previous elements so i will do two or with one and if you do two or with one whatever you're going to get i think one yeah so if you are one with the two you get one and if you or two with the two then you get two okay so now at the end of my array my previous subset would have one and two okay so uh so oh no sorry if you do or of uh two with one sorry uh sorry my bad guys if you are two with one you will get three not one so if you do bitwise or of two with one you will get three but if you are 2 with 2 you will get 2 ok so now this is our previous set now obviously we are out of our elements and we don't have any other values but what we were doing behind the scenes guys while they were storing the elements in the previous set actually we were also storing these unique or results so these all results were also getting stored in the unique results so in this iteration in the after the first iteration one was stored then after the second iteration one comma two were generated but obviously one is already there so two was stored and after the last iteration three was also added in the unique result so while they were creating these uh previous uh set and current set we were also storing the bitwise or results in the unique result at the end guys we are going to return the size of unique result and in this case obviously the size is going to be 3 and that is going to be our answer okay so i hope guys the solution approach is clear to you what we are going to do we are going to implement the exact same thing using the code now at least let's see how we can do that so hash set integer so the first set which we are going to create is called as unique result which is going to be our results new hash set integer the second set which we are going to create is going to be called as previous and the current set we are going to create in our for loop because for every current element we have to create a new set right so integer equals to 0 to i less than and dot length i plus so for every current element i have to create a new set so let me just copy this and create current now obviously the current set is going to have the iath element okay and the unique result is also going to have the is element okay because we all know that the singular elements are also part of the contiguous sub array okay so we have added the ith element now what we are going to do we are going to traverse our previous array so integer previous preprev in previous is going to traverse from there and we are going to or every value of previous element so pre or with array of i so every value of previous uh set with the ith element and we are going to store that value in our current also we are going to store the same value in our unique results as well okay because a unique result and current are both sets so they will only store the unique values once this entire thing is done then we are going to assign previous to our now created current value so obviously uh for example in this case the current became one comma two so this whole current is now assigned to previous and now the next previous becomes uh current and the next element can be now bitwise odd to these elements okay finally when this entire for loop is completed the unique result is going to have all the unique values so return unique result dot size let's run this code guys let's see if this works and you can see that it works for one example and it is going to get accepted for others as well and there you go it was okay so that was the video guys i hope uh you guys uh understood the video and your coding factors become a little bit better if i talk about the time complexity for this solution guys then for this solution the time complexity is going to be order of n square so t is going to be order of n square uh the reason being is that we are ordering uh doing the bitwise or operation of every element with all the subset elements in the uh down the lot so that's why the time complexity is order of n square if i talk about the space complexity guys then uh space complexity is order of n because we are creating three sets so we can say three times uh three and uh if you are storing any elements and basically three and space is being used so using the big o you can say that it's only order of n okay so that was the video guys i hope uh you understood the solution and you like the solution as well if you do then please do not forget to like this video share this video with your friends please do subscribe to my channel and hit the bell icon for future notifications write down in the comment section below anything you want to say to me guys any feedback is definitely welcome and thank you so much for watching guys i'll see you guys in the next video until then take care and bye
Bitwise ORs of Subarrays
transpose-matrix
Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A **subarray** is a contiguous non-empty sequence of elements within an array. **Example 1:** **Input:** arr = \[0\] **Output:** 1 **Explanation:** There is only one possible result: 0. **Example 2:** **Input:** arr = \[1,1,2\] **Output:** 3 **Explanation:** The possible subarrays are \[1\], \[1\], \[2\], \[1, 1\], \[1, 2\], \[1, 1, 2\]. These yield the results 1, 1, 2, 1, 3, 3. There are 3 unique values, so the answer is 3. **Example 3:** **Input:** arr = \[1,2,4\] **Output:** 6 **Explanation:** The possible results are 1, 2, 3, 4, 6, and 7. **Constraints:** * `1 <= arr.length <= 5 * 104` * `0 <= arr[i] <= 109`
We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!
Array,Matrix,Simulation
Easy
null
1,964
hey what's up guys this is sean here so elite code number 1964 find the longest valid obstacle course at each position right so the description of this one is pretty long but you know so basically uh we're trying to build some obstacle courses you know so we're given like obstacles of length n where the uh the obstacles describe the height of the ice obstacle and then it then defines the longest obstacle course you know so the longest obstacle course is the basically the previous order the longest uh obstacles on the left side who is either equal or smaller than the current one right basically has to be a either equal or smaller uh then the negative the next one because here it says you know every obstacle except the first one is taller than or same height as the previous one right okay so that's the uh the definition of the long obstacles but i think this one is kind of long but uh i think it's all it's going to be easier to look at some examples here right so for example we have obstacles here and then the output is one two three why is that because in at one here uh the length is one right and because there's nothing on the left side but for two you know for two we have two because one two is the answer for two that's why we have two right and for three obviously three because we have one two three and for this two here it's also three because we have one two and two right that can give us like longest obstacles so then there are like some another examples here you know and some constraints so actually so after reading this description you should be realized that you know this is like another a bit vibration of the longest increasing subsequence right basically the ios the only difference is that this one is not like increasing either it could be equal or greater right because with is you know everything has to be strictly increasing right but for this one you know it could be the same right so that's the only difference and plus uh this uh constraint right with an of n so we need with this 10 to the power of 5 we cannot use n square because since we already figured out its ios with a little bit of variations you know the naive solution for ios is going to be a dp right with n square time complexity where you know for each of the i here we will check all the previously dp values right and then we'll get the minimum uh we'll get the maximum among all the previous dp values right but that will be o of n square so which means for this one you know i believe i have already talked about there's like a unlock login solution for this ios where we will be using the binary search right so basically we binary search the dp value here you know we have a dp array here right so we do a binary search on this dp array here with the current value um basically if the index is within the size of the dp then it means that we can insert it right and then when the index is outside of the dp of the uh us outside of the uh the dp array here it means that we need to increase the dp which will and in the end the length of the dp array will be the longest will be this hour s we're looking for right so for example let's use the example to explain this let's say we have three one let's see that we have to do this three one five six four two right so if you're only looking if you're only talking about ios right so for this one you know we have a dp here right we have a dp value array here so at the beginning if we do a binary search on uh on this one obviously we get an index but the index will be uh greater than the dp size right so that's why you know we're gonna insert this one to uh three into the dp right so now we have uh dp equals to three right and then we have one here right so if we do a one is do a binary search um there is one on this dp array here what will we have we'll have zero right let's say we're talking about uh final search uh bisect left okay i would never the zero it would never index if it's in the dp we update this value with one so which means that you know for one we have dp equals to one right and then when it comes to five right what we have five if we do a dp a binary search on five you know five uh this one will get the index will have what the index will be one in this case right so that's why we're gonna ex extend this dp array to one five okay and then for 6 again right this one's going to be a 1 a 5 and a 6. okay right and then what and then 4 right and then we have 4 here so if we do a 4 the index will be what the index will be one right because since we're doing a bisect left that's why you know for four we're going to update index one with this number gonna be one four and six same row is two it's two we have like what it's gonna also be a index is going to be one right so you have one and we're gonna update this one with one two and six okay so basically we use a binary search to track the uh basically to track the smallest right to track the smallest uh value at each of the index so that later on you know if we have another values uh greater than 2 here we can try to increase that later on right because now we know that you know at index one here the smallest is two right so if we have some bigger number after this uh average two here we can append this one to here and then in the end the length of the is will be that the final answer so that's basically the binary search solution for it for the is okay but as you guys can see we use a bisect left because we're looking at what uh strict increasing right that's why we have to do a uh bisect left but for this one the only difference is that we are we also need to consider the same value right to this uh into this consider into this uh bisect uh binary search so what does it mean we can all we need to do is instead of bisect the left we just need to do a bisect right because you know for example we have one two three and two right if we use the same logic here you know dp of dp right so at the beginning we have one right and then we have one two and then one two three right one two and three right and so now we have two here right so when we have two here if we do a bisect left right so then what will be the what would be the index it's going to be one right but instead what we need is instead of one we need two because one two also counted that's part of the long the longest up circle course right that's why we need uh index two here so that's why we're gonna do a bisect right and as you guys can see actually the index plus one will be the answer for us right for each of the index right because for the index we have zero right we have one and then we have two and two right if we do i plus one then this is our final answer so that's it right i mean as long as you can figure out this is a bit of variation of ios with the uh binary search uh solution everything should be pretty straightforward right so we have this one obstacles uh actually we don't need n in this case okay so all we need is a dp right so let's say we have a dp array and then of course we need answer all right as well right so for obstacles in obstacles right we have index right index going to be a bisect like i said it's going to be right we search the dp with the final obstacle right if the index is smaller than length of dp okay we do a update right index equals the ob circle right else we do a dp dot append of this obstacle right and then the only thing left is that we just need to use the index plus one to update the answer right index plus one okay and then return the answer so that's it okay cool right so this one no it's this one's not that hard but i think the only thing is that you have to be realized that first this is ios problem and second is you need to know there is like a unlock and uh solution for it given like given the constraints here otherwise it will tle and the last thing is that you know uh so this is a little bit of vibration of the regular rs solution where we have to consider also uh consider the same number right into the final answer that's why instead of bisect the left we need to do a we need to use a bisect right okay and then that's it i think cool uh i don't think there's anything else i want to talk about for this problem i would stop here thank you for watching this video guys and stay tuned see you guys soon bye
Find the Longest Valid Obstacle Course at Each Position
find-interview-candidates
You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle. For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that: * You choose any number of obstacles between `0` and `i` **inclusive**. * You must include the `ith` obstacle in the course. * You must put the chosen obstacles in the **same order** as they appear in `obstacles`. * Every obstacle (except the first) is **taller** than or the **same height** as the obstacle immediately before it. Return _an array_ `ans` _of length_ `n`, _where_ `ans[i]` _is the length of the **longest obstacle course** for index_ `i` _as described above_. **Example 1:** **Input:** obstacles = \[1,2,3,2\] **Output:** \[1,2,3,3\] **Explanation:** The longest valid obstacle course at each position is: - i = 0: \[1\], \[1\] has length 1. - i = 1: \[1,2\], \[1,2\] has length 2. - i = 2: \[1,2,3\], \[1,2,3\] has length 3. - i = 3: \[1,2,3,2\], \[1,2,2\] has length 3. **Example 2:** **Input:** obstacles = \[2,2,1\] **Output:** \[1,2,1\] **Explanation:** The longest valid obstacle course at each position is: - i = 0: \[2\], \[2\] has length 1. - i = 1: \[2,2\], \[2,2\] has length 2. - i = 2: \[2,2,1\], \[1\] has length 1. **Example 3:** **Input:** obstacles = \[3,1,5,6,4,2\] **Output:** \[1,1,2,3,2,2\] **Explanation:** The longest valid obstacle course at each position is: - i = 0: \[3\], \[3\] has length 1. - i = 1: \[3,1\], \[1\] has length 1. - i = 2: \[3,1,5\], \[3,5\] has length 2. \[1,5\] is also valid. - i = 3: \[3,1,5,6\], \[3,5,6\] has length 3. \[1,5,6\] is also valid. - i = 4: \[3,1,5,6,4\], \[3,4\] has length 2. \[1,4\] is also valid. - i = 5: \[3,1,5,6,4,2\], \[1,2\] has length 2. **Constraints:** * `n == obstacles.length` * `1 <= n <= 105` * `1 <= obstacles[i] <= 107`
null
Database
Medium
null
232
hey what's going on guys today i'll be going over how to implement a queue using two stacks the first thing you want to note here is the distinguishing features of a queue and a stack so in the case of a queue we have this concept of first element and first element out and for stacks we have this concept of last in first out in this problem we're given these four methods to implement push pop peak and empty and we're only allowed to use functions that are unique to a stack and those functions are right here so push to top peak slash pop from top size and is empty and the tricky part about this problem is that we have this follow-up question here is we have this follow-up question here is we have this follow-up question here is and you implement the queue such that each operation is amortized constant time complexity and what i'm gonna do is first go over a o of n time complexity and then go over how to optimize that o of n time complexity and make it of one amortized say we have three elements we want to push onto our queue and let's say those three elements are one two and three in that order so we have one two and three and when we go to pop elements out of the queue the one would go first then the two then three and now how would we translate that into stacks so what we want to do is once we know what elements we want to push in we just push it on to stack one so one two and three in that order now we want to actually pop an element out of the queue so we would expect to get one here but if we were to just to pop from the stack one we would get three so what we want to do instead is pop every element in stack one and move it over to stack two so we pop three and we add that to stack two we pop two we add that to stack two and then we pop one and we add that to stack two and then we would pop on stack two and we would get r1 here and peak is essentially the same thing except you're not actually popping it you're just getting the last elements in the array so that's why we have the self dot stack to negative one here so let's say you pop off this one here and then afterwards we need to restore the initial state stack one so what we would do is pop all the elements of stack 2 and add it back into stack 1 so stack 2 is empty and what you're left with is this after the pop operation and you can go on and keep doing pushes and pops and the algorithm will work as expected and that's an o of n time complexity for both the pop and the peak algorithms so i should change this o n for peak here so how do we remedy this well first i would recommend you to pause the video and look over this code right now and see if everything makes sense now i'm going to go over the algorithm to make it of one amortized runtime let's go back to where we are appending we were pushing the numbers one two and three into the queue in that order so what we would do is we would push these elements onto the stack so one two and then three and then now when we go and do our pop operation we would pop out three pop out two and then pop out the one now we just pop out our one and we return that one when we do our pop and we're just left with two and three now the next step would be to clear out stack two and make that empty and move over the two and the three back into stack one what you might notice is that we don't even have to restore the state of stack one we can just keep this current state of stack two and whenever we wanna push a new item onto stack one we just push it on to stack one and when we do a pop-up to stack one and when we do a pop-up to stack one and when we do a pop-up stack of the queue though second element we wanna do a pop-on second element we wanna do a pop-on second element we wanna do a pop-on would be two so what you'll notice is two is already at the top of stack two so we just pop that and then we return that so essentially we have these two states and one state is where stack two hasn't been populated yet and the other state is when stack two has been populated so we have these if statements here to check whether back two isn't populated so for the pop we would first check to see if there are items in stack two and if there are then we just return we just pop the element off of stack2 and if it isn't we go through our original algorithm where we're popping every single element in stack 1 until stack 2 is populated and the same can be said about the peak method and we have this if statement checking to see if stack 2 has elements in it and if it does you just return the top element in stack two and one caveat here is that with this algorithm we always have to keep track of what our front element in the queue is so say when we want to do peak we need to keep track of that element let's say that in the case that stack two is completely empty and we tried to do a peak operation on it we would see that there's nothing actually in stack two so we would return this self dot front and what self.front is pointing to is and what self.front is pointing to is and what self.front is pointing to is this right here so how does it point to that we have whenever we push an element and we see that there are no elements in stack one we set that pointer at front pointer equal to that first element you push onto stack one and after that you would just return stack or you would return that front value whenever you do a peak when stack2 is empty and one thing to note is both of these algorithms have an o of n base complexity so we have two stacks here which would be m plus m and that reduces to just o of n and if this video helped you out be sure to drop a like and consider subscribing thanks for watching and i'll see you guys in the next one
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
1,438
hello everyone this is your daily dose of late code assuming you have an array of integers and a integer limit can you find the longest continuous sub array such that the max range of the array does not exceed our limit no can you if the limit is equal to 5 in our case the longest continuous sub array we can find as 2 4 or 7 to the max range of the array is 7 minus 2 which is 5 and it does not exceed our limit to start with the question we can always use the brute force solution find all the possible sub arrays and don't find one with the longest the lens that the range does not exceed our limit they ask you how you are you just have to say that you're fine when you're not really fine B so for every left and right boundary of our array we can find a self array and we can check if the array meets our condition which is and we simply return the result let's see if that works so we are having a time limit exceeded which is good means our logic works this is a pretty bad solution to be honest time complexity is o and three calculating the maximum mean every time is quite time-consuming we don't need to is quite time-consuming we don't need to is quite time-consuming we don't need to do that if we already calculate those before we just need to know if the new number we find is our max or me we can have a max number and whenever we are increasing the right boundary all we need to do is to update a max number and mean number if later we find our array meets the limit constraint we can simply update our own maxbox let's see if this solves our question I'm fastest fuck-boy so we are still I'm fastest fuck-boy so we are still I'm fastest fuck-boy so we are still getting a time limit exceed since this algorithm is now changing from 1 3 2 oh and tooth it is still very complex if we have our super large array this is fine the problem in our solution is that for a right boundary we went through all the possible left boundaries but actually when we check the next right boundary we already know that the left boundary won't exceed the one we find in a previous iteration so all we need to do is to find a smallest distance we need to move our previous left boundary to satisfy our limit requirement think this as a sliding window where we want to move our boundary to the most right and see what's the minimum shrink you need on the left side however this solution will still give us over to time complexity so what we need to do is for every right boundary in our possible sub array we will find a left boundary which starts from the right boundary and keep going left until we meets the end of our array later we'll return the result ok it's still te unexpected [Laughter] [Laughter] [Laughter] so like we said we will need a variable to recall the left number and here we won't go through all the possible left boundaries we will start in from the previous iteration we will need some way to find a max number and the mean number and once we find a max number and the mean number we just need to check if our current sub array meets our criteria oh if not then we will move to left boundary to shrink it so the problem being how do we find a max number and a mean number we will have to queue to store those information let's start with the mean number this is a increase in queue recording what's the smallest number the second smallest number the third smallest number between I and J so every time we meet a new number we will add it to our main queue but before that we need to do some cleanup here I mean Q so this is a cleanup for our I mean Q this basically means we check the queue from the last or the number that is close to our current number if the number is bigger then we don't really care because that number cannot be the smallest number between I and J because we are including the current number if this is smaller this number should replace the last number in your I mean Q we keep doing so I'm sure there are some number that is smaller than our current number which means that number is the smallest number between the I and J so the minchia stores a bunch of numbers the first timer always means the smallest number between IJ the second number means the smallest number if we move I across the first number what's the smallest number between I and J and so on and so forth so if we move I to the J position the smallest number of between I and J is guaranteed to be numbers I'm J because I and J are in the same position there is only one number bitching ing God so we will have a max Q do the same thing for our max number instead that the first number of our max Q stores max number between I and J so every time we meet a number we will append that new number to our max Q and before that we will do some cleaning in our max Q to clean up all the number that is smaller and on the left side of our current number you can even use it on the washing up they're all clear again so now we find a maximum number and the mean number in constant time by just picking up the first number you mean Q and mass Q otherwise we will shrink the left boundary but while we're doing that we cannot use the leftmost number anymore what if that number is the max number that will change how we calculate the next max in the next iteration so we will need to update our max Q to see if that number is the biggest number if it is we can't use it anymore so we will pop it we do the same for the I mean cube because the leftmost number can also be the smallest number detering I and J we can totally using array here but in order to make the cooperation here faster we are using a DQ the DQ can do pop and pop laughing or one time Oh magic let's see if this compound and let's see the prophecy is true and let's explain why it is this faster because since there are a lot of operations in this for loop these are all operations so we don't need to care about that part what we do care is about these min q and max Q we are only adding new numbers into our immune cube and mask you while we are moving the index J which is the right boundary so every number is guaranteed to be adding to our mean Q or mask you at most ones which means the total operation of all this well function is going to be owin so in a time we are doing o n which is going through all the right boundary plus all append operation we find in all the for loops which is going to be open and the same for our min Q and we will do some pop left which off the popular operation we do here inside this for loop is going to be o in total so in n we will still have a own ton capacity so is it any wonder people are afraid of technology
Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
find-the-team-size
Given an array of integers `nums` and an integer `limit`, return the size of the longest **non-empty** subarray such that the absolute difference between any two elements of this subarray is less than or equal to `limit`_._ **Example 1:** **Input:** nums = \[8,2,4,7\], limit = 4 **Output:** 2 **Explanation:** All subarrays are: \[8\] with maximum absolute diff |8-8| = 0 <= 4. \[8,2\] with maximum absolute diff |8-2| = 6 > 4. \[8,2,4\] with maximum absolute diff |8-2| = 6 > 4. \[8,2,4,7\] with maximum absolute diff |8-2| = 6 > 4. \[2\] with maximum absolute diff |2-2| = 0 <= 4. \[2,4\] with maximum absolute diff |2-4| = 2 <= 4. \[2,4,7\] with maximum absolute diff |2-7| = 5 > 4. \[4\] with maximum absolute diff |4-4| = 0 <= 4. \[4,7\] with maximum absolute diff |4-7| = 3 <= 4. \[7\] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. **Example 2:** **Input:** nums = \[10,1,2,4,7,2\], limit = 5 **Output:** 4 **Explanation:** The subarray \[2,4,7,2\] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. **Example 3:** **Input:** nums = \[4,2,2,2,4,4,2,2\], limit = 0 **Output:** 3 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 109` * `0 <= limit <= 109`
null
Database
Easy
null
203
this little challenge is called removing list elements we're going to receive a linked list and we need to remove all the elements from that list of integers that have the value val so let's say this here is our list we need to remove the nodes that have the value six so these linked lists will become this here what you see on my right here is the solution so here we have a function we have to return a node points on the first parameter here is the head of the linked list and the second parameter is the value that we want to eliminate so they don't guarantee here in this challenge that the head pointer is going to be valid so i'm taking care of that here and if it's null i simply return back the heads otherwise i want to make sure that the beginning of my list is actually correct so if the head pointer has a value that is equal to val meaning it's a value that we want to eliminate then i want to shift my head pointer let's say this is our list the value to remove is one so at first this is going to be the headpoint so what i've just painted here so we're going to verify does the head nodes have a value equal to one in this case yes so i'm going to shift my head pointer to this here now i'm going to compare again we can see that these two values are equal so i'm going to shift my head pointer here so moving forward in our program whenever we access the heads of that list we will always begin at this node so we will no longer have access to these nodes and in theory these nodes are going to be excluded from the linked lists now in this challenge i'm not actually deleting the notes from memory but you guys can go ahead and implement that as an exercise i think i've already showed that many times before in some of my hacker rank challenges so this line of code here this while loop does what i've just explained and once we have our heads at the correct position then i'm going to grab a node pointer to the new head here so i'm checking first if the next node after attempt has a value that is equal to this parameter then i want to skip that note by saying temp.next temp.next temp.next is equal to temp dot next that next otherwise if either of this evaluates to false then i want to advance through my list node by node to keep verifying once this while loop terminates because temp becomes null then i can simply return the heads so that's it for the logic here i'm now going to run this code we've passed the sample test cases so now i'm going to submit this code and i believe we should be able to pass all the test cases so in terms of speed we did alright and for memory usage as well so that's it guys for this icon challenge if you like my solution please subscribe to my channel and i'll catch you next time
Remove Linked List Elements
remove-linked-list-elements
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example 2:** **Input:** head = \[\], val = 1 **Output:** \[\] **Example 3:** **Input:** head = \[7,7,7,7\], val = 7 **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 104]`. * `1 <= Node.val <= 50` * `0 <= val <= 50`
null
Linked List,Recursion
Easy
27,237,2216
941
foreign it's a very simple question but as usual let's start with the reading the question trying to understand it with an example and developing algorithm later obviously let's get really good and code that as a garden so let's get started by reading the question so given an array of integers ARR return true if and only if it is a valid Mountain array so what does it mean it means that we are given an array if it is a mountain array we have to return true else we have to return false pretty simple right but you may ask me so what is a mountain array you didn't even tell me what a mountain area is but you wanted you want me to check that whether it's a modern area or not it's a valid question and that is what they are given here so recall that ARR is a mountain array if and only if there are basically two conditions the first condition being the length of the array should be greater than or equal to 3. pretty simple easy to check as well okay first condition easily satisfied what's the second condition so there exists some IE with 0 less than I less than array dot length minus 1. so that is some index between 0 and the last index so there is an index in between the first index and the last index okay and specifically it's not less than or equal to and greater than or equal to it is less than and greater than which means I cannot be 0 and I cannot be array dot length minus 1. so I must be a number in between these two numbers it cannot be other extremes we'll see why is that okay but still just know that this is what is given in the question okay such that array of 0 is less than array of 1 is less than I of 2 until array of I so what does it mean until I the value of the array numbers should be strictly increasing so the first number should be greater than this no the previous number second number should be greater than the first number third number should be greater than the second number and eighth number should be greater than I minus one remember so starting from 0 until I all the numbers should be strictly increasing it should be in the increasing order and from I until the last element which is array dot length minus 1 the element should be in the decreasing order so array of I is greater than array of I plus 1 and area 5 plus 1 is greater than RFI plus 10 similarly until the last element so this is the tricky part and this is what we have to find okay so let's first simplify this try to visualize this as a mounted and then get back okay so let's get started so here we have uh character and a mountain associated so let's first climb this mountain and check whether this is a mountain array or not okay so first as he can it climbs to the you know top of the mountain which means this is the value of I that we have this I satisfies the condition that is given here so it starts from the lowest point and reaches the peak and it did not decrease it's straightly or strictly increasing it did not go like it dips down and then comes up it's not like that it's straight and it's strictly increase and similarly from here to the bottom it's strictly decreasing okay it did not come down and then go up again come down it's not like that it's irregular and it's smooth so it's strictly decreasing so if it's strictly increasing reaches a point I and then it's strictly decreasing you get a triangular shape right if you get that triangle it means it is a mountain array okay and since it approximately resembles the triangle and it does not decrease and then increase okay so this is a mountain array but let's take this example in this case you have a mountain you can climb to the top so this would be the value of I because this is the peak an element starts to decrease from here right but as you can see here it decreases and again increases so this does not satisfy this condition sorry this condition of after finding I elements should decrease right array of I should be greater than array of I plus 1 that condition is not being satisfied yet so that is why this mountain is not a mountain array okay so with that let's get to an example so okay this is easy to find if you give me a mountain I can visually see this and check but how do I make a computer find whether there is a mountain array or not so that is our next question so let's make an array like this okay so this is the exact uh you know image that is given in lead code let us first try to understand this and then let's take our own example as well okay so 0 2 3 4 5 here as you can see here 0 is less than 2 is less than 3 is less than 4 is less than 5. and when you reach 5 is not less than 2 so this is the point which is I you have reached the peak of the mounted and from this peak it should strictly decrease so 5 is less than sorry 5 is greater than 2 0 than 1 is greater than zero so this is strictly decreasing this is strictly increasing okay so this forms a triangle as you can see here this is a triangle and hence this is a mountain array but in case if you take this example 0 is less than 2 is less than 3 is not less than 3 it's equal to 3 right so 3 is the peak point we'll assume that 3 is our value of I okay now we'll check whether uh the elements to the right of I is less than the value of 3 okay so 3 is not greater than 3 it fails here itself but again 3 is not greater than 5 and 5 again here it is decreasing 5 is greater than 2 is greater than 1 is greater than two but here there is a ah you know a flat surface and then it increases and then it decreases so it is not strictly increase it does not form a triangle it rather forms uh where trapezium or somewhat right so it's not ah exact shape that you want which is a triangle and hence this is not a mountain array okay it is not strictly increasing but it's strictly decreasing okay and hence this is not a mountain array so how do we find this and how did we find this let's take an example like this here what did we do we found the value of I by checking whether until which point or which number is the values are increasing we stop the loop when we find the value which is starts to Decay the element starts to decrease from that number for example in this example the element starts to decrease at this point and in this number the element starts to decrease at this point the five value five right and similarly in this point as you can see here 1 is less than 2 okay 2 is less than 1 that is false right so the element stops to increase at this point so this is the value of I and what you have to check after the value of I the element should decrease to 0 and it's strictly decreasing so two to one it's decreasing but 1 to 4 is increasing again and hence this is wrong so as this is incorrect we'll say that this is not a mountain array but I'll show you by visualizing this that this is not a mountain array so here you can see a graph it starts from 0 and then we have 1 2 1 4 and then zero okay so this is the exact values that are being repeated in this graph so as you can see here we are increasing decreasing as when we should strictly decrease to zero but again we are increasing and hence this is not a mountain graph okay so for this we are going to code resolution in lead code so what we are going to do is we are going to say that we are going to find the value of I this peak point from which it starts decreasing so we are going to find the point until which it is strictly increasing and the point which is where the element starts to decrease that will be our I okay after finding the value of IE we'll check whether the elements from I until the last element is strictly decreasing if it is not like this example we'll say it is not a uh strictly decreasing array okay that means it is not a mountain array but in case if it were decreasing until the last element then we say that it is a mountain array so let's get to lead code let me start with the first case as we saw is if the array dot length is Less Than 3 okay in that case it was strictly given a mountain array should always be of length greater than or equal to 3 so if it was less than 3 then it always means that it is not a mountain area and hence we are returning false that is the first base case it's a very you know simple Edge case that we are given it directly to us in the question itself so what's the next part an X part is to declare the value of I equal to zero so initially we are assuming the peak to be 0 and then we are going to Traverse this array until we find the value of peak okay so while we're gonna Traverse until I is less than r a at length minus 1 okay and not just that the other condition that we have to check is array of I should be less than array of I plus 1 so what does this mean this means the elements that strictly increasing okay so this condition checks for out of boundary it should not exceed the array of length minus 1 and it should also be increasing so this condition checks whether the elements are in the increasing order so both the conditions are satisfied sorry so if both the conditions are satisfied in that case we increment the value of I and more than the next point and check the same condition okay and after the end of this Loop what do we get we'll get the value of the peak point right so with that Peak point you would have to continue and check whether it is strictly decreasing order okay so we have found this part of the triangle f is if this is a triangle we have found the value of I this is the tip of the triangle after that we have to check whether this decreases to the least value okay so that is what we are going to check next but before that we are given specifically in the question as you can see here the value of IE should be between 0 and array dot length minus 1 and as I saw as I said earlier I cannot be 0 and I cannot be array dot length minus 1. so with that in our minds after finding the value of I that is our Peak value we have to say that if I is equal to 0 R if I is equal to r a DOT length minus 1. in to equal to r a DOT length minus 1. in that case we again return that are array is not a mountain array so why is that because if I is equal to 0 it means that I is the peak value or the maximum value peak of the mountain if the starting element is the B cross amount then what does it mean the mountain looks like this so it doesn't have an increase in path it certainly starts from decreasing and goes until the least value so for example 54321 if this is an array that would be represented by this graph right but this is not a mountain area as we know we have to have it increasing part and then the decreasing part so since this part is missing we say this is not a mountain array so that is the condition for I equal to 0 so similarly if I is equal to your higher dot length minus 1 it means it is strictly increasing so I is this point which is the largest element which is like one two three four five so this is the array in that case 5 would be the largest terminal it is strictly increasing so we have reached five but there is no decreasing part so since this part is missing we say that this is not a mountain array and return false if both of these cases didn't occur it means we have an increasing path and a decreasing part but it might increase here making it not a mountain area so you would have to check that so we are going to check whether the remaining part is strictly decreasing for that again I should be less than r a DOT length minus 1 we should not go beyond our limit beyond our bounds and the other condition that we are going to check is that array of I should be decreasing right so greater than array of I plus 1 exactly the opposite of the award okay in that case again we increment the value of I and check again so one two three four five and then if you have at 5 4 3 2 1 so that would be checked by this part okay so first part if the length is less than three return false this part is to find the maximum element of the peak element where it is strictly increasing okay so this will find that part and if that part is 0 or length minus 1 that is if it's in this way without decreasing but or if it's in this way without an increasing part we return false here we check that whether it is strictly decreasing after this increasing path if that is true then we can return true right but how do we check that we have reached the end of the array so we are having this array and this Loop will run until the elements are decreasing right so for example this Loop the value of I here is 2 it starts to run so it goes until here and the condition fails here because it starts to increase here right so the condition is failed here now the I value is 3 so if the IE value is equal to array Dot length minus 1 then it means that it's a mountain array we have reached till the end so here if we are reach till the end so if it starts from 2 and goes until 0 here then it means it is strictly decreasing and we can return true right but our I value stopped here which means there is an increasing part here and we didn't reach the end so it means this is not a mountain array so in that case we didn't RI value is not equal to r dot length minus 1 in that case we return false okay so this path can be simplified further by just returning this okay so if the I value is equal to another 10 minus 1 it means we have reached the end and it is strictly decreasing which means we can return true if it is not we return false so this would be our solution to this valid mounted and a question okay so I hope you enjoy this video before that let me first run this and verify whether do we have any errors in syntax this is where we run these stuff okay let's end this again and check for any errors that we have so it got accepted now let's submit the code and verify for all the other test cases that we have here congratulations we have submitted this and got accepted so this is a valid Mountain Area question so let's get started with the next question in the next episode until then bye from Shiva
Valid Mountain Array
sort-array-by-parity
Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_. Recall that arr is a mountain array if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` **Example 1:** **Input:** arr = \[2,1\] **Output:** false **Example 2:** **Input:** arr = \[3,5,5\] **Output:** false **Example 3:** **Input:** arr = \[0,3,2,1\] **Output:** true **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 104`
null
Array,Two Pointers,Sorting
Easy
2283,2327
322
hi fellow golfers today we're going to have a look at the coin change problem let's have a look at the description so you are given an integer array coins representing coins of different denomination and an integer amount representing a total amount of money return the fewest number of coins that you need to make up that amount if that amount of money cannot be made up by any combination of the coins return minus one you may assume that you have an infinite number of each kind of coin okay so let's have a look on how we can solve this problem there are actually two ways of doing dynamic programming there's the top-down approach where we there's the top-down approach where we there's the top-down approach where we start from the global problem and then break it down into sub problems in order to find the solution of our global problem then we have the opposite way which is the bottom-up approach the bottom-up approach the bottom-up approach where we start solving the sub-problems where we start solving the sub-problems where we start solving the sub-problems and then we build up on those solutions to solve the bigger problem the global problem so in this video we're going to have a look at both so let's start with the top-down so let's start with the top-down so let's start with the top-down approach which is the more intuitive approach for solving the coin change problem in order to understand the top-down in order to understand the top-down in order to understand the top-down approach let's take an example let's say we have an amount of four and we have the coin denominations one two and three so what we are going to do is to build a decision tree based on the current denominations and the current amount so the amount initially is four so let's say we're going to take a coin of one then the amount is going to be three if we take again at this point a coin of one then the amount is going to be two again if we use the coin one the amount is going to be one and finally if we again use the coin one the amount is going to be zero so how many coins do i need remember that we want to return the fewest number of coins needed to make up a certain amount how many coins do we need in order to make zero we don't need any coin to make zero so here we're going to return zero so we're back to amount one and we have um other coins denomination right so we what if we use a kind of two and in that case the remainder is going to be minus one so it's not possible to make up an amount of minus one so we just ignore this result ignore this branch and same for the coins tree if we have an ml of one it's going to lead to -2 so it's not possible so we're lead to -2 so it's not possible so we're lead to -2 so it's not possible so we're going to ignore those branches so let me remove them for clarity let's have a look at the result here what does it mean it means that when we have an amount of one it takes one coin to reach an amount of zero plus the number of coins that we need to make up to zero so it's zero plus one so it means the fewest number of coin to make up to one is one so we're going to return that value here to the color in our tree so we're back we're here at two and we want to try with a coin of two so then the amount is going to be zero and we know that in order to make up zero we need zero coin so we're going to return zero here so if i use one coin of two then i use one coin of two here and plus the number of coin it takes to amount to zero so it's zero plus one which is one on the other hand if i use one coin of one then i use one coin of one plus the number of coins that we need to amount to one which is one as computed previously so it's one plus one and here since we're interested in the minimum number of coins we're going to return the minimum of those two values so the minimum between two and one is obviously one so we're going to return one here to the color so for three we're going to go again with the coin two so in that case our remainder is going to be one so let's have a look at one here we can notice that we have already computed the result for one i'm not going to recompute it would be exactly the same right so i'm just going to return one here it's the same result so now let's uh take the branch for three so three minus three is zero so it means that we are going to have a zero amount how many coins do we need to amount up to zero we said it was zero okay in order to make up the amount three and in one coin of three so that's one kind of three plus the number of coins to amount to zero which is zero so i need zero plus one coins uh now let's look at the branch two how many coins do i need one coin of two the one i just used here plus the amount of coin that i need to make amount one so it's going to be one plus one two and again for a branch with one we're going to need one coin of one plus the number of coins that we need to amount to two which is one so it's two here and one here the minimum of those values of the three values is one so we're going to return one here and in a similar way we're going to do this down that subtree so here the amount would be two again we have already computed the result for two so i'm not going to compute it again i'm just going to return and the result for two was one here we are going down the branch for coins three and the amount the remaining amount would be four minus three one and again we know we have already computed it for one so for one the result is one so we just return one here one coin of three is going to be one plus the amount needed for an amount one so it's going to be two same one coin of two plus the amount required to amount to two so it's going to be two as well and finally if we use one it's going to be one coin of one plus the amount required to amount to three which is one so we're gonna have the minimum of those values the minimum of two and two is two so here we return two so it means that we need two coins to make up the amount four so before moving forward i want you to notice that we are computing the same sub problems um over and over again like for instance two is there so in dynamic programming what we want to do is we want to cache those results in order to reuse the result directly and not go down the tree again because it's uh it's exponential complexity to go down this kind of decision tree so it improves the computation the time complexity a lot so what about the time complexity for that algorithm if you if we don't use any kind of memorization or caching then the time complexity will be exponential if we are using a cache a hashmap for instance then this complexity is going to be reduced to if we if c is our number of coins and n is the amount so the time complexity is going to be reduced to c times n what about the space complexity for this algorithm so the space complexity is going to be o of n because we're going to store in our map a value for each amount now let's have a look on how we can code the solution so let's code the solution using the top-down approach we're going to use top-down approach we're going to use top-down approach we're going to use recursion so i'm going to create an inner function called dfs because it's going to be a depth of touch as we have seen in our decision tree we are doing a depth first search traversal so let's create a function for this and we know that what we want to know is the remaining amount of coins the remaining amount that we need to make up with the current that we have so that's going to be our parameter here and the return value is going to be the fewest number of coin that we need to make up to that amount okay so in go you need to if you are going to use an inner function you need to declare it so that you can actually reference it later so we know that the result so the minimum number of coins let's call it min is going to be the result of that function okay so initially we're just calling it with amount so what are our base conditions for the recursion we know that if the remaining number the remaining amount is zero we're going to need zero coin to make up that amount so return to zero if the remaining amount is negative we say that it was not possible so here we're going to use a max in 32 as in let's say infinity or impossible value because again as we have seen in our example we're going to compute the minimum of some values so just to make sure um to pick the minimum value we're starting with setting the let's say impossibility with the maximum so that it's not going to be selected over anything else so now we're going to compute uh we're going to go over all the coins that we have available to us so let's wrench over let's iterate over the coins that we have so we've also seen in the example that the coins that are greater than the remainder are yielding negative results right so if the coin value is greater than the remaining amount then we just want to ignore that so we're just going to continue so now that we have excluded those coins we can compute the value for the valid coins denominations so we know that when we are using a coin denomination it means the number of current that we use is going to be one plus the remaining after we have subtracted the value of the coin so it's going to be remain minus c that's what we want to return to the caller but remember that we are going to test several current denominations so we need to store i mean we need to compute that minimum and store it in into a variable so let's call it number of coins let's initialize it again with let's assume that it's not possible initially the number of coins is going to be the minimum between itself or one plus the result for the subproblem which is the remainder minus the value on the coins and we want to return the number of coins once we're done with our loop one last thing we need to check is that if the number of coins so let's say we have coin denominations that are not working out let's say we have an amount of three and our coins are like five ten and eleven so we can't make up that amount so it's possible for our amount of coins to be uh still that impossible value max in 32 so we're just going to return -1 in that so we're just going to return -1 in that so we're just going to return -1 in that case as we're just going to return the number of coins so let's test that code it looks like it's working let's submit it all right so as you can see we got a ideally time limit exceeded that's because we are not using any kind of memorization in our code right now as i mentioned before the time complexity for that code is exponential so this is normal that we time out on it code now let's add a memorization table so let's call it memo as we have mentioned before we're going to cache the results for each possible amount we're going to have a table which size is going to be amount plus one because we want to include amount itself in that case we're going to actually we're going to use pointers here because we want to know if the value in the table has been initialized or not has been computed or not so we can do that with a pointer so if a memo of the remaining amount is not nil we can return that value now we need also to populate our memo table so here we're just going to populate it with the result like this so let's test that code oh yeah we need the indirections for the pointers so here we need to take the address okay so let's test this again all right so here we see that we have the same results okay it's still working let's try to submit this code all right so now the solution is accepted it's pretty efficient so now let's have a look on how we can solve this problem using top-down dynamic programming top-down dynamic programming top-down dynamic programming so let's take the same example as before so we have an amount of four and the current denomination one two and three so we're going to use a 2d table to store the results of the sub problems the dimension are going to be the amount times the number of coins denomination so n times c so we already know that the space complexity is going to be o of n times c so let's draw that table so we have 0 1 2 3 4 which is the amount and then we have let's say the empty set one two and three which are the coins if we don't have any coin so the first row we don't have any coins so it's not possible for us to make up an amount of one or two or three or four this x returns it means it's impossible basically now if we have an amount of zero to make we don't need any coins for that so we're just going to return zero for every current denomination if we want to make up an amount of zero we just return zero coins so that's the initial setup for our db table and now we're going to fill this table row by row so let's start with the first row if i have an amount of one and a coin denomination of one how many coins do i need one coin uh if i have an amount of two and the coin of one what is the fewest number of coin that i need to make up that amount is going to be two coins or we can write it differently is going to be so if i use a coin of 1 then it means the remainder the remaining value is going to be 2 minus 1 now it's going to be 1. so it's going to be 1 plus how many coins do i need to make up the amount of one which is one so one plus one is two so this value here is two same principle here if i have an amount of three and i use a coin of one so let's say i use one coin so three minus one is going to be two and how many coins do i need to make up the amount two is two so i'm going to add one plus two and our result is going to be three here in the same way if i want to make an amount of four i'm just going to use one coin and four minus one is three how many coins do i need for three and it's three coins so one plus three is four so now let's fill the second row as you can see it's not possible to fill this value because the amount is one and the coin we have is two so one minus two is negative so we can't return the value so what it means is that the only way we can return some coins for this amount of one is using the previous current elimination which is one and how many coins enemy how many coins did we need for that we need one coin so we can't do any better so we're just going to copy the result in that position so now have a coin an amount of two and a coin of two so how many coins do i need to make up to that amount so if i use a coin of two then let's say one i'm going to have 2 minus 2 meaning 0. so how many coins do i need to make up an amount of 0 i need 0 coins so it's going to be 1 plus 0 here so one plus zero is one then again the amount is three and i have a coin of two so three minus two is one so i use one coin of two and then i look at the amount required for one it's one so one plus one is two so i just write two there in the same way four minus coin two is two so i use 1 coin of 2 and i look at the number of coins that i need for a value of 2 which is 1 so i do 1 plus 1 and then it's 2. again for the coin of three as mentioned before we're not going to be able to do any better so we're going to reuse our results from the previous row which means that the coin one and two so we're going to it's going to be one here now we have a value of three and we have an amount of three and we have a coin of three so three minus three is zero so one coin is three plus how many coins do i need zero so one plus zero is one again for four minus three is one so i'm gonna use one coin of three here and i'm going to add it to the number of coins needed for one which is one so one plus one is two so here our value is going to be two and our final result is going to be in the bottom right cell and for this problem is going to be two what is the time complexity for this solution we just basically need to populate the table so it's going to be if we say we have c denominations and n as the amount is going to be c times n and for the space complexity it's exactly the same because those are the dimension of the table itself so now let's have a look on how we can code this solution okay so now let's see how we can code the bottom up dynamic programming approach so as we have mentioned before we're going to use a table it's also called like tabular dp so let's call it that's called the table dp so we know it's going to have two dimensions as we have seen in our example so the first dimension is going to be the coin denominations doesn't matter which one you pick you just need to stick to one and that's it and so we are going to initialize all the rows now so we're going to range over gp dpf i is going to be a slice of hint of land amount plus one so okay we have our table initialized now we need to set the default value for the table so as we have mentioned again in the example we want the first row to be populated with the impossible values because it represents the empty set so what it means is like we're gonna start at one because zero is always returning 0. we're going to start at 1 we're going to be less or equal than amount and we're going to initialize those values so the row 0 and i is going to be the impossible value which is max in 32 okay so now let's start populating the table if you remember the example we don't want to start at the zeros column at the first column we start at the second column so c is going to be one c less or equal than the number of coins denomination so c plus and then same for the amount we're gonna let's say call it a we start at one a less or equal to amount a plus and we know that there we have some conditions to fill that table so first we want the amount to be greater than the current denomination in order to be able to fill that column or if it's not the case we're gonna have to copy the value from above so remember in our example when we're introducing a coin that is greater than the current amount it means that we can't use that coin because it's too big so what we are going the only choice that we have is to revert to the previous um row in the table and use that amount because the current denomination is not possible to use right so now let's have a look at the case where the coin is greater or equal to the amount so it means we are able to use that coin so what do we want here so if we are using that coin we want to so add one so one is the represent the fact that we are using that coin plus the result for um the amount when we have subtracted the coin value so current c minus one and we want to have the minimum number of coins so the it is possible that this combination that we're trying is actually greater than the combination we already have we're going to compare the value between the one that we have already computed which is c minus one and the current amount or the one where we are actually using that kind and we want the minimum of those two values so it's going to be something like this now finally we need to check the results so the result as mentioned before is going to be in the bottom right cell of our table so if that value is equal to the impossibility we're just going to return -1 as we're just going to return -1 as we're just going to return -1 as we're just going to return the value so let's have a look at this code let's test it let me fix this real quick all right so it looks like it's working and yeah so as you can see it's a pretty efficient solution as well it's accepted so i hope that you have enjoyed that video and i'll see you next time bye
Coin Change
coin-change
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`. You may assume that you have an infinite number of each kind of coin. **Example 1:** **Input:** coins = \[1,2,5\], amount = 11 **Output:** 3 **Explanation:** 11 = 5 + 5 + 1 **Example 2:** **Input:** coins = \[2\], amount = 3 **Output:** -1 **Example 3:** **Input:** coins = \[1\], amount = 0 **Output:** 0 **Constraints:** * `1 <= coins.length <= 12` * `1 <= coins[i] <= 231 - 1` * `0 <= amount <= 104`
null
Array,Dynamic Programming,Breadth-First Search
Medium
1025,1393,2345
380
Hello hello guys welcome back to back design this video will see problem where required design and data structure which will be doing should delete and at random in one everest time solar system digit code 12:00 challenge so let's no problem no 12:00 challenge so let's no problem no 12:00 challenge so let's no problem yes-yes veerwal Operations in every problem yes-yes veerwal Operations in every problem yes-yes veerwal Operations in every time you will remove value will remove the elements from the return from the current president of probability of doing so they are required to implement subscribe Operations in every time you need to elementary remove in the grind them know your digestive designer data structure date performs All the missions in Vwe Everest Time 100 latest example for this is and example not let you want to 59059 know you want to know what you want to remove knowledge you want to remove to go to is not present in this can be removed from the Subscribe to element now to you will not give them from this two elements only one will be id the pick up the phone statement no letter c very simple idea in order to implement all other operations so what comes to your mind will be the first data structures in Plus 2 And Vector This Is Nothing But The Are So How Can We Press Latest Subscribe To 2000 Green Beans Elements Who Want To Remove This Element You Can See That Will Come Starting From The Best All Elements Which Element In Order To Provide Only End Values After this element id two elements the same time will be taken northern railways train time from this point of elements you can just use and function to generate the element use this youth result complete from reduce when you can simply go to the first and research and development Will generate random numbers which will be nothing but two size - 110th subscribe The Channel and subscribe the 100% 999 9999 Robbers Quarter of End Time because you need each and every element to be completed with element to remove the great random will generate random element In order to just say 1000 times but in the removal of so let's not alternative approaches and alternative which you think that we can do subscribe latest tax liability set 2002 and second idly you want to be implemented please subscribe that it will take long and tank Printer Everest Time You Must Give Me To Beethoven Burdened with the latest information in this will take some time will be no the removal of elements from time to time set the function generator value or elements are not wanted to read the content you will have to the The Alexis Not Possible In 600 This Great Grandmother Bottle Net So What Is The Structure Which They Can Apply Can Also Check The List Play List Latest 102 And Widening And Want To Remove This We Will Have To The And Start With This app you will be able to remove this will take you can see hidden in one time and remove and generate random element from other ranges from this subscribe value one I have given your setting from this head and you are searching phone will have to go Elements in the best and will not possible for problem remove with me problem solve ever problem Delhi and removal in every way I want to basically access the element in Amazon you can access the solution for this problem solve want to solve this data Structures Which Used To Go With A Plus B Plus Subscribe My Channel Like This Thank You Will Understand What Is The Difference Between And Subscribe To Ek Dum Episode Actually Anti So They Can Just Introduce Elementary And This Will Be At Index Phone No Will Have To Also Update And Map For The Values ​​Relented And Update And Map For The Values ​​Relented And Update And Map For The Values ​​Relented And Values ​​09 2009 Presentation Ki 93009 Dahej Subscribe Ki Thi Is Already Will Not Be Able To Give No Veer Is Not Present In The Way To Subscribe Thank You No Interruption Jhal 9 We Want To Remove The 024 Removing Vishuddha First Verify Weather It's Present In The Fennel Battery Saver Check Them App So They Can See But Its President Subscribe Person Is Presents Subscribe Indexes One Can Simply Go To The Sentence From This And Want To Remove Person Remove This Element From The Way Will Help you all elements from this will again be what we can replace this element with the last 10 years so they will remove that you can see the element switch time to like or delete this elements what will remove this from or map ok thank you can Also directly this element we present at index two but now its exchange also need to change a 100 index to 9 2012 What he did not think they are only to the value generated with the latest end values ​​and use this and its value will remove all Present in the present some will have to in software Android 2.2 and will certainly does not decided to give Android 2.2 and will certainly does not decided to give Android 2.2 and will certainly does not decided to give me to remove want to remove will see what Is this what is this what will be the subscribe to subscribe and subscribe apne updated in and map chotu quotes best wishes to early years now it's n x is equal to one so will have to change its n text-21 ok no and next very great You text-21 ok no and next very great You text-21 ok no and next very great You Have Read And Only Two Elements Letter Se Random Number Generator 2009 This Is The Way Can Involve Waste Oil Do n't Forget To Subscribe To My Channel Check The Element Already Present In The President Will Not Been And Will Not Be Present In The We will have to insert in and 810 line insult the element and the lethally updating or map with the new President rule operation Operation We will give the present in the President will use this It will be the first President will be present in the picture And will be replaced with the that the they will update the entry after last but not least iscon it's ok so that index needs to be updated soon after updating it will remove the country for which remove function was called under-15 return true knowledge And Information under-15 return true knowledge And Information under-15 return true knowledge And Information Will User And Function To Get Rich And Mode Of Witch Will Generate Random Number 102 Size - Sid And Its Just Want To Understand Its Implementation Of Solution In Different Languages ​​So Please Like Languages ​​So Please Like Languages ​​So Please Like Share This Video And Subscribe Our Channel Like This Video
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
6
Do it Hello friends welcome to another episode of I am from Indian company Vestige Paper Should give this question on a Saiyan Fagua II level problem Entries Question No. 60 451 A friend singh like this place is having four wheel and beside such a want To give a number of what you want to divided into several different types of subscribe now to receive new updates reviews and character and the number of subscriptions who is the first month ago P's growth is controlled by positive thoughts and Selzman sewerage's number of forestry loot decrement population would end up in the city next character or spicy position in the recruitment against wasted a role number one in the wake up in the next day boy so I edited continues to and most important is requested to enter In the days you need to remove puran long dhoi tractor appearing in a single example in this is the number one day aur test se peechee achhi tyohar mein nahi sokhiti nahi to try vastra 0151 end up and its true character of adverbs pages rock candy crush example Number 210 Tricks Page Number 90 Degree The Giver Number One Hai Saunf Another BJP 10th Decrement Benefit And Character Under The Victim Enter Character Hai Dhundh Laptop Printer Input Continue Till The Time I Have A Suitable Boy For Registration And His Dress In The Quarter Final Or men will be lit use tombstone before in this particular Chinese value decorative width juice squat with which you want to particular thing to take place basically two types of that one is the chief manager set soe give way to please subscribe thank you a Political affiliation and key want to take medicine at character .au position medicine at character .au position medicine at character .au position person the what and what drives away extract using dot s later at the junction of things cold drink builder going to use in this particular question 500 or coffee exports question And I Will Explain * Havya Proceedings And What Explain * Havya Proceedings And What Explain * Havya Proceedings And What Is Requested Surya * First Is Requested Surya * First Is Requested Surya * First Tractor Problem Into Several Parts Point Is That We Have To Take Off But Number Of Baroda Smile Vijaypal Singh Ashok Binttu Let's Move Veer Is Pain Position Feet Web Series Final Number Of Rodent Specific Questions Page of Life But I Love You Select Support This Question On The 100th Post Into A Baby In The Singer Hai Smart Hai A Mistake Sune To Thanks For BJP In Teacher Tiger Hindi Adb Screen Ulta Hai The Vinay Mein Tiles Map Hua Hai To bank will be beaten absolutely position witch reduced or indicated phulchand hence first individual character juta particular question tamil explain video sheet for using after being in the world should implement i n c r n initial secretary pro a love but in 12th part sorry sentence rent pad will give Winners in this question is pencil shedding the water bills urination available havoc see in one fell swoop time and will convert string into character superintendent and that firmly defined panchami point to which are in tamil guessing that boat Dinesh Singh Babbu find out his reaction position of air force Variable and Qualities Which Define Position Number of Given to Check Once Question is Equal to Name Manoj is E Want You Don't Sick Alarm Set Increment to Position Since E Two Not Want of Three Finals Dry Jobs for Students Saturday Increment is Vegetable Sports But from 2210 per position in were first position a baby in cement 120th site agreement benefits that north and thank you to sp ne to check of instruments true but in its doob increment ubuntu increment mla only duets of improvement edit question school and st louis Pacific like this and implement and you know specific want you to 8 minutes be considering that the implement this true a vivid entertainment value of p was for that all your day cream and images of coming that not think tank does mean that took place At Check FIR Hai Smart Already Hours Already Contents Till That POS Side Effects Not Contain Value At Particular That Yes Insider Android Phone Will Only Next Character Inside The Position The Walking Dead Play Se Half Inch A Fan App Download Contents Jai Hind Yes Injuries Safe Map Did Not Contain The Value Of Yourself Sets Key Limit Rather Simply Put Back Particular Questions Were Insider Says The Person Pintu Thanks Record Hai Smart Beach Tooth Isse Zabani The Flash Light That Newly Formed Presentation For Adults Not Contain Know What They Need To Quit Container Onion patients' january 2nd test at your Onion patients' january 2nd test at your Onion patients' january 2nd test at your service that and up in the person a serious b character item particular position inside your trident who with this page like this has the output of giving admission date for kids acquisition deals and yet result a wicket spring field with Name Result Jari Hai A Yes Bhai Naveen Dhatura Nilu Hai 11 Class All Decline That Indian Skin Shine Like A R Rahman Ka Ki Animals Media Chaiye Na The Index Position Who Deals In Place Of To A Friend At First To Press Diet Wicket The Opposition A Friend Vanshi to write readers to return result birthday result intermediate 2nd test day three to strings hai so use hai a ruk 102 the highest bliss at last the come back waters running kar do hai yeh dil se rokta admission play game hua hai ki a meeting adversaries Ajay was the most selling his strong contender that the Naxal camp is at this time there is a vacancy of tax return its name Singh meeting will be put on Thursday this rumor time tax is to be calculated that a court in a valley settings of time that why not a Din Explanation Question Hai Birbal Bhi Posting More Content Song Please Like Share And Subscribe Our Channel And Comment It Brian Adams Thank You For Watching My Video
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
384
ok let's do this together yeah 1 384 shuffling away chipping away number of numbers of about duplicates and then there's just some usage ok so I mean this is kind of silly now I'll explain what I would do later so let's just say or what you know and then this like a random Dutch shuffle I think I put it in the wrong place I can stand put doesn't have to be sorted or wouldn't matter either way so you have someone like okay let's just say we so you know and then we turn these out now talk about how to do this without cheating what does this mean me I don't even do anything in here cuz I just copy everything that's the reset give you our reset returns - okay fine I thought that this returns - okay fine I thought that this returns - okay fine I thought that this is just a void function but yeah I mean it's just random right so I mean using a library function I feel like if I swung then it would just be a sad day cool though it could be fasting apparently but yeah I mean okay let's talk about this farm a little bit and maybe future MBLAQ to be like what why did you do it this way easy and you're probably so yeah so I mean I just used the live way so it is not for an interview I mean I would say for an interview you're probably not gonna get this I want to say in the sense that so the stand up stand album - because - to the stand up stand album - because - to the stand up stand album - because - to learn about shuffling or permutation or yeah like a random permutation is called our fishery Yates would you know especially its album so I mean that's the same way is that like I don't that is why I don't feel bad about doing this with the library that is in Python is because like well just if you get this on interview it becomes can I use a library no well do you happen to know the Fisher Yeats album well that's like the entire interview group forum right so that's kind of unfortunate in the sense that like well if you know this problem or if you know the album then you can sell but if you don't and you can't and that's pretty much you know like and I wouldn't really spend time on learning the algorithm in the sense that like you play if you're studying in the viewing problems or beginning the core problems and so forth like the other things you can do that a better use of your time so because this is quite the only time where would come up that's all I have to say to this one back to a really short yeah I don't know but so don't only thing I would say is that the official yeast and it comes from very simple concept so that so I given I remembered given though you know it's been a long time and it's something that's you know I would like to explain so that you have some idea in the back we mi of course so the one thing that you need to know about suffering and like doing a generating a random permutation in general its data you know a very naive thing to do and I don't know how they check that this is correct and services whatever because of like distribution but already naive but and often implemented and maybe a little bit better nowadays because people can use Google and also this there's a lot of their libraries for it but back in the day there are a lot of times we're like well the way that people would start this problem is well pick a random index and then pick another random index and then swap them way well the problem with that is that let's say you shuffle or you swap anytime so a K times say because n is the length of their way so you'd be shuffle or sorry you swap k times well there's 2 to the K possibilities of this is it will end to the yeah so anyway a so that's the number of permutations that you can get after case shuffles but you know how many permutations there are which is n factorial right and those two numbers will never match up and you can prove to you could feel ready now you've proved to show why in fact always never gonna be - today well yeah be - today well yeah be - today well yeah - to the K for any K except for maybe - to the K for any K except for maybe - to the K for any K except for maybe well two numbers I guess so that's why that doesn't work and that's a very common trap that before and dude I don't know I don't think that shows up when in an interview but the right way to do it which is where easy to remember I don't know it's way easy remember but the way that I remember it yes dad okay you go one away LM at the time start on the beginning or the end I think the canonical way that they describe is you take the last element and then you just take the prefix right which is from one to seven join ask you out this and then you take one when the number swap it with the number eight Oh actually I lie so actually it's inclusive so you take one number from one to eight and then swap it right and then next you do the same thing for seven except for you still only want the prefix so you're only looking at the first seven elements at that time and so forth and you can kind of prove that this distribution work because in the first case in the first iteration well each number can appear in one eighth of the time and then in the second one well you only have seven numbers and the key thing is that you have to swap the eight into whatever it appears even if it's itself so in that case there are seven numbers love each one seven of the time and then so forth dad and then from dad it's easier showed that uh you know you do the product or which is technically called the PI of the Fung these functions which is similar to Sigma but it's just for the product it's just one over N factorial which means each of the N factorial permutations have equal chance and that's what you want from the shuffling yeah and this is relatively easy to implement as well if as long as you remember that point so yeah cool that's all I have for this problem like I said for an interview it really becomes like hey do you know this one algorithm that I know which is in my mind a crappy interview problem excuse me but sometimes you didn't with crappy interview problems so but I would worry about other fun
Shuffle an Array
shuffle-an-array
Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling. Implement the `Solution` class: * `Solution(int[] nums)` Initializes the object with the integer array `nums`. * `int[] reset()` Resets the array to its original configuration and returns it. * `int[] shuffle()` Returns a random shuffling of the array. **Example 1:** **Input** \[ "Solution ", "shuffle ", "reset ", "shuffle "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\]\] **Output** \[null, \[3, 1, 2\], \[1, 2, 3\], \[1, 3, 2\]\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.shuffle(); // Shuffle the array \[1,2,3\] and return its result. // Any permutation of \[1,2,3\] must be equally likely to be returned. // Example: return \[3, 1, 2\] solution.reset(); // Resets the array back to its original configuration \[1,2,3\]. Return \[1, 2, 3\] solution.shuffle(); // Returns the random shuffling of array \[1,2,3\]. Example: return \[1, 3, 2\] **Constraints:** * `1 <= nums.length <= 50` * `-106 <= nums[i] <= 106` * All the elements of `nums` are **unique**. * At most `104` calls **in total** will be made to `reset` and `shuffle`.
The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31)
Array,Math,Randomized
Medium
null
1,685
hey everyone let's all the today's ladco challenge which is sum of absolute differences in a sorted array so here in this problem we are given a list of number arrang in order and for each number in the list we want to find the sum of the absolute differences between that number and the every other number in the list so in for example for this case we have for the first index two we have to find its absolute difference with each of the other element in the array which is 2 35 so let's say for this uh for the first number two the sum is 2 - 2 first number two the sum is 2 - 2 first number two the sum is 2 - 2 modulus 2 - 3 modulus 2 - 5 modulus 2 - 3 modulus 2 - 5 modulus 2 - 3 modulus 2 - 5 modulus which is 4 and so on for three and five okay so how do we do that first approach is like uh checking for all the possibilities or maybe following the same what is mentioned in the problem like checking two with all three elements checking three with all three elements checking five with all three elements so that is going to be n sare which is not a very optimized approach so what else can we do this problem is also in the problem it is also given that uh we it's a integer array which is non decreasing so let's say for this given input if we have to check for three how do we check the absolute difference with it with itself is always zero so three is done so now we have to process from left side and right side and for the right side all the elements are always going to be larger than three so we need to find the difference with each element so what we are going to do is we will calculate the sum of each element and subtract the three from each so which is one element in the right side so we are going to subtract three from it which would be two so from the right from the left side we have to subtract each element from 3 - 2 which is 1 so for three our answer 3 - 2 which is 1 so for three our answer 3 - 2 which is 1 so for three our answer would be 1 + 0 + 2 which is would be 1 + 0 + 2 which is would be 1 + 0 + 2 which is 3 which is also mentioned here for run let's try to have a look on a larger example so you will get more idea 1 4 6 8 and 10 and now we have to check for 6 for six uh if I take if we take the mod with itself it is always going to be Zero from the left side we're going to subtract each element from 6 which is 6 - 4 is 2 6 - 1 is five from the right - 4 is 2 6 - 1 is five from the right - 4 is 2 6 - 1 is five from the right side it is all the elements are greater so we are reducing six from each element 8 - 6 is 2 8- uh 10 - 6 element 8 - 6 is 2 8- uh 10 - 6 element 8 - 6 is 2 8- uh 10 - 6 is so four so this is going to be our answer which is 30 how do we approach this problem what we can do is we can check for the prefix sum firstly we will uh pre-compute the prefix sum and using uh pre-compute the prefix sum and using uh pre-compute the prefix sum and using that if we do the iteration over the array we are able to find like what is the sum of elements on the right side sum of elements on the right left side so let's say in this case if we do the prefix sum 1 4 6 8 10 prefix array would be like 1 5 11 19 29 okay so this is our prefix and let's say if we have to calculate for six what we need is we need sum of all the elements on the left side and we can directly reduce that from the uh the same number of six let's say we have two elements on the left so we will multiply 6 with two and subtract that sum the sum at the left side and for the right side we will check how many numbers are there on the right side which is two so for the sum of all the elements on the right side is like that we can directly calculate which is 29 for whole array and 6 11 till 6 so if we reduce 29 and if we take a difference from 29 and 11 so we are going to get 18 so which is sum of elements on the right side so sum of element on the right side minus 6 into number of element on the right side sum of right side element will always be larger because it is a sorted array so in this way we can calculate the sum of left side and right side let's try to finish the example for six the left side we have two maybe let's say Nal K = to 2 so sum of maybe let's say Nal K = to 2 so sum of maybe let's say Nal K = to 2 so sum of element on the left side is prefix of i- element on the left side is prefix of i- element on the left side is prefix of i- 1 which or maybe prefix of 1 11 - 1 which or maybe prefix of 1 11 - 1 which or maybe prefix of 1 11 - 6 which is 5 should be subtracted from 6 into 2 - 5 would be the left side 2 6 into 2 - 5 would be the left side 2 6 into 2 - 5 would be the left side sum or maybe left side answer for the right side the sum of elements at the right side that we can compute from our prefix array which was 18 minus 6 into number of element on right side which is two which is six so the answer would be 13 which we calculated in our answer which is same so now how like how did we approach this problem we can just calculated the prefix sum array for the given input and iterated over the given input and use that array to solve our answer so in that case we just did some precomputation which is O and time and then so calculated our answer which is o n so 2 N is all also o n so we have now solved this problem in the linear time let's try to code this problem here let's capture the length given array now we will calculate the prefix array for the given input now we will calculate the prefix array values prefix I is equal to prefix i-1 plus nums of i as we are using i-1 plus nums of i as we are using i-1 plus nums of i as we are using prefix IUS one we will start from 1 and for 0 we can directly say that prefix of 0 is equal to nums of zero okay now we have the prefix sum and let's take a answer array new integer of n size and we have to calculate for every integer in the given nums array I equal to 0 I less than I ++ and after to 0 I less than I ++ and after to 0 I less than I ++ and after calculating the answer we are just going to return that now what we have to do is uh we have to take the modulus from each element so modulus to itself is always zero so no need to consider that modulus from all the left elements are smaller than the current element so we will reduce the sum of all the left element from the current element which is nums of I minus nums of I into the number of elements on the left side minus the sum of left element so firstly calculate get the left sum in the current input which is equal to prefix IUS one here what we will do is we will check for I because we don't want to check add an extra condition for I greater than equal to Z greater than zero so prefix of i minus nums of I so this is our sum for all the elements left side so let's say for three this is the uh this is going to be sum of two or maybe for two this is going to be sum of all the elements on the left side prefix 0 minus nums of 0 which is0 int right sum how do we calculate the right sum prefix of all the elements in the array which is at the left last index minus me nums of I okay now we have the left sum and the right sum uh now we have to calculate the number of element on the left side left count maybe in right count of element at the left side r equal to I because I is starting from zero 4 3 I is 1 and number of element on the left side of three is also one for the right side let's say for three how many elements are there on the right side n minus I which is n - i - 1 n is 3 which is n - i - 1 n is 3 which is n - i - 1 n is 3 here so 3 - I is 1 - here so 3 - I is 1 - here so 3 - I is 1 - 1 so N - 1 - 1 so N - 1 - 1 so N - 1 - I okay so left answer now we have to calculate the answer from the left side which would be equal to numi into left count minus left sum because left sum is lesser int right answer is equal to right sum is always greater than minus nums I into right count so now what we can do is we can capture that in our answer is equal to left answer plus right answer okay now let's try to submit the problem over test cases sample test cases is giving me a wrong input let's try to figure out what's the issue so here we calculated our sum right sum wrongly now we have to subtract the total sum minus sum of all the elements at I index which is prefix of I not terms of I now let's submit again submitted okay successfully run on the over the sample test cases now submit to the problem okay submited successfully okay hope you understood the problem thank you guys
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
1,260
hey everyone it is aside hope you are doing good so let's start with the question so the question is shift 2d grade okay so you're given a 2d grid of size m cross n and integer k you need to shift grid k times okay so in one shift operation uh if the element is at grid i j you have to move to grid i j plus one basically you have to move one column ahead uh let's say if your element is at last column basically great i uh sorry last row so n minus one okay they have representing in different manner so let's say this is in the last column then you have to do you have to increase your basically point row pointer by one and your column will be one so let's say if you are at this position so this three will come at this position okay similarly if your element is at the last position m minus one and minus one so if it is this position then it should move to this position okay this is for one operation but let's you have to do it for the k operation okay so what you have given is you have given a grid array and there is a k pointer to it okay so let's see this example so as you can see this is one two three four five six seven eight nine a two d matrix what you have to do we have to move it by one k equal to one okay so as you can see one will move to this position two okay then two will move to this position then this 3 is at 3 can't we go ahead by increasing the matrix size so 3 will come by increasing the row with pointer by 1 and column pointer to 0 so 3 will come at this position so 3 at this position similarly four will move further then five similarly six will go at this position similarly seven similarly eight but for nine now it is at this position at the last so if we go ahead we need to basically you can't go after this again this there is no row after that so you will take it from the start you will commit here okay so let's see another example so this is c8 one this is a matrix and you have to move it by k equal to four okay so if the element is at this position then this three after doing the four operation like you have to do it by four times so this will be one then two then three then four okay so i hope like you can see the three will come to that finally at this position similarly eight come at this position so let's see how we can approach it like basically we don't need to go like to do every iteration we can just increase the pointer like we can just add three at this position we can add k to it and it will take it to this version okay so let's write a code it will be cleared to you by side so let's take row uh grid dot length and let's take the column so here only i will explain how we will write it so now we need to check the constraint also so this is gridline and they are in the range of 50 and you can say this is a k so k also like k is not dependent on n and m so let's do one thing uh let's say if k is greater than our row and column what we will do we will basically take it mode for this so basically row into column so that k range will should be lies in this range only inside our dimension okay now what we need to return our list integer basically we have to take a new array so we will take a new array and we will sell it to drn we will just return that okay so let's take a new error so let's take our answer in row column same size okay what we will do we will basically add every index we will insert it okay so let's take a loop over here row i plus for n j equal to zero j column j plus okay oh i didn't write the for loop so we have created a 2d loop now what we will do we will calculate the basically if this is the initial position we are directly creating this final array so for this what we will do we will calculate the new array position basically new row and press it in new column okay so what we have to do like you have to shift uh the k times basically you have to move the column not you don't have to move your row will only move uh in this case only when you're you are at the end of this position or when you have like at the end of row and column okay so row will always be i and your new column will be j like the current plus k so you have to move it k times okay now we after this what we will do we will just in answer new row new column we will just take grid of i comma j okay so basically what we are doing is we will calculate the new position of this element basically i and j so as you can see nine is come at this position so when you do basically uh neuro of i and j plus k so in this case it will be like uh let's write about then it will be cleared to you so this is the first step like we calculate a new row and new column but we haven't added condition when new column is at greater than our column length okay so we need to update that so if new column is greater than column then you need to do something so what you need to do you basically have to increase your row but how can you say like for the one step it will be clear like call row will move only one but uh so what we will do new row basically uh it will be equal to new like it will be like neuro plus equal to new column divided by column okay so what we have done is let's say at this position zero one two let's say you add one to it so this become three your new column is 3 what you will do you will basically divide it by your column so you will get to know how many position you have to increase your row so let's say if it is k equal to 4 okay so at disposition 0 1 2 you will do 2 plus 4 which is 6 okay so now if it is 6 how can you say that like this will be your current position in that case so this will be 0 1 2 3 4 5 6 this is the current position so if it is 6 so what we are doing is new column is 6 divide by column so column is 3 so that will give us the 2 and new row is at this position 0 so it will do 0 plus 2 it will come at this position okay now we need to add one more condition of neural also so if you say like we are just doing for 3 plus basically we are done for three plus four seven let's say uh it is you have to move it eight times okay so k is eight so zero one plus zero one two plus eight is ten so if we do mode of this so 8 so divided by 3 so 8 divided by 3 will give us only 2. okay so let's take it like this if your new row basically crossing the matrix row and then you also have to do something so if neuro greater than equal to rho you will do just neuro mode equal to basically you will do its uh row it will be only one second so if it like neuro is greater than equal to row so we just lie in this range only so we do more of this so this will come in the range only similarly we have done for this now we will after that we have updated row we have updated our row in the like if row is greater than rows after this if you're you just have to update your new column so this will be like this will be a separate condition so we have created a answer array so after this you just written answer okay so the answer will be in the list format so that is thought list let's pass the answer i think this will be like this so let's cast test okay let's run it okay so there is a mistake so this will be l capital let's run it so as you can see this is accepted so i hope this will be clear to you what we have done is we have calculated a new row we have calculate a new column after this first step we update the new row if neuro like we need to update it to go to the next drawer k times row and if new row is also greater equal to row like it will be crossing the row with index then we again update the new row after that we just update a new column and just inserting into our answer let's submit it so that's it the time complexity is like we are inserting the every element in the like it's the order of row column row into column and similarly we have taken a space but you can say this is a space for giving the output so it's a order of one uh hope you like it thank you for watching my video and do join the telegram group if you have any doubt any concern thank you
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
374
hello everyone welcome back here is vanamsen uh if you're new here we discuss and solve all things uh code if you haven't already don't forget to smash the Subscribe button and ring the notification Bell so you never miss any coding fans so today we are attacking a very interesting problem guest number higher or lower from lead code I have chosen this one because it's really helped us understand the concept of binary search and it's a problem that has been asked in several coding interviews so let's dive straight into the problem we are playing a guessing game where the computer picks a number from 1 to n and we have to guess the number each time we guess the computer tells us if the pick number is higher or lower than our guess now we don't want to guess randomly right we want an efficient strategy and that's where binary search come into play so a binary search is divide and correct algorithm so used to find a specific element in a sorted array but don't worry we are not dealing with RIS here the main Concepts however Remains the Same we try to eliminate half of the remaining possibilities with each guess so uh all right let's get to the fun part coding so today we will be using a python but don't worry if you more comfortable with other languages I have included the equivalent code in Java C plus JavaScript uh c-sharp uh in plus JavaScript uh c-sharp uh in plus JavaScript uh c-sharp uh in the description below so we are defining our guest number function here so we start with the range of possible numbers which is 1 2 and in each iteration of our while loop we calculate the midpoint of our current range and make a guess we then use the response to adjust our range if the guest number is too high we adjust the upper limit to be one less than our guess number if it's too low we adjust the number limit to be one more and if guess is correct we return guest number so now let's implement it uh so left right will be 1 and n and while left less equal right mint will be left plus right minus left divided by two wrong to remainder and result will be guess mid and if rest equals zero return mid point else if rest Less Than Zero right will be mid minus one and else left will be mid Plus 1. so we return -1 if we haven't found so we return -1 if we haven't found so we return -1 if we haven't found anything so let's run our implementation and see if it's working so yeah given uh input n of 10 we pick six so yeah output is six and yes so all is good so our code runs so let's run it for unsynthesis cases as well to verify everything's work so as you can see it's really an interesting way to implement a binary search and yes everything's work and our implementation bit 85 with respect to runtime and also 36 with respect to memory but uh yeah we can see that uh there is no so big difference probably if we run one more time the result will be different so it's uh quite common with this code so yeah so for example now our implementation is uh bit 97 with random and 36 with respect to memory but here we have just 0.1 a megabyte of here we have just 0.1 a megabyte of here we have just 0.1 a megabyte of a difference so not so much uh so remember the actual guess function is predefined API only is good but for our local testing we have a mock function set up so the guest app is already defined for real so param Nam uh your guess and to return minus one if num is higher than the peaked number uh one if num is lower than the peak number otherwise return uh zero so it's def guess so that's why we are using here Dev gas and we are guessing that midpoint so uh and there you have it our binary search strategy has page off and we have guessed the number efficiency and this problem really showcases the power of binary search and how it can dramatically cut down the time complexity from o n so linear to O log n that is common for uh binary searches because we are dividing uh every time by two our search space and narrowing it so I hope you found this video enjoy it and learn from uh this uh something new and remember the more problem you solve the more pattern you will be able to recognize fastly and making it easier to tackle new problems with same pattern you have learned so if you found this video helpful be sure to hit the like button and leave the comment down below if there is a specific problem you would like me to tackle next as always uh keep practicing happy coding and see you next time
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
337
all right let's talk about the house rubber three and then you're given a route and which is a binary tree and then basically you don't want to uh take the value when there are connected so basically that directly in this house which is directly linked with no you cannot uh you cannot rob right so basically you need to just um try to avoid parent and child um traversal so this is parent this and this one's trial you are not allowed to you're not allowed to rob this one this is this connection is parent-child this connection is parent-child this connection is parent-child connection and this is like directly connection so you cannot do like this and also you cannot do at least right left and right child cannot be robbed at the same time so if you want to rob this one you cannot rob your child right but the problem is what if your parent is right here and then this is two child right i mean two children you can grow up like you can grab two children instead of parents so you don't want the raw parent you want to rob the child this is okay because this is not directly connected right this is not you commit from your parent and then you go to the other child right so this is uh this is a law so basically we can just using the recursion solution i for every single node i'm going to draw from my first level so here's it so imagine this is the tree and i'm right here so i'm going to rub this label and all the all labels right so this is all labeled and how about the even another color wait this is all level right and this one is even level so you want to take which one you want to uh which one you want to drop right so this is even and you want to just drop an even level 3 and all level 3 and this is pretty much it right all level all right this is it so you want to find out the maximum between the odd and even right and also the note could be negative right so you want to avoid the negative value as well so basically like this is super easy like you just want to find out which one is your maximum for all we're trying to maximum for eva and then you return the value so you set the vowel to this one and then you return it out so this is the effect so let's stop holding so if the route is actually able to be long i you will return here right and then again now you want to walk right you basically want to rock yourself first and then you want to rub your um the next level right so i'm going to just say here so if root of left is not known right which means you can rock right drop what you can draw the left leg and left right and then if root on left is no you drop you return zero and also on the right pretty much exactly the same thing but root right and this is the entire all level i mean just for example and also in well not raw so i'm going to just say this is oh this is even so i would say rob rudolph plus rob through the right so less of my current maximum value max drop even so i will just return down right again this is uh doable but the problem is what if you have like 10 kilowatt 10 to the fourth note you will get tle right time then x6 so you need to have a highest map as smack i'm putting a key for trino and also the value for integer this is called map and then i'm going to put this one about metaphor follow current route with the bell right into my map and then when i repurchase the clothes i'm going to check have i ever tried to traverse this note or not right so map contents if i do i will just return and let me try to run this case and this is doable and here we go so let's talk about time and space for time uh basically like since you are using a memorization recursion and this is all of them like for every single node you traverse ones and if you want to traverse again you will just return the valve so it's all the fun for the time although i'm full of space for sure you want to traverse every single node to put your tree now into the map so it's open for the time for the space and here's my solution so if you feel helpful subscribe like and leave a comment if you have any questions and i'll see you next time bye
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. **Example 1:** **Input:** root = \[3,2,3,null,3,null,1\] **Output:** 7 **Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. **Example 2:** **Input:** root = \[3,4,5,1,3,null,1\] **Output:** 9 **Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 104`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
198,213
108
hey what's up guys white here I'm detecting coding stuff on twitch and YouTube and I'm back on leak code it's been a while but here I am and we're gonna get back into it now we're gonna start with an easy problem here this is a tree problem I've done most of them but I guess I missed this one it is the last easy one I have to do 108 convert sorted array to binary search tree okay so I'm guessing we're gonna take an array given an array where elements are sorted in ascending order okay so we're given an array and the elements of the array are sorted so for example like this negative two negative three zero five nine sort it alright right we know that so we want to be when we're given that array we want to convert it to a height balanced binary search tree now if we wanted to just convert it to a binary search tree what is a binary search tree it's a tree where each tree node a binary tree because binary is base to the tree node can either have no children it can have one child or it can have two children so you know in this case this node has no children in this case this node has one child which is negative ten and in this case this node has two children negative three and then nine so there we go that's all it meant for this problem a height balanced binary search tree is defined as a binary tree in which the depth of the two sub trees of every node never differ by more than one meaning just that sub tree can be like you know this is a subtree of the negative 3 in 10 the negative 9 and 5 is a subtree the heights of these sub trees they never differ by more than 1 so there's not going to be like this side the right side of the tree isn't gonna go down like three more levels deep than the left side it's only gonna differ by one at most ok so how do we do this how do we take an array and turn it into a tree like do we loop through the array and then do we just make the tree and then it's like okay like how do we negative ten we just make that the root and then we just go left is through negative three and then right is zero you can't do that and you can't do that because one thing you also have to make sure you remember about binary search trees is that these are somewhat sorted as well and how it works is on the left side of the tree our elements less than the root and on the right side our elements greater than the roots so you can see here we have 0 is the root because it's the middle it's basically in the middle of all these elements in the sorted array and what timing is we have 0 and then we have negative 3 because it's less than 0 on the left 9 is greater than 0 and it's on the right and then 5 is on to the right of negative 3 into the right of 0 but it's to the left of 9 so you know what I mean it's just left is 4 so it's kind of sorted you know what I mean the all the way the leftmost elements are gonna be the smallest elements right most are gonna be the greatest elements so that's how it's kind of like you know you could start to put it together a little bit you see you have a sorted array and it's like okay well it's sorted so we know that the smallest element so like how do we set this to the leftmost element though how do we set the greatest to the rightmost like I can't just construct my tree from the left most node do I do like dot parent or like you know that might be like what you're thinking but here's the way to do it in a sorted array I have this in my study guide on my patreon if you want to check it out but it is when you see sorted array I say first thing you should think of is binary search in really that is pretty common like whenever you see sorted array like think binary search it's always gonna be something right at that and if you think about our research the way we can construct this tree easily is we can start at the root because the root is going to be the middle element and then when we make the root to the left it's going to be the middle elements of the left side and when we make the root to the right it's gonna be the middle element of the right side and we can keep constructing this tree using a binary search so I'll just show you a little bit better example I had right here so that it makes a little bit more sense so you could see how let's just code it actually so first thing we're gonna do is we're just gonna say okay we're given this array it's the sort of and we see we have a tree node we have access to the left the right we could set the left the right and the value and there's a constructor so we could pass a value so first thing we'll do is if our sorted arrays length is zero we'll just return null otherwise we'll return on a helper method called construct tree from array you know we could call it that and we'll pass in num step -1 if I could and we'll pass in num step -1 if I could and we'll pass in num step -1 if I could click that ok so this is going to be a helper method that returns a tree node it is also gonna take the sorted array and like a binary search we're gonna kind of do a recursive binary search with this method where we take in a left boundary in a right boundary much like in binary search so we're gonna say into left into right and in this method we're it we're gonna treat we're gonna in recursive methods when you're doing recursion always check the boundaries so we don't want the left to be greater than right so if left is greater than right we'll just return null and then we'll calculate our midpoint like binary search left + right - left / - because search left + right - left / - because search left + right - left / - because this is integer overflow if you just did like right / - or whatever you have to like right / - or whatever you have to like right / - or whatever you have to make sure you do it like this because of energy overflow and then what we're gonna do is we're gonna say okay tree node is equal to new tree node we're gonna build a new tree node of the middle element so we get the middle index of the array and then we make a tree node from it because that's going to be the root that's how we start so the first call we make to this we're getting the middle element of our sorted array which is 0 in this example and we're gonna make that the root so we're gonna return node right we're that's gonna be what gets returned as the root node and that's what it's gonna be returned from the method now we have to set the left and right so no dot left we're going to set to be equal to the recursive call like in binary search we're going to then do from the left side so the left side is going to be from left to midpoint - one is gonna be from left to midpoint - one is gonna be from left to midpoint - one is gonna be the right boundary so from zero to the middle I'll the element right before the middle element so you get this as the root you set it as the root and then you set send the boundaries from this element to this element and we want to recursively call on that and then we're just gonna set the right node to be equal to the right know from midpoint + equal to the right know from midpoint + equal to the right know from midpoint + 1 sorry about that to the rights boundary so that's just gonna be your calling the recursive call on from 5 to 9 right cuz midpoint plus 1 from 5 to the ending boundary which is right and that's all that's the whole problem like it I'll explain it how it works is like you set you get that middle element right we got the midpoint we pass the sorted array we get the midpoint we make our tree node and we return it that's the route but we before we return it we do these recursive calls to keep going deeper and deeper into recursion and no dot left is going to be set to the middle of these boundaries so that's gonna be set to negative 5 in this case right you could see negative 5 I made I added a couple elements to the example so that's more clear and then negative 5 calls on the for the left element to negative 10 and negative 5 calls to the does the recursive call to the right element to negative 3 and then on this side it was the middle of these eight is the middle and then eight calls the middle of this boundary in the middle of this boundary which are just one element so 5 and 9 for the left and right and that's it that's all you have to do to solve this problem it's a pretty easy straightforward problem to get into tree problems definitely learn the pre-order problems definitely learn the pre-order problems definitely learn the pre-order post order and order traversal some of that and yeah that's pretty much it thank you guys for watching let me know if you need any more deeper explanation into this but it's just a little bit of a binary search type call binary search pattern - you know construct these trees pattern - you know construct these trees pattern - you know construct these trees thank you guys for watching I appreciate you guys joined the discord we've got everything in the description get on that and I'll see you in the next lead code video I'm back on this Lee code stuff so don't sleep on me I'm doing all these problems I just needed some time to I had to stuff alright see ya
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
337
today we're doing recursion specifically recursion with some memorization or cash we're going to do that with the example of House robber 3. the thief has found himself a new place for his theory again there is only one entrance to this area called root besides the route each house has a one and only one parent house after a tour the smart Thief realized that all houses in this area form a binary tree it automatically contact police if two direct killing houses are broken into on the same night given the root of the binary tree returned the maximum amount of money the thief can rob without alerting the police it's a little bit confusing by what they say by directly linked houses so let's take a look over here we have three two one um it's showing that the max amount we can Rob is seven which is this one plus this one the example we you see here illustrate that if you take three you cannot take two and three since they are directly linked and once you and here you can take three and one because um their parents are not taking it over here the example illustrate the other case um so here you can see that if you take four uh four is directly linked to three one and three uh since we've taken four none of its directly linked members can be taken so if we take a note both its parents and children cannot be robbed the reason why you can tell is recursion is because well we have two cases if we rock we want to know what's the maximum monetary value we can Rob if we rob the current house and what is the maximum monetary we can route if we don't Rob the current house now that we know we want to reuse recursion we want to find out how we want to Traverse the tree there's two techniques DFS or BFS what both techniques Works yes all problems that can be solved by DFS can be converted to BFS vice versa but one is going to be very inefficient right let's take a look if we use DFS say uh if we use DFS all we need to know is whether or not our parent um our parent is taken or not if our parent is taken then well we cannot use the current node right if our parents not taken then we have the choice of using this node or not using this node so what we can do is when we go from three to two we can pass it down be like hey your parent is used or hey your parent is not used that's how we're going to be using DFS and then when we're going to three same thing when we call upon the right child of two we can pass down be like hey uh two is used or hey two is not used if that's DFS right so DFS that makes sense now let's try it with BFS so with BFS uh we go here three we go two okay um we tell it hey our parents use or not use and then we go three hey our parents use or not use makes sense and then three parents use not use makes sense three parents use or not use so over here overall uh this makes sense so at this point both DFS and BFS works at this point both algorithm Works uh it's just like which one is more efficient right well neither because we need to optimize it why uh here's an example we have root three right three we have the option of take or not take right or like not take say if we use take then we will call upon our child two so two over here so before was three we're gonna call Coach child two um two has the odd we have the option um actually we have no option since three is taken two will be not take right not take and then it will call its child three so three over here and then we can choose take or not take right obviously take us better but we still need to check um so not take um now we're going to go through take uh sorry now we're going to go through not taking the route so if we don't take the root three we're gonna call two again two now has the option between take or not take so take or not take um and then two will need to call three again uh but depending take or not take it will be called twice well this is not really efficient because when we work on root we need to go through the take or not take case uh that means we need to call its child uh twice right so but because we call two twice for take and not take each of the time we need to call uh it's child three take or not take twice so in total uh three is called four times uh two is called twice and uh just for one call of three the root this will grow exponentially and will be repeatedly calling its children known over and over again this is very inefficient what we can do is when we're done calculating the result for a child we can cache that result right we can cache it so next time when we go to it's child two be like hey take or not take uh for either case we know the optimal answer this is how you know you want to use DFS reason being is that we will go in depth know the children first and at the first hit of three we can already catch the result right with DFS we go depth First Cash the result this way when the child is called again we can just use the cache but with BFS we don't know the child until we reach that level we will go three two three and then three one we will actually call the child last in this case um so we can't really cache any results so at this point we will note that we can solve the problem using recursion plus DFS and memorization after reading the question I was able to come up with that intuition myself and that was my train of pro uh train of thoughts first identifying that we need recursion and then deciding whether we use BFS or DFS and finally how to optimize it here's the code I have created for this question if the root is empty there's no houses to Rob we simply return we have a cache like I said we're going to use some sort of memorization um so here the key is the node and for the node uh for example we land on two depending on the case whether we want to take it or not take it either way we can know the max value and then you can see that I have a single helper function that helps me with the recursion for the result we're going to Simply return the value of the help function with our root the parameter of the helper function is the current node and the Boolean variable so this is point taken if it's true then that means our previous parent or is parent taken right so if this is true that means our parent is taken then we cannot use our current node if this is false that means our parent is not taken and we can choose whether or not we want to use the current node so we have two value here take Max and not take Max if the node exists in our cache we can simply update take Max and not take Max for the current node if the node is not registered in our cache we need to calculate it so first we're going to calculate take Max if we're going to take the node what is uh the maximum what is the maximum value will you check what's the maximum value of taking the left side or not taking the left side either way uh wait no so for take Max we actually take the current node right so save two we actually take the current node two in that case we pass down with the helper saying that hey your parent is taken um if left exists we go to the left note your parents taken you cannot use yourself basically and for the Rhino we do the same we call helper indicating that the parent is taken now we're going to calculate the not take Max since we're not taking our current node that then we pass down false meaning that hey your parent is not taken once we calculate both take Max and not take Max we're going to register it in our cash here we have two cases if my parent is taken say my parent is Taken 3 is taken then we cannot take the current note we just simply return the value of the maximum value at this point of the tree of not taking the current Max if you're if my parent is not taken right um then we have the choice whether or not to take our point or not take our point we will return the maximum of not taking our point and taking our Point whichever one is bigger we're going to return it and that is the code even though the algorithm sounded a little bit complicated recursion on memorization but as you can see here it's relatively straightforward now let's talk about runtime and space usage for the cache we're going to read uh we're going to store every node and it's take our Max not take value once so for space utility is o-n as for runtime for space utility is o-n as for runtime for space utility is o-n as for runtime we're actually only visiting each node once because once the node is visited the value is cached therefore the runtime of this algorithm is also o n just a quick reminder DFS runtime is on
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. **Example 1:** **Input:** root = \[3,2,3,null,3,null,1\] **Output:** 7 **Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. **Example 2:** **Input:** root = \[3,4,5,1,3,null,1\] **Output:** 9 **Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 104`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
198,213