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
763
all right let's talk about partition label so your given string of lowercase english later is given so you need to return the partition so for this a b c b a c a right the string the partition string is at most as possible so let each letter appear in at most one time so in this case every letter inside the inside a string appear in at most one time and then in this string it's at most one time which means there is no actual d e f g on other sides right so in this example we can see i can make sure i keep updating my character position so if a write a appears at 0 but a appears at 2 so i update the a to the position 2. so if a hit the position 8 i know everything is already inside the substring so i can put the insert into my list so the idea is this i have a counting rate and then in this container array i and then i store the char c for this char at and i and then count c minus a and this time we equal to i right position right so a character a minus a would be zero equal to zero but with character a again it would you would become two right now let's do the integer list new array list for the answer and we need this option right because we cut into partition right so ins that we can start from zero and that would be it so in i equal to zero so i need to loop through again so i need to see if n at least puts at this character if n at least character is actually the length of the itself all the position i found so say it's the chart at high minus a where everything should be inside the count counting array right so for the example a minus a 0 right and we already know the last character inside a is 8 right is uh is eight from zero to eight and then is nine so we know the last one the last character it appears in this substring is eight so if i equal to n right we can just add the length of it itself so a minus zero plus one right and then we need to increment and we need to um change the value for star so it's m plus one we are no longer need this character so we're starting from new character which is d so d is the position you we want to use and what else we just return this right and i don't have typo right i don't all right pretty good so let's talk about time and space is all of 26 should be constant all of one and you just add shouldn't be a problem time out of n in for this loop because you are traversing every single character in the screen and this is as well so all the fun because there's nothing inside the loop when you traversing choppers in the length of the s right so you just keep changing the count which is your n and then to see if i equal to the value which is the maximum for the character you found if that is you just add and that will be it peace out
Partition Labels
special-binary-string
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
String,Recursion
Hard
678
1,854
lead code 1854 maximum population year so the question is say that you'll be given uh an array which is nothing but a log of people who uh were born and the year they were they died in so this array is something like this so it gives details about each person say a person took birth in 1993 and died in 1999 okay so that would be the first person the second person would be say 2000 and died in 2010 the third person say is uh 1998 and died in 20 12 and say the fourth person is in 20 12 and died in 20 23 okay so this is an example that will be provided to us we have to figure out what was the year where the population was maximum right so what I'll do is this seems to be in sorted array as of now but no it is not sorted there's 2,000 year there's 1998 sorted there's 2,000 year there's 1998 sorted there's 2,000 year there's 1998 here yeah so this is how the input is going to be I need to find the year in which the population was maximum so how could I figure out so looking at this array what I can say is 1993 the population was one then until uh 1998 the population increased to two right so 1993 the population was 1 1998 the population increased to two 1999 it decreased back to one because the first person died here right then 2000 year 2000 it increased Again by one right 2000 10 it in decreased by one because this person died and then in 2012 this person who was born in 1998 that died right so 2012 it reduced to zero but then 2012 another person took birth okay so the population in 2013 was 1 okay oh sorry 2012 was back to one because one person died and one person took birth so it did not change at all and then 2023 is when it came down to zero so which is the first year where population was the highest it was in 1998 right there are two years where the population was highest but we need to return the first year first time the population was highest so 1998 this is the year and this is what we will return at the end right so if we see what did we do we sorted this all the values by the year and then continued figuring how many people uh continued updating the population and checking the population and returning the max year where the population was maximum this is exactly what we can do in code as well right so what we can do is we can I can create a AR okay I can name it BD okay births and deaths so BD would include uh triple the tle would include what would it include let's see so for every log in logs first of all I'll create an array of births so tle will include log index zero because Zer is where they talk about the tell about the year in which the person was born so we'll take the birth year and set it to one because we'll be increasing by one so I'm setting the second value by to be one and then I'll also join with this another array which will include the debts so for log in logs and here what I'll set is I'll set it up CLE with log of index one which gives me the year of death and the value would be minus one because I would be reducing my population by minus one so now I'm creating an array such that BD is the ARR says that it has got Tes where there is your mentioned and there is + one and minus one mentioned there is + one and minus one mentioned there is + one and minus one mentioned for birth and death this the length of BT would be double of L LS because in logs in each record we are getting birth and death both while in BD we are separating out one record would either have birth or either have death right so after this what I'll do is I'll sort BT okay so sort PD what will it do it will sort PD by the first element which is the year and if there is any conflict in the year in the first element it will check for second element right so second element will either be minus1 or + one so it will take the minus1 or + one so it will take the minus1 or + one so it will take the depth value first which is minus1 and then after it plays the birth value which is+ one that is exactly what we which is+ one that is exactly what we which is+ one that is exactly what we want to be able to figure out the uh the maximum population at each year okay so now what I'll do is I'll initialize Max population to be zero I'll initialize current population to be zero and I can go for uh for each login for BD for login BD okay and I can check the current population so current population will be I'll update the current population first current population would be log index it would be I would add uh log at index one okay so either + add uh log at index one okay so either + add uh log at index one okay so either + one or minus one will be added to current population right and if current population is greater than Max population then it will update Max population with current population and I also maintain a variable called year which will store the max year so whenever Max population is updated I'll update here with the current year so current year would be log at index zero right so that means when the for Loop is complete and it has gone through each element it would have got Max population and the year in which that Max population was that'll return the year and that's it let's run this and see and that work for the test cases let's submit it and that worked 15 milliseconds better than 98% of solutions that's how you than 98% of solutions that's how you than 98% of solutions that's how you solve this problem 1854 maximum population years see you in the next video
Maximum Population Year
maximum-population-year
You are given a 2D integer array `logs` where each `logs[i] = [birthi, deathi]` indicates the birth and death years of the `ith` person. The **population** of some year `x` is the number of people alive during that year. The `ith` person is counted in year `x`'s population if `x` is in the **inclusive** range `[birthi, deathi - 1]`. Note that the person is **not** counted in the year that they die. Return _the **earliest** year with the **maximum population**_. **Example 1:** **Input:** logs = \[\[1993,1999\],\[2000,2010\]\] **Output:** 1993 **Explanation:** The maximum population is 1, and 1993 is the earliest year with this population. **Example 2:** **Input:** logs = \[\[1950,1961\],\[1960,1971\],\[1970,1981\]\] **Output:** 1960 **Explanation:** The maximum population is 2, and it had happened in years 1960 and 1970. The earlier year between them is 1960. **Constraints:** * `1 <= logs.length <= 100` * `1950 <= birthi < deathi <= 2050`
null
null
Easy
null
202
what's going on everybody zane here back with another video for this one we've got question number 202 which is happy number on lead code so we need to write some algorithm to determine whether or not a number that we're given is happy a happy number is essentially going to be its numbers like if there was a number one nine its numbers one and nine if we just square those two numbers and then add them together if that will eventually get to a point where it'll endlessly loop or it'll end it a one so here's what i mean if we look at this example of 19 we've got one and nine so if we do one squared plus nine squared that'll be 82. that's our next number so our next number after that would be eight squared plus two squared which is sixty-eight plus two squared which is sixty-eight plus two squared which is sixty-eight then six squared plus eight squared hundred and then finally we've got one zero so one squared will be one plus zero squared and zero squared again it'll be one so that'll eventually get to a point where the value where the sum will speed stuck at one then the other example here is where n is equal to 2 so 2 sum is going to be 2 squared is going to be 4 then 4 squared it'll just continuously go increase and it'll stop at obviously the maximum value here but uh that's what they mean by endlessly in the cycle so how are we going to tackle this well we actually kind of got the answer here the first step is to really get the next number so in order to get the next number we can actually create a helper function for that and for me i can i'm actually happy that i said helper function because before i was a little uh confused as to when people said helper function ah damn i don't know what a helper function is or but essentially you're creating another method another function that will do something for you without having to constantly copy the same amount of code here so i can do something here then do something again and again but instead of doing that i could just create a function to do something that can be called once so instead of us calling it a thousand times we'll create a function that will do something for us so let's create a function to first before we even deal with if it's happy or not let's figure out how can we get the next number so i'll create another function here private and we're gonna return an int get next number and this is going to take in some number now what exactly do we need to do to get the next number well we need to first take the last digit and well it wouldn't necessarily be the last digit but we'll get all the digits and we'll add it to sum to some sum so let's just create a sum variable and initialize it to zero and we'll say that while we need to run a while loop so whilst the number is greater than zero we need to continuously do something so we wanted to continuously run in through this while loop until we get to a point where the number is now zero so that means we've got our sum or got our value whatever so in order to get the digit on the far right we should know that to get that digit it would just be the number mod 10. so now that is our number on the right side now in order to eliminate that number we could just say num is just going to equal num divided by 10. so now that number has been accounted for and has now been removed and we could do now is we can add our number two or our sum is going to equal our digit times digit so what we're doing here is we're extracting the digit we're then removing it from our numbers num and then we're adding it we're setting it to our sum and i think what we need to actually do here is we're going to add these so we don't want to just set it to some and then once that is summed up it'll continuously run through this and then we'll get to a point where we could just return our sum now this is going to get our next digit so now up here how can we tackle whether or not something is happy so first off what we need to do is we need to establish what we're going to use to solve this so when it comes to endlessly looping or a cycle or doing something constantly until we get to a point where things are done that's always a while loop for me so while something do something so in this while loop we want to make sure that n is not going to be one so while n does not equal one and what else well we need to think about what values we can store in some data structure to account for it either being endless or if it was already accounted for so what we could do is we can actually create a set so let me create that first and it should make sense afterwards i'm going to make a new hash set here and i'm going to say that while end does not equal 1 otherwise we break out of this loop and the set does not contain the number then we can continuously loop through which is going to be now we'll add the value of n here and now n has been added to our set now once that's been added what we could do now is we'll grab the next number so we can just do get next number n and we'll say that n is going to equal that next number and then continuously go through so this is what i meant by doing one function otherwise we'd have to copy all this and put this here which is a little bit messy and then we'll continuously have it get the next number add it to our set get the next number and as long as it's not in the set that means that it's infinitely looping and as long as n does not equal one that means it will never get to a one now if it does get to a one then okay then it's happy so just return n equals one so let's run this see what we get and submit that's it so let me recap real quick so our first step was to get the next number we're not even dealing with whether or not it's happy our next number is essentially going to be a while loop we that we constantly perform we'll extract the digit using the modulus we'll now set number to be num divided by 10 so that we've already accounted for that digit on the right side so now we can just remove it from the right side and then we'll say that the sum is going to be whatever digit is squared because that's how we get our next number we'll take the digit square it plus take the digit square it once we do that sorry i lost my audio there once we do that we'll add it to our sum and then we'll return our sum at the very bottom once we've done that then all we need to do now is account for two things the number is going to be happy if it's going to be endlessly looping or if it ends in one so as long as n does not equal one we can run a while loop and as long as the set does not contain the value we'll add the number to our set and then we'll get the next number and continuously iterate as long as it's not in the set and n does not equal one that means it'll continuously loop or if it ever jumps out return whether or not n is equal to one anyways guys that's it for this one if you have any questions comments feedback please let me know in the comments below otherwise hit that like and subscribe button show me some love and i'll see you in the next one peace you
Happy Number
happy-number
Write an algorithm to determine if a number `n` is happy. A **happy number** is a number defined by the following process: * Starting with any positive integer, replace the number by the sum of the squares of its digits. * Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1. * Those numbers for which this process **ends in 1** are happy. Return `true` _if_ `n` _is a happy number, and_ `false` _if not_. **Example 1:** **Input:** n = 19 **Output:** true **Explanation:** 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 **Example 2:** **Input:** n = 2 **Output:** false **Constraints:** * `1 <= n <= 231 - 1`
null
Hash Table,Math,Two Pointers
Easy
141,258,263,2076
1,588
all right so let's talk about the sum of all of then sub array so you're giving a real positive integer array and calculate the sum of all possible all length separates so you have to return the sum of all of them sub array of array so this question consisted pretty hard so i'm going to give this guy credit so this is a legend and let's just dive into the example so uh this is the array one two three four five so he actually um give us the answer already so how many times one represent this is actually five times right and eight times for two nine times four three eight times again for four five times four five right so this is k equal to i plus one times m minus i but somehow the off the often should be one three four five four three right let me just uh value three so one uh one itself is actually length of one which is all length one two three and then one two three four five which is three uh three times four integer one and how about two okay two uh for lengthwise is actually one and then uh for one two three there's another one so it's two three four is another one which is uh three and one two three four five which is four right so you have all length is actually equal to uh k plus one divided by two right so you actually determine uh what determine your uh k if k is actually uh multiply two is actually equal to one then you have to implement your fonts if not then you basically just return the even length right so this one it's actually okay so this one's actually the same four and four so let me say another one about five so uh index two uh index three so in this three you have to take five another four right so this is because what one two okay three the length of one is one two three is another one two three four another one so it's actually one two three and three four five four one two three four five is five right so you have to take five instead so let me just call it you'll be able to follow along so you have the return value which is original i'm gonna just resort right now so i need what i need next for sure i plus so i will have to have the i will have to have one in this k equal to i plus one times n minus one uh a minus i right so this is actually representing one it's actually representing in star equal to i plus one almost n equal to a rate of length minus i so uh this will be pretty much it right so i also need to have a k okay repeating star time chain right so i will have to have a counter so this is going to be my cons bounce represent plus or minus divided by two right so i would definitely get my uh even lens count for sure right so i have average four for this one and four for this one but in this case in the off index it's actually i have to implement by one this is because uh due to the math right so it doesn't matter so if k mod 2 is at equal to one times increment right com plus the return value is actually plus equal to count based on the cons multiply the array i so this will give me what so in this one in this example integer one you will represent how many times you represent three times right so plus three plus and then four times two which is 8 5 times 3 is 15 right so this will be the answer and this is pure math so if you don't understand this is definitely fine so uh cannot find okay this is k sorry this is k right so let me submit all right so let's talk about time and space is going to be constant time is going to be all of n and represent end of the array and this is the question for the uh this is the solution for this question and i will see you next time bye
Sum of All Odd Length Subarrays
sum-of-all-odd-length-subarrays
Given an array of positive integers `arr`, return _the sum of all possible **odd-length subarrays** of_ `arr`. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,4,2,5,3\] **Output:** 58 **Explanation:** The odd-length subarrays of arr and their sums are: \[1\] = 1 \[4\] = 4 \[2\] = 2 \[5\] = 5 \[3\] = 3 \[1,4,2\] = 7 \[4,2,5\] = 11 \[2,5,3\] = 10 \[1,4,2,5,3\] = 15 If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58 **Example 2:** **Input:** arr = \[1,2\] **Output:** 3 **Explanation:** There are only 2 subarrays of odd length, \[1\] and \[2\]. Their sum is 3. **Example 3:** **Input:** arr = \[10,11,12\] **Output:** 66 **Constraints:** * `1 <= arr.length <= 100` * `1 <= arr[i] <= 1000` **Follow up:** Could you solve this problem in O(n) time complexity?
null
null
Easy
null
1,889
hey what's up guys uh this is chung here so this time bitcoin number 1889 minimum space wasted from packaging right okay so you're giving like un packages and you're trying to pull to place in the in some boxes right so one package per box and then we you have like m suppliers and each produce different size of boxes okay and obviously a package can only be placed in a box if the size of the package is less or small or less than or equal to the size of the box and the package size are given as an integer array right so that's why you know the suppliers are given like as a 2d integer right so for each of the suppliers we have a list of boxes that supplier can provide and you want to choose a single supplier right and use the boxes from them such that the total wasted space is minimized right so the total wasted space is the sum of the space wasted in all the boxes right so basically there's a it's a difference between the actual size and the package size and then you summarize everything together okay so you just need to return the minimum total wasted space right by choosing the box suppliers optimally if it's not in if it's impossible to fit all the box packages right you simply return minus one okay and then you do a modular in the end so for example this one we have three packages with size two three and five and then we have two suppliers uh who will supply provide these two kind of different sizes right and so the optimal choose is the first one basically we choose the first one and then we use size 4 to we use size four for the first two packages and then we use size eight box for this for the last package that's why the answer is six right and then yeah so here are some constraints right so the boxes and the packages they're both 10 to the power of 5 right and there are some like other constraints here so obviously this problem is that you know obviously we need to try to check each boxes each supplier right but you know since we have 10 to the power of 5 packages and we have this many suppliers so suppliers is also gonna be uh this many right and for each of the supplier you know for each of the supplier we could also have like 10 to the power of five different size of boxes right so at the beginning i was like you know there's no way we can check this one without causing the time tle right because in total we have 10 to the power of 5 boxes of suppliers and then we have three suppliers we can have like 10 to the power of five sizes right the box sizes so there's no way we can do it regardless and then i saw this one actually see so basically the total sum the total different sizes of all box sizes across all the suppliers are also within 10 to the power of 5. right then what does this one mean it means that you know all we need to do is we just need to reduce this dislike n times n to somehow to unlog in right and then we can solve we can pass the test cases so how can we if uh more efficiently find the check each of the boxes if we can config can put the uh some packages in into the box right i mean obviously if we have some packages right for some packages we want to use the smallest box that can fit in this package right because we want to minimize the waste the total wasted space so which means let's say we have a package two three and five right if we have some boxes let's say if we have box three and the five this is the box right so for the package one obviously we want to use three right and then for three we also want to use three and then for five because three cannot hold 5 that's why we have to go to 5. right so i mean now it's i think it's kind of we can certainly do a binary search in this case right because assuming let's say we store the packages from the smallest to the biggest and then for each of the supplier we also sort the boxes from the smallest to the biggest and then we for each of the box side we can simply do a binary search right so for the binary search you know for example if we have three here right uh we do a binary search here and then for three if by just looking uh look at those kind of ladder uh the numbers we know for box three we can put two boxes into it which is this two right and then we with the with this two here you know we can simply calculate the uh the total waste right so since we have two boxes here you know the total of these two boxes size is five right and then for to use two size three boxes we have six that's why the waist will be six minus five right and then after this one you know and then we can move to the second one the second boxes for the second boxes here you know we need uh we're gonna we will we'll see five here right that's why we'll get the five in get the five the last package into the boxes so in order to efficiently calculate to make this thing work you know one thing is that you know it could have like some several uh packages right so these are packages maybe for the first boxes you know we can uh put in the first two right and then for the second packages maybe it can conclude uh the next three packages and then for the last one and then for that for the next box size we can put the last two right as you guys can see here so we will need to get some of somehow the range sum right which means we need to use a presump right pre-sum out of it and then right pre-sum out of it and then right pre-sum out of it and then besides the pre-sum we also need to besides the pre-sum we also need to besides the pre-sum we also need to maintain like a pre prefix pre index because you know for example at for this kind of box right we need to get the pre-index get the pre-index get the pre-index which is this one and then we'll have to we'll have the current index which is this one so if we use a pre the current index subtract the previous index we get the get how many packages the current box can handle right so that's how we get this six here and that's we can also use this kind of these two indexes to quickly get the pre-sum of this to quickly get the pre-sum of this to quickly get the pre-sum of this of the total size of for this kind of packages and then whenever the index reached the end we know okay we have uh put all the packages in into the boxes then that's when we stop right so that's basically the idea and we do a sort we do a presump and then we use binary search okay and one more thing is that so when we use a binary search you know we want to use binary uh bisect write in python because let's say for three here right so for three because for e even if it's the same size of the boxes we still want to include that packages right that's why you know when whenever there's a there's the same value of the box size we want to use we want to move it to the right that's why we use a bisect right otherwise you know we'll get this one we'll it will exclude this three which is wrong right for this side three box um yeah i think that's pretty much it is right so first we sort the packages okay dot sort uh and then we have a pre-sum right so this time i use the uh the array type basically you know to prefix with zero and then for the length of the packages okay we do a length of the packages and then for packages in the packages right we do pre-sum dot append we do pre-sum dot append we do pre-sum dot append okay and then pre-sum dot minus uh okay and then pre-sum dot minus uh okay and then pre-sum dot minus uh minus one plus p right that's how we do with the presump and yeah and then we just need to check the uh you need to check the uh each box right so for each box in boxes right which means is the supplier right we sort we stored the all the box size we can simply do a quick check basically you know if the biggest box is still smaller than the package then the biggest packages right that means that this supplier cannot handle all the packages that's why we can simply continue right so this is like simple check but i yeah i think this one will not affect the final time complexity and then we have the pre-index pre-index pre-index equal to zero and then we have our cost right work cost means weighs you know but i use cost zero right um and then for size inbox okay and then we have a index it's going to be a bisect right we search the packages and then we do the current size okay so now we have two indexes right so we can have like the total uh the total size so the total size the current box can handle is what is a pre-sum is a pre-sum is a pre-sum of index minus the pre-sum of index minus the pre-sum of index minus the pre-sum of pre index okay so here you know so that's why i use zero here because you know with the packages right you know since we have this kind of uh p a c k h a g s packages so whenever we prefix this zero at the beginning so when we are trying to get the uh the prefix sum right so let's say we want to get the prefix sum of this part so how do we calculate that we're going to use the index of here of this one minus the index of this one right that's how that's why we need to move the index forward by one right and this kind of uh bisect right this one is exactly the index we're looking for right because if this one is like two three and three right and if our the box size is three that's that it means that you know we'll get index of this one because we use a bisect right that's exactly the index we're looking for here okay and the pre-index is exactly the okay and the pre-index is exactly the okay and the pre-index is exactly the one of the previous one which is this one right and for in terms of the prefix zero here you know it means that you know at the beginning right the beginning let's say if we have like proof this is of the part this is a this is the first index right so we have index right here okay that's index and the prefix is zero because in this case we need the prefix of this one right which is the uh yeah which is the uh which is empty which is zero right that's why you know uh we you will use the zero as a as the at the starting point yeah actually i think one also works because this is one right so prefix zero and prefix one there they're both one uh they're both zero uh okay cool so that's how we get the total size right that's the total size of the packages the current box can handle right and then the cost will be what the cost will be this the total package total count so the total count is what is simply the index minus the pre-index minus the pre-index minus the pre-index right so that's the uh that's the total packages count that the current box can handle and then the cost will be what will be this kind of uh the size right times the count right so that's the uh the box the total space when we use and then subtract the total package size and that's the cost right and then we have a we have we can do an early break basically if the index is equal to n it means that okay we have already covered all the packages we can simply break right and then don't forget to update the pre-index with the forget to update the pre-index with the forget to update the pre-index with the current index okay right and then here we do our answer going to be a minimum of answer.cost right that's it right so in the end we do answer do a modular okay do we have our modular here no we don't mod it's going to be the 10 to the power of nine plus seven okay so here we have a mod if the answer smaller than system max size right house minus one yeah i think that's it so if i run the code okay all right so at least it passed right um so one thing to be careful is that you know uh i mean during in during the contest i was doing something like this so uh i was doing like this i think yeah then we'll get the wrong answer i believe let's see i think this one will not pass okay so i have to do the modular in the end i think yeah i think that's for some reason i think that's the uh that's the modular thing right so basically we have to do the modulars in the end so that is when the module will not affect the uh and will not affect the logic to get the minimum cost right um so yeah and for the time complexity right so this one uh actually we already have like unlock in here right to store the packages and here for the boxes okay so for the boxes you know we the since the total size of the box size is 10 to the power of five that's why you know this two four loop here will be uh will be a in total right where n is the 10 to the power of five and for each of the inside the photo here we have a binary search which is unlocked right that's why the total time complexity for this one is also unlocked that's why this one can pass and yep i think that's it right at least that's what i did right during the contest so basically it's just like a sort plus a binary search and so we sorted by package at the beginning and for each box we'll also sort from smallest to the biggest right and then for each of those the boxes we do a bisect write binary search right and then we maintain like the previous index and also use this prefix sum to help us quickly get the total package size and then the count right and then we calculate the cost and then there you go uh yeah i think that's it for this problem and thank you for watching this video guys and stay tuned see you guys soon bye
Minimum Space Wasted From Packaging
check-if-number-is-a-sum-of-powers-of-three
You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box. The package sizes are given as an integer array `packages`, where `packages[i]` is the **size** of the `ith` package. The suppliers are given as a 2D integer array `boxes`, where `boxes[j]` is an array of **box sizes** that the `jth` supplier produces. You want to choose a **single supplier** and use boxes from them such that the **total wasted space** is **minimized**. For each package in a box, we define the space **wasted** to be `size of the box - size of the package`. The **total wasted space** is the sum of the space wasted in **all** the boxes. * For example, if you have to fit packages with sizes `[2,3,5]` and the supplier offers boxes of sizes `[4,8]`, you can fit the packages of size-`2` and size-`3` into two boxes of size-`4` and the package with size-`5` into a box of size-`8`. This would result in a waste of `(4-2) + (4-3) + (8-5) = 6`. Return _the **minimum total wasted space** by choosing the box supplier **optimally**, or_ `-1` _if it is **impossible** to fit all the packages inside boxes._ Since the answer may be **large**, return it **modulo** `109 + 7`. **Example 1:** **Input:** packages = \[2,3,5\], boxes = \[\[4,8\],\[2,8\]\] **Output:** 6 **Explanation**: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box. The total waste is (4-2) + (4-3) + (8-5) = 6. **Example 2:** **Input:** packages = \[2,3,5\], boxes = \[\[1,4\],\[2,3\],\[3,4\]\] **Output:** -1 **Explanation:** There is no box that the package of size 5 can fit in. **Example 3:** **Input:** packages = \[3,5,8,10,11,12\], boxes = \[\[12\],\[11,9\],\[10,5,14\]\] **Output:** 9 **Explanation:** It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes. The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9. **Constraints:** * `n == packages.length` * `m == boxes.length` * `1 <= n <= 105` * `1 <= m <= 105` * `1 <= packages[i] <= 105` * `1 <= boxes[j].length <= 105` * `1 <= boxes[j][k] <= 105` * `sum(boxes[j].length) <= 105` * The elements in `boxes[j]` are **distinct**.
Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it
Math
Medium
326
226
I am Ashok Hello friends blind 725 new day and today problem number five is born in Shagun's words for adultery easy problem the previous one BCE and this is so small that means we have been a lot of workers too so this is for and this phone is that route of ours. The voice message will remain the same, just add other things, then those notes on the left will be controlled on the right, so remember that two was here, so it has gone here, you have to make it 90, basically you will switch it off and the children below one two. Child 143 341 To subscribe, the first thing we do is now school, not war, then we have to return that we will start the net, like I told you, what do we do to get it, take a temporary variable Then there is the one in which I am cleaning the left and right, so I will tighten the route, okay, and of course, dot right, our tempo will go, the thing is clear, now we just have to call this function, inverter, okay, Russia. Dot Something Let me copy this that Electrolyte will run both, then in India then this also has to be taken care of, just working on the Electrolyte note will not help, you will have to pay attention to both, okay now that we have started this, now the score also. I have seen that I will do the final vitamin, let's check the route, I have a safe tour, let's submit. In 2020, I had earlier said that it is okay, so I will not miss the class today, the code was there, we will talk about the rest later and my It is good that Sehwag is following the test, see you in the next video.
Invert Binary Tree
invert-binary-tree
Given the `root` of a binary tree, invert the tree, and return _its root_. **Example 1:** **Input:** root = \[4,2,7,1,3,6,9\] **Output:** \[4,7,2,9,6,3,1\] **Example 2:** **Input:** root = \[2,1,3\] **Output:** \[2,3,1\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
729
hey everybody this is larry this is the 10th day of the june niko daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem uh i my ac is still booking it in case you're curious and wondering uh but i did figure i put on the t-shirt uh but i did figure i put on the t-shirt uh but i did figure i put on the t-shirt you know it's still uh well okay it's only 77 degrees outside today but it's still pretty uh warm inside uh anyway okay so i usually start this live um so if it's a little bit slow fast forward or watch another video or whatever you need to do uh i believe in you okay today's problem is my calendar one um i feel like this is like one of those movies that they're already ambitious and they um you know you don't even know if it's going to be a good problem but they already have like three sequels coming what are you doing just like you know make sure it's good first anyway uh implement a my calendar class to store your friends and your new friends and can be additive added event can i cause a book double booking okay so you have an open interval uh so it's a real number is it real it seems like these are all ins unless i'm like confused about it okay so double booking happens when they have not empty intersection um so effectively this is inclusive but n minus one so that's a little bit awkward i don't know maybe it's fine anyway for each chord to return true if the fan can be added otherwise return first and do not return okay so this is this seems pretty straightforward basically you have um a list of events and then you're trying to think whether um what it is that you find in it right uh and actually just i know that there are a couple of solutions for this for sure uh okay well the really basic one is noting that uh the number book the test cases is a thousand and to be honest if this was a contest or something and this is like a um you know a second problem or easy problem relatively or like the second media second problem like a quantum medium but relatively easy problem uh i'll i look at the n and i just do some n square and algorithm where we just loop for everything twice right that's why we insert and we loop for everything once and that's fine uh that's pretty straightforward and you can do that in like a minute um like just typing it out uh there are a couple of other solutions some requires uh you know the one that i probably like is one that we um is it now it's a scan line or sword line uh yeah scanline algorithm-ish but there is yeah scanline algorithm-ish but there is yeah scanline algorithm-ish but there is an the one that um or prefix sum if you want to call it that uh there's one about prefix sum as well which is dynamic programming but the key thing to noting is that uh so how do you do prefix sum well you add one under the start range and then you do a subtract one and end range and then now that you have this prefix sum you just have to query everything in between and of course the naive implementation of a prefix number is not going to cut it but if you're being really slick and you do a binary index tree or a segment tree then you know then that's how you would um do it in n log n time or well it's not n log n times n log um the dom n log u time where u is 10 to the ninth is that true uh well i guess if you do it with uh binary index tree that's true but you could probably do it with segment tree or something like that um yeah so there's some ways of doing it there's also um just binary search uh you just put everything in um yeah same idea with prefix sum is that you know you just put i mean same edge they're all kind of related in a way because you're representing the same underlying data but you can just do a binary search um if you know the thing to note there is that there really only a couple of possibilities for sigmund um uh yeah i mean i think the tricky one is yeah i mean there are a couple of things you can have to make sure your binary searching on but i think that should be okay or at least a binary index tree um and then you know oh yeah actually no i mean you could just i was gonna do something even really fancy but you can actually just um just do a two binary search right one on the end start point and one on the end point and if there's any number in between or any um endpoints in between then um so they're only a couple of scenarios right there either there's another endpoint in between your two numbers or your current um segment is uh entirely overlapped by or dominated by another event which means that when you do a binary search just look at two adjacent numbers and so forth um so yeah so there are a lot of possibilities to play around this because this is uh that kind of problem with there's just a lot of possibilities so i gave you like five of them maybe i don't know i didn't count but try to up solve it if you can and play around with it uh maybe not the end square one because i mean okay you can spend a minute to play around with i'm just gonna do the binary search one i and then maybe we'll go over other people's solutions afterwards because i think there are definitely a lot of solutions here um so yeah so how do i want to do it okay so let's just keep a assorted list uh yeah i'm a big fan of sorted lists but uh but you know make sure you know other ways of implementing around it otherwise you know you only want to be in an interview where they're like nope you cannot use it right uh actually i'm having a little bit allergy thing everything's so itchy i don't know if i ate something or just trees in general i'm allergic to a lot of things who knows how these things work technology is weird uh i don't know if you know this but in new york um there's a new york times article at some point recently or maybe not that recently a couple of years ago where they mentioned that they changed all the sex of the trees to be um i think they changed it all to male i could be wrong on that one but anyway they changed it to one of the sex so um so that because it's less messy i forget which one it is um i think it's the male it's a less messy one where um it's less smelly um but there's a lot more pollen uh so that's why like everyone's just getting hit hard uh the last decade or so because when i was growing up i was pretty fine there's no uh no issue here but it is what it is so yeah so let's do two binary searches on this uh i have to remember i have to think about this a little bit with respect to whether this should be inclusive or exclu or sorry left bisect left or bisect right um i'm gonna make everything inclusive anyway because this is just i don't like so then um you can be a little bit sloppier uh i think maybe uh let's do start indexes here and indexes you go self-doubt indexes you go self-doubt indexes you go self-doubt bisect left of uh n if start index is equal to an index um that means that okay so now we okay so if they're not in the same index then we return false because that means that literally there's an endpoint in between right so you don't want to add it um because if there's an endpoint in between them you know if you have this point there's an end point here that means that by you know either it overlaps in some way right you could visualize it in your head uh whatever but okay and so now if they are the same then that means that the other possibility is that you're in between two endpoints so i think i have to keep track of because there are two in other scenarios right where like the i guess we only have to keep track of i think i got it but it's just running through the scenarios in my head um definitely try a little bit at home i was going to think about caring about um each particular segment uh and whether that matters but actually i think it doesn't it just matters whether you're looking at the right end point or the left endpoint or the start endpoint and end point of the previous um the previous segment because for example if you have a segment like you know that's for the purpose of um you know if you have two indexes that are here and then you have one that is to the right or the one that appears afterwards if the starting point is to the left um yeah because the by some pigeonhole of force e kind of way if the next if the index are the same then okay so you look at two things right one is that the index if it is the right index then it's just to the right oh is that true i mean that part is true oh no because okay because i was going to say that there could be other overlaps but in this case there the reason why this could work is that there is an invariant in which nothing overlaps because if they're overlapping then you have to check all these other segments but here the closest segment because they're not overlapping if it faces the other way yeah another way of thinking about it okay let me actually i know that i talked a lot so and it's very confusing the way that i'm talking about it so i'm gonna just pull up paint real quick uh what i'm saying is that okay so let's say you know we basically have a number line uh we have points um let's say our search is here and then now we have to look at the two adjacent indexes right so i describe these two um the two adjacent endpoints as either a start endpoint or an n endpoint but you can actually face look at it the other way if it's an end point that means that here this faces that way uh or this one faces that way depending on which one and then if it's a start endpoint then it faces that way right and because there are no overlaps if this index is facing this way uh if changing colors hang on if we're doing this way that means that this lines end point it's going to be going the other way somewhere but it passes our point because that's the definition of in between right um and then in the same way if we are here and it's facing left meaning it's in uh in an end point and it goes you know here and it you know intersects with some other endpoint but i guess it has to be this one actually because as we said there's no overlaps so okay so actually in that case because there's a lot of things that's uh in a way forced because there are no overlaps and because of that and variant actually i was wrong about this drawing as well just actually have to stop here right because there's no overlaps so that means that we just have to check with these things and that also means that we only have to check for one end point which is that the index is facing um your index is facing right which it means that it's a start endpoint okay so that's the only thing that we have to do so um so yeah so now of course we don't really do any so now that just means that we have to track one thing more um let's also double check real quick that this is in it because if because there is a case where if this is oops link with this then so this is in between and that's good otherwise if it's either all the way to the beginning or all the way into the end then this is true so let's actually return true in the other case but here let's say it's in between so now we have to check the indexes so we do something start index um so let's just have two things right one is the x which we don't care about because we know that it's smaller and then let's just say we have a tag on whether this is the start endpoint so uh it starts saying let's go here if it starts oops wait oh yeah return true uh we actually didn't do this problem quite right of course um or by we i mean me because we have to insert stuff in this the list which we have not done so um okay so actually let's actually change this to if it's not start then we turn force otherwise we just do add here and the way that i restructure this code so that i don't have to write the same thing twice though depending on what you're doing it may be a little bit tricky so yeah so now you just insert the start which is an insert true and then also and also true oh sorry n and then force and of course we change these to be inclusive don't so hopefully this should be good uh let's give it a spin only one test cases so i hope this is right uh tuple and int oh yeah um that should be sufficient okay i think i want to top up one element and i guess we can put a dummy element as a second element but i think this should be okay nope into object is not there well do i insert weird things okay fine let's just do i don't know if this would be sorted the right way that's why i'm a little bit worried about doing this um i thought that you could do it with tuples of different lengths but maybe i'm wrong oh whoops um maybe this is what i need okay there we go uh syntax is very awkward apologize for that um the reason is because uh we have a second thing that we don't want to search by and we want to get the first element no matter what anyway and i forget whether i mean i think intuitively it would uh put force before true but i didn't want to test that and also it's a little bit awkward so yeah so this looks okay i'm not confident about it because this test case is kind of crummy uh but i am lazy so i am lazier than i am not i am lazier than i am unhappy so let's give it a submit and see how it goes because after all it is 3 28 a.m because after all it is 3 28 a.m because after all it is 3 28 a.m uh here in new york uh unfortunately we do have a wrong answer and at least it looks like it's uh it's a big case 72 hour 148 uh unfortunate though still but let's see so that i could click on div so i returned probably later on as well um because these things tend to cascade or maybe apparently not but okay so one two three zero and seven overlaps but i returned true why do i return true oh because i search for sex here and i know what i think i know why this is to get yeah okay i see why because i because um now we search for sixes and inclusive it finds a six um so any overlaps is not good but i did not check for that case i was a little bit sloppy on this one uh okay so then and six is of course the end now this is a start point huh that is awkward though wouldn't that because it is the start point i do search for sex and it finds sex huh i mean there are a couple of things to fix that i'm just trying to think through it a little bit um so this returns the same index oh because they return the same and no um so it returns the same index so it goes here and then the start index should be zero so it goes here but then now why would this be wrong all right let's just um let's do some minor debugging um and i sometimes even when i get something right i will debug it because i'm not confident about it but oops okay i guess that's fair okay so yeah it does 23 true 23 and 31 okay 42 and 50. that's gucci six and fourteen uh okay so that's good uh this is also true that's basically what i said right why is the is start not right so this is six and true so if this is oh maybe i just confused my logic a little bit if it is the start then it will return force no wait yeah if it is to start did i just have this logic wrong yeah wow whoops i think i said the right things but i confused myself at some point yeah okay i think my logic is just wrong in general to be honest um i think i messed something up here i think that's why i was very confused and i just got like i said um that's why i got lucky on the first one having that test case but um i definitely should have checked a little bit more okay let me step back a second uh because i get confused easily clearly so okay let me do a bisect left the number that you get is actually not the number on the left is the number on the right so i messed up that one um i think that's where um i confused myself so we look at the number to the right and if the number to the right is to start then that means that this is good so if this is a start did we return true but then that's how we okay so i actually i think i did this by accident i made two so the funny thing is that yeah i made two bugs that counteracted each other um but then now we're checking the one that's to the so now this is the start if this is a starting endpoint we want to i'm just trying to think whether it is good enough that we do a bicep right i think it is actually because then now but i could be wrong i think i'm off by one on that one oh no i stepped the wrong same wrong answer huh okay let's just so it gives us the number that is so okay so bisect let me step back for a second uh okay so the bisect left will get us the number that is bigger than this one or equal to this one if it is equal to this number then obviously it is not good but whether it is start or not did we miss a case i mean how did i miss this case i'm trying to think okay and i think we're just i'm just not handling off by once very well that's the short story to be honest okay i think we can just check it another case i thought i didn't need this but maybe we have some off by one issues that uh okay so now it looks good um though obviously given what we experienced i'm not as confident but again but i am still lazy though so i am going to submit uh get the wrong answer here okay so let's take a look again at this one so this one i have 99 100 45 57 did i mess this up why would this return force so okay so we're looking at the right side because by different i think i'm just confusing myself with the direction i visualization's hard sometimes late at night okay so when we do a binary search we get the thing that's on it okay that return force so or bigger um so assuming these two indexes are the same then yeah i think this needs to be eyesight right i think this is a little bit awkward otherwise but then this would never be true so i don't know i think i'm just being a little bit awkward i think bicep right will get us to the next one that is for example if it is six it gets us to next one and then where to start then it is good now i think i just need to check for more cases i think oh fine okay but this is just not even off by one so basically this is saying that this searches um this gives us zero because we're inserting the beginning uh this is gucci um we looked at the first element that we're installing before um it's going to be the 47 and it is to start and because this is the start uh this should be good right yeah i gotta point it again i get so confused right now no i think i have two other test cases so maybe it's awkward okay i think it's this one though right so 99 and force did i mess up why is 99 of oh it's 99 b oh that's why because i've i did forget about this case so the case is that because we're now doing inclusive now this is a point and that means that the here it's going to give me that true end force so maybe it just by definition um gave me a force for this thought because it's taking like we said it sorts by force first uh okay how do i want to handle it well i guess of the g code and they'll never overlap with anything no that's not true because then the number can be like um 90 to 100 or something right so we have to be able to support this case but we just wanted to put we want to sort this the other way i guess so i am very yucky today my apologies so i guess we just need to do sn instead so that it sorts the other way um and then it starts as you go to sn maybe someone like that uh evolution of bad code i suppose and i thought this was supposed to be pretty straightforward but you see me struggling this a little bit uh okay is this good again okay this is good again um let's give it a spin okay welp ah you've been hit with me half an hour uh give yourself some props for having a good attention span or maybe just skip to the end i don't know either way give yourself props uh thanks for the support i appreciate it um but yeah so what is the complexity of this um it's gonna be n log n where n is a thousand uh maybe if i just did the two for loops it'd be less embarrassing because we do a by we do a couple of binary search but constant number of binary searches each and each of them is going to be log n so this is going to end uh oops and also these two operations for um it's not binary search but it binary in section insertion something like that uh but yeah so n log n is the total complexity and that's all i have um let me know what you think about this problem i think my visualization made sense my implementation is kind of terrible though and i had some weirdness weird edge case that i did not anticipate uh enough with respect to you know the one point case i guess with the inclusive inclusivity but uh but yeah well i hope this was uh educational for you uh let's actually take a look at the solutions before i go uh but i still hope it was educational for you though um let's see what other such i mean i think i mentioned a few so uh yeah i mean we knew about before so that's fine uh band's tree that's kind of what we did um yeah uh okay yeah so we can we basically did that and that's the two ideas that they have um oh well uh yeah that's all i have for this one i think i could have done i think i tried a little bit too hard looking back though in that i try to make this like prefix something that which i generally like uh thinking about things in a prefix some kind of way because it comes in a lot more handy in different places um but i think what uh we looked at very briefly and the binary search tree solution is that if i just put the actual segment in the binary search tree then i could have just binary search for the next one and then just see if it overlaps and then look at the previous element or something like that see if that overlaps um and that would have saved me a lot more time but uh and because when you're doing interviews and um and competitive especially uh you want to keep it as stupid as possible as simple as possible because that means that you're not doing anything fancy uh and it'll get you way far once it gets hard but for the simple ones keep it as simple and stupid as possible because when you try to do things that are an overkill uh you know people are not that impressed people just get uh i mean people may be impressed if you get it right very quickly but if you mess up then you'll be like uh what's what is this person doing anyway i hope you all have a good thursday and the rest of the week i'll see y'all later see you tomorrow hopefully uh and happy lead coding happy solving and ticker mental health bye
My Calendar I
my-calendar-i
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**. A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.). The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`. Implement the `MyCalendar` class: * `MyCalendar()` Initializes the calendar object. * `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar. **Example 1:** **Input** \[ "MyCalendar ", "book ", "book ", "book "\] \[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\] **Output** \[null, true, false, true\] **Explanation** MyCalendar myCalendar = new MyCalendar(); myCalendar.book(10, 20); // return True myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event. myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20. **Constraints:** * `0 <= start < end <= 109` * At most `1000` calls will be made to `book`.
Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added.
Design,Segment Tree,Ordered Set
Medium
731,732
1,609
hey guys let's understand the problem 1609 even odd trees okay it's bit a unique question uh this question let's read the question given a binary tree name even and odd if it meet the following conditions means uh we have to say if the tree is even or tree it will be only by these following conditions so let's understand the root of the binary tree is at level zero means the root should always be at zero index okay so let it floats so yeah uh the thing is suppose I have a which would be the two then it level should always be zero okay this is the first condition now it children are the at the level index one means if I have a then it's um children should always be at level two level one sorry okay so the level should keep on increasing and as we go deeper and deep and same as would be oh that for every even index levels suppose this I have a d here and it's a even L even level then uh all noes of the level have all integers value in a strictly increasing order means uh suppose I have a value suppose I have two notes and these are the childrens okay and these are childrens of this note and these are children of these and it's on level two okay so the thing is this the value of this index should be very should be the smallest and this will keep on increasing okay this will keep on increasing and have odd integers and all these are OD integers 2 = to 1 these are OD integers 2 = to 1 these are OD integers 2 = to 1 okay this would be the condition for even and the same opposite for the or indexes okay so what can we do is uh you can just say that we are going for each level then going from left to right okay so what is the level it is simple BFS okay so we have to use a simple BFS in this um to just solve this question so let me just code for you okay so I need a CU first of all so let's make it a Cu uh in which I have root in this start okay so Q would be R okay now I need a level should be starting to zero okay now what I need is uh a flag you know a flag that will tell me U that the value that I have to check is keep on increasing or should it be keep on decreasing okay if I have a flag with one then I have to keep on checking for the increasing order and if I have a zero it means I have to keep on checking for the decreasing order okay so I need a flag which will be in the starting would be one means increasing and zero means decreasing okay let's U why Q uh n would be the length of Q and while n and we have to minus n also and if every iation I have to Simply switch the flag means uh flag Z flag to one Z means at every level I have to suppose in this I have one then I have to make it zero then I have to make it one and suppose I have to make it zero these are the flags and these are the levels as I keep on going in the level then I have to change the flag also okay it will tell me the increasing or decreasing okay so and I have to increase the level also okay these are the conditions and now let's go for the conditions okay let me P the L from the que of the top bottom node okay or the first node then I have to check for few conditions and for uh suppose um suppose I have few values okay and I have to check for if these are in increasing or decreasing with only one iation so what I will do is I will take a pre which in the starting would be minus one okay now if I'm standing here I'll check is my pre minus one if yes then I have to Simply make it the same as a value then I will check for this is my threee is less than or equal greater than according to the increasing or decreasing okay if my flag is one suppose my flag is one then I have to check is my pre previous node is less than the current node okay if it yes then it is a true okay for this if it's true then I have to make a reverse condition okay to make it false sp Let me let me just go for you uh I need a pre first of all um if um f 3 = to minus one then what I um if um f 3 = to minus one then what I um if um f 3 = to minus one then what I have to do just simply uh change the value of previous value it would be no do okay else uh if soor I can do this else okay now the conditions if my flag equals to one and uh previous is less than node do well then it is a correct we are going in a correct direction but we have to check for the I'm checking for the false condition okay so I'm just making it false and make it false and say here Al flag equal to Z and p is less thanal to no do well and I have to return false okay you two condition that I have to check either it is uh keep on increasing or decreasing if I found something that is decreasing then I will return false and the flag one and if the flag is zero then I have to check for keep on decreasing values increas keep on okay what I do is um I just uh come make the previous note to the current note then I will check if I have check for even the odd indexes and the even indexes okay is the odd value or the even values if 11 mod 2 = to Z and if 11 mod 2 = to Z and if 11 mod 2 = to Z and node well to = to Z then return what right okay these are the conditions that I have to do and simply just if node do left then U do no do left and what I have to do is Dri right okay so this is the code and if it all satisfi then in the end I have to return okay will be not Z like = Z okay the thing is I'm one submit this yeah it's been submitted and it will accept yeah it being accepted so yeah this is the main concept behind this I'm going for each level and from left to right I'm checking if it increases or decreasing according to the flag and the Lev okay this is the main concept behind this you understand this
Even Odd Tree
find-all-the-lonely-nodes
A binary tree is named **Even-Odd** if it meets the following conditions: * The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc. * For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right). * For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right). Given the `root` of a binary tree, _return_ `true` _if the binary tree is **Even-Odd**, otherwise return_ `false`_._ **Example 1:** **Input:** root = \[1,10,4,3,null,7,9,12,8,6,null,null,2\] **Output:** true **Explanation:** The node values on each level are: Level 0: \[1\] Level 1: \[10,4\] Level 2: \[3,7,9\] Level 3: \[12,8,6,2\] Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd. **Example 2:** **Input:** root = \[5,4,2,3,3,7\] **Output:** false **Explanation:** The node values on each level are: Level 0: \[5\] Level 1: \[4,2\] Level 2: \[3,3,7\] Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd. **Example 3:** **Input:** root = \[5,9,1,3,5,7\] **Output:** false **Explanation:** Node values in the level 1 should be even integers. **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `1 <= Node.val <= 106`
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
563,1005
1,217
That's all Hello everyone welcome back to my channel today were going to discuss the problem is minimum cost to move chips to same position its very easy problem butter concept is very good so let's see what problems we have and ships where the position of IS CHIP IS POSITION I HAVE TORCH LIGHT VINNY TUNG ALL THE TIPS TO THE SAME POSITION IN ONE STEP WE CAN CHANGE THE POSITION OF COMMISSIONER CHIP FROM POSITION I2 POSITION OF TO OR POSITION OF - 263 AND SUBSCRIBE TO OR POSITION OF - 263 AND SUBSCRIBE TO OR POSITION OF - 263 AND SUBSCRIBE TO IT WILL GIVE HELP 2051 AND SUBSCRIBE ONE From Position I Will Give Costume To You Will Need To Remove All The Let's Understand Problem That Lipstick 10,000 From Position Reduce That Lipstick 10,000 From Position Reduce That Lipstick 10,000 From Position Reduce Position Suddhowala Position It Is The Volume Two Three D Joe Position Digestive One Two Three Position Restorative Chips Thoughts 821 Kum TOO'S NEW TOXINS A TASK TU ALL THIS IS TOO ONE POSITION IS PAIN E TO SHOOT LESS HAIR AND OTHER GOOD WORK TORCH LIGHT TOO WE NEED TO TELL THEM MINIMUM COST NOW HOW TO STITCH DEFINE THE EFFIGIE AF IS THE CURRENT POSITION Fiber Glue Two and Three Two Like and Subscribe 280 Ki and Figure Add One and 20 Plate Improve One Step Ahead or Wave Step Back and Will Give Equal to aLove Letter I Will Know Problem Solve What We Will Do It Will Be Moving Bto Tips Hair Hai Tu Yaar Movie Dhoom One Step What Means The Current Position Video 5 - 105 -1.3 Lee - World Bittu Video 5 - 105 -1.3 Lee - World Bittu Video 5 - 105 -1.3 Lee - World Bittu Sudheesh Two Tips Will Go Near To Avoid To Switch 142 Chipset 52122 So This Scene From Distant K Out This Is Stupid So They Can Also Be Set Free Movies Free Chips To Parishad Teen To Worry About Your Beloved And * * Will And In The State Will And * * Will And In The State Will And * * Will And In The State Will Go To Three Liberties Pet Will Question Is Great And 222 Returns Minimum Cost Subhash Viewers Shifting Btu Kuber Hai To Aayi Hogi Odds Test Tour Input Output Don't Worry For Not Getting Approach You All The Best And Wants A And Width Very Illegal Approach Gather Possible To This Topic See So Let's Celebrate Hadith Hai Lahariya Retired This Point Hai To Ephesians Fiber That CRPF And To Improve 520 Upright With Cost 0 Ki and Effigy Hai to Eighth and Again Prank 1a Ki Behen Fifth Class One So No Need to Know Which Position Will Be Keeping Up with the Position From Position in the Lake to Position Final Position Good-Good I Want the Final Position Hai Torch Light i want to be the final position dubai dat ki which means all also elected tis e to m 3 ki indicators 22182 question effects over your this teachers and over into tears effect diet want to be i want the final position will government even into water drips 3000 1000 subscribe Video from this one that झाल झाल झाल feature hai tu from this what we get from get attracted to get a good day main ine but i want the final position 2110 is P55 is even no problem no cost ka abhi aas final try And this oil do I will dare I will have to go to the ship which will go to the final finally Bigg Boss main to Bengaluru final position only one and went UPTO 5000 court violin opinion * went UPTO 5000 court violin opinion * went UPTO 5000 court violin opinion * * Arvind Singh and * Arvind Singh and * Arvind Singh and similar in Delhi but its final position liquid liner 6 days ago232 views 259 2012 56001 between 1000 ads hello friends smart together brave what is the final position has given a hai idhar pfi is jeevan mein a low cost a letter and its pure form in opposition has given only but your fit third 20 You Will Have To Switch On The Right Development We Are Going To End The Last Article Supportive 12328 18182 6 York Times Does But This One Day 116 Chi Method Cash Deposit On It Final Position Easy 157 Definitely A Point And You Will Not Possible To Torch Light Poking Iodine For Electrical Yadav And Final Position In The 5th That Daily Use Hee In Award Shows Means Less Than What You Rent From Three To From Which You Want To Reach From C-25 Gillard To In Delhi Which Means When C-25 Gillard To In Delhi Which Means When C-25 Gillard To In Delhi Which Means When You Reach To the notification wedding to so otherwise speed 512 ki lete oct sudhir voting tour from if you want to listen to panch this lad for * * * * * * no this lad for * * * * * * no this lad for * * * * * * no cost because you are doing to medium to low cost but when you need to reach from Photo 50 28182 That Badwani Was Cost 155 And Cosmetic Act Is To Ayurveda Want From You Got Introduced In More Trends Which Will Get Is That Is Pay's Exit Poll Defense Life Secure Final Position Thinking Is 115 The Appear For Even No Cost Final Position In China hua tha but profile award dene wa hotspot on this point se 1 inches resignation final position is not a loot any of your choice award main tere bina cost but if you find even be equal to ki tum logic airplane ho gayi hai se this is the mean Approach Which Means To Speak Now Let's Take Another Taste Take Off A Plate Yudhishthir Vacation Super Different Aspects Lipstick 462 318 The Elected As 462 Atin 15000 And Share And Different Aspects Of The Great Warrior Behave Like Position 12345 Take And Drop Tips This Seventh Tip Posted on 20 Sep 6 2013 पुन 2013 पुन 2013 पुन इंच है की की की Navneet To Calculate Which Will Be A What Is Of In Opposition Should Be Worshiped Even Total Cost Also Number Of Lord Position Because All Subscribe Final Position Is Just Not Mean That Position On And Even position tips I hope you are getting less is so simple it's very simple now just simple things with me to just calculate how many even numbers in this we give them and na de to even numbers in this position are this 123 one chord numbers in This position airways 1234 soft effect final 12424 number two how to come to reddy bandhu good morning 12.21 tight it cost but as 12.21 tight it cost but as 12.21 tight it cost but as you fix position to final position 3151 position 212 mode of the year award function finally only which will give 21 hai to so nak isko Cost is opposite that suited depends upon how many even numbers where pencil we go in noida what ever The Amazing minimum number one dead to dooba court to sharp answer for kids and beautiful to basically a affected approach the code very simple pleasures due to find how Many Even Numbers Aa Jaye Hamari Aur Damage Hai Jagdish What Means To Understand Things Which Is The Preparation To Exceed To Not That If U Ment For Tak Water Can You Understand It Developed Agendas And Visits To A Dysfunctional Give Worst Position Actress Give Winners Were Taken 2001 Hot and Where Going to Cheese Pages of Creating This Edifice Edit to three layer checking even if not effective work in preventing the invisible and if they cultivate thought for improvement in the heart and detergent water to minimum balance between even not that show in this year This video is made for cooking ₹5 and spirits pimple time click ₹5 and spirits pimple time click ₹5 and spirits pimple time click tips very simple staff and don't thing that you will show a flying jatt video please like and share with your friends and electrical department of fuel is very interesting problem thank you
Minimum Cost to Move Chips to The Same Position
relative-sort-array
We have `n` chips, where the position of the `ith` chip is `position[i]`. We need to move all the chips to **the same position**. In one step, we can change the position of the `ith` chip from `position[i]` to: * `position[i] + 2` or `position[i] - 2` with `cost = 0`. * `position[i] + 1` or `position[i] - 1` with `cost = 1`. Return _the minimum cost_ needed to move all the chips to the same position. **Example 1:** **Input:** position = \[1,2,3\] **Output:** 1 **Explanation:** First step: Move the chip at position 3 to position 1 with cost = 0. Second step: Move the chip at position 2 to position 1 with cost = 1. Total cost is 1. **Example 2:** **Input:** position = \[2,2,2,3,3\] **Output:** 2 **Explanation:** We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2. **Example 3:** **Input:** position = \[1,1000000000\] **Output:** 1 **Constraints:** * `1 <= position.length <= 100` * `1 <= position[i] <= 10^9`
Using a hashmap, we can map the values of arr2 to their position in arr2. After, we can use a custom sorting function.
Array,Hash Table,Sorting,Counting Sort
Easy
null
1,846
hello hi guys good morning welcome back to a new video this maximum element after decreasing and rearranging I hope that you guys are doing good I hope that Changi now let's go see the it has been asked by Amazon not pretty much uh just in last one two years and not much frequently let's see uh it's marked as medium but it's a pretty easy question uh that we given a positive integer array called as ARR and we have to perform the operations possibly none on are so like number of operations are not needed here you'll go and see uh now what are the operations like the thing which you have to make sure after applying the operations are the first element in the array must be one okay must be one that is one thing which you have to make sure right we'll make sure that and also the absolute difference between two adjacent elements should be less than equal to 1 which means if I have two elements right here so either they can be same or they have a difference of one are in why not 2 one because like you saw that the first element must be one so I'm just considering this is the first element and then the next element I'm just picking okay it can be a one or a two but Max to Max it can be a two now there are two types of operations which we can perform that first just decrease the value of any element of ARR to any smaller value so I can just decrease the value that is one I can decrease the value and other is I can rearrange in any order which means I can just do the rearranging in any order I can just do the shuffling now I have to return the maximum possible value now if you just go and imagine the same thing now this are the two things which we can achieve starting because it is a starting value so we know very well sure that we can achieve these two formats either same or more now if I want to achieve the maximum possible value then it is evident right that if I have four numbers so I will always try to place the maximum possible value one next maximum possible values is two although I can also place a one here but I'm saying okay I'll just try I'm trying to place the maximum possible value okay if it is three now like I can place a three which is the next possible maximum value next I can place a four so you saw that okay I'm just always trying to place a next possible maximum value which is nothing but what the value I had previously plus one but I okay so with this concept your answer should have been and uh like whatsoever the side of the array is that should be the answer which is n so is that the answer I'll say no because here I just assume that I'm putting a one and then I assume that I'm putting a two I did not consider the array itself I have my array as a benchmark what if my array itself has an element like 1 uh 4 like 1 8 and 9 so if my AR had an element like 1 18 and N so no matter what I do I cannot make this one or two I cannot increase a value let's say it was the aray element I'm hoping my array should look something like this finally so as to obtain the maximum element is four but for that for sure I need to increase 1 to two that I cannot do so I have to take minimum of what I have and I and what I expect to be so for sure what will happen is this will modify to one now if this modifies to one for sure the later part will also be modified right so the later part will actually become now okay what's the previous value I can just increase that value to one okay previous value was one add a one you can obtain a maximum value of two here now so how we got this by just saying okay what's thee what's the previous value just have that value which is pre like previously to us just have that value which is previously to us and then add a one to it and same I just can say Okay previous value is two I can add a one I can get a three so this is how we can get the new maximum value again make sure that whatsoever you are expecting I expected a two but I have a one so I have to take the minimum of both of them and then I have to place a one here so now I'll say okay at this location which is a r of one I'll place a one and then moving forward I can use this previous value which is prev to actually compute the next value so this next value will be nothing but my prev value + one again when I just my prev value + one again when I just my prev value + one again when I just take minimum of both of them minimum is again two so my prev will become a two and then this two will actually make sure I use when I'm Computing for the next element I'll make sure that this next value will be nothing but prev + one so it will be 2 + nothing but prev + one so it will be 2 + nothing but prev + one so it will be 2 + 1 is three and I'll take minum of three and 9 okay I get a three and that will be my answer so I'm just trying to modify my input but RN okay now also you imagined one thing you considered one thing that it is sorted can you sort it yeah I can rearrange the elements of error in any order so what I can do is I will simply sort this stuff out which is 1 2 now I'll start from very beginning I know that initially I can have a zero as the previous because I know that if I will add a one in my previous it will actually become a one so I know okay I just simply add a one here so now my element which I have to compare which is next element this is the next element it will actually become a one which means simply adding with the previous simply adding a one to my previous was zero so now I'll just compare one and one minimum is one simply okay the current element I'll replace by one cool I just go on next I'm expecting to have a two but I'll take minimum oh bro it's a one sorry bro sorry I'm really sorry it's a one minimum is one so for sure I can only place a one here I'll place a one here cool I'll go next I'm expecting a two now okay minimum I took minimum it's two okay I'll just leave it here now expecting I'm expecting a three I'll take minimum uh bro three you cannot have the two is maximum you can have okay cool place a two next I'm expecting a three because just is it is a previous plus one I'm expecting a new value higher value previous plus one take minimum bro again you cannot take a two expecting a three oh it's over cool last element was AR of nus which is the maximum element I could achieve was two same for this example 100 and th000 I was initially the per was Zero I was expecting a one minimum I took it's a one okay cool move ahead I'm expecting a two minimum oh two is possible cool move ahead I'm expecting a three minimum okay three is possible move ahead answer is three for this case 1 2 3 4 5 same the per was Zero initially I am expecting a one yeah true go ahead expecting a two yeah true go ahead expecting a three yeah true go ahead expecting a four yeah true go ahead spting five yeah true go ahead thus simply just check what's the expecting value just say Okay previous Value Plus one is the new expected value take the minimum of the current value of a of I and the value which is previously and just simply have your answer let's quickly and see it's just o of n uh we are not using any extra space so that space will be o one itself cool uh let's see it's pretty simple firstly as we saw that we have to uh sort our entire array which is AR do begin and AR n because we know that we have to like first we can rearrange that in any order and also we want this to be beginning with a very small value so that we can compare the small values now I know that I need to have a previous so I'll just have the previous with a zero now I'll go on to every element in my ARR now I'll just have uh say to that element that bro uh just do one thing um just check what is the current minimum value so for sure that minum value will only get placed here so I just say bro minimum value is my current value which is this element um or I can just keep it by address so this element will be nothing but AR and let's also have the N so that we can actually get that last element in just by just saying okay AR of n minus one so I just say that the current element will be nothing but minimum of the element itself and also the current value which I'm expecting which is pref plus one I'm expecting a pref 1 and for sure uh please put the prev as the element whatsoever you have got ultimately simply return the rror of nus one and that should be your answer cool let's see let's quickly have this running yeah and by this you can simply get this solved I hope that you guys got it right byebye
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`. There are 2 types of operations that you can perform any number of times: * **Decrease** the value of any element of `arr` to a **smaller positive integer**. * **Rearrange** the elements of `arr` to be in any order. Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_. **Example 1:** **Input:** arr = \[2,2,1,2,1\] **Output:** 2 **Explanation:** We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`. The largest element in `arr` is 2. **Example 2:** **Input:** arr = \[100,1,1000\] **Output:** 3 **Explanation:** One possible way to satisfy the conditions is by doing the following: 1. Rearrange `arr` so it becomes `[1,100,1000]`. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now `arr = [1,2,3], which` satisfies the conditions. The largest element in `arr is 3.` **Example 3:** **Input:** arr = \[1,2,3,4,5\] **Output:** 5 **Explanation:** The array already satisfies the conditions, and the largest element is 5. **Constraints:** * `1 <= arr.length <= 105` * `1 <= arr[i] <= 109`
null
null
Medium
null
987
hi guys welcome to algorithms made easy today we will go through the day 7 problem from august lead coding challenge vertical order traversal of a binary tree please like the video and if you are new don't forget to subscribe to our channel so that you never miss any update given a binary tree we need to return the vertical order traversal of its nodes value for each node at position x comma y its left and right children respectively will be at position x minus 1 comma y minus 1 and x plus 1 comma y minus 1. running a vertical line from x equal to minus infinity to x equal to plus infinity whenever the vertical line touches the same node we report the value of nodes in order of top to bottom that is decreasing y coordinates if two nodes have same position then the value of node that is reported first is the value that is smaller return a list of non-empty reports in return a list of non-empty reports in return a list of non-empty reports in order of x coordinate where every report will have a list of values of node let's take this tree and find the coordinate of the nodes for that let's take a grid where we have x and y coordinate as shown the root will always be positioned at 0 comma 0. 9 and 20 will be 1 level beneath the root and one step left and right to the root respectively so with respect to the root nine will be at x minus one comma y minus one and twenty will be at x plus one comma y minus one similarly for this two till now we got one node at one coordinate now let's take two more nodes and see the effect on the coordinates with this we can see that there is an overlap in 0 comma minus 2. as we need to add all the node values in same line in one list we would get a result as shown here there are three things to remember or you can say three points to consider first the ordering in the result is primarily done on basis of x coordinate starting with the smallest one second for the values in same column the ordering is done based on rows from top to bottom fashion and third for nodes with same x and y coordinate the one with the lower value must appear first so the sorting in this case will be based on the value of node summarizing we need to perform sorting on three parameters x y and value to make this simpler we will create a custom class and implement a custom comparator or comparable interface that suits our sorting requirement the class will have three parameters x coordinate value y coordinate value and the node value let's call this class as location and the implementation of the comparable interface will look like this in this we have overridden the compare to method to sort the data primarily based on x in ascending order then on y in descending order and lastly on value in ascending order now that we have a data structure we need to travel the tree and store the value in it so we will take a list of location and traverse the tree which can be done using either bfs or dfs in our case let's use dfs i have not shown the entire tree traversal in this video so as to keep this one brief you can find the similar video link in top and in the description to get an idea of tree reversal while reversing we will store the location of each node in the data structure created so for root node the value of x and y will be 0 comma 0 and the value of its child node would be in respect to the root node the left child will have the coordinate x minus 1 comma y minus 1 while the right child will have the value x plus 1 comma y minus 1. this would be the value for each node the list of location after dfs traversal will look like this now we would sort the list to obtain the data in correct order after sorting the location list will look like this we have the data in correct order now we just need to correct the format so we will prepare the result list from a location list by iterating through it all the values with same x coordinate would fall in the same list so we need to compare the x coordinate values in each iteration and bring the same x values together if x is same we would need to put the values in same list or create a new one so the values will get combined in this manner at the end we return this result list summarizing the steps we will create a custom class called location with x y and node value and add a custom sorting to incorporate sorting based on x y and value we can either use a comparator or comparable for this we will initialize a list of locations and apply bfs or dfs on tree and store the location for each node in list after that we sort the list using the custom sort for the class we now iterate over the location list and check if current x coordinate is equal to the previous x coordinate if yes we add the value associated in the same list otherwise we create a new list and add the value in it at the end we return the result list the time complexity for this algorithm is of n log n while the space complexity is of n here's the actual code snippet for the method you can also check out the link to this code in the description below thanks for watching the video please like share and subscribe to the channel also let me know in the comments what you think about the video
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
309
hey what is up everybody welcome back to my channel this is a part two of um the problem 309 and uh previously we had an intuitive attempt trying to solve the problem by breaking uh this stock buy and sell problem into sub problems um by you know cutting the entire array of prices into different uh smaller chunks but looking at you know where we had like uh um by looking at the specific places where we had like a temporary one-day we had like a temporary one-day we had like a temporary one-day uh price drop um that was kind of like an intuition but it's way more problem specific and it didn't turn out very well so um we ended up looking at solutions and trying to follow from the solutions and uh one of the solutions was similarly using dynamic programming but the explanation was a little bit vague or confusing to me so i actually did it uh did some um learning offline now i'm prepared um and i got some slides actually to show you my upgraded understanding of that solution and hopefully my solution is more intuitive at least to myself and explaining you know the combination of using dynamic programming and state machine to uh basically decompose this problem and solve it using dynamic programming all right so let's uh take a look now this is the solution that we were looking at and so let me just remind you what we're doing here we were doing uh we're doing the uh best time to buy and sell stock with the cool down so unlike the previous buy and sell stock problems now we have to actually go through a day of cool down which is like doing nothing and wait until we can buy again on the next day uh so then we looked at solutions and this approach one dynamic programming with state machine was the one we looked at and uh you know although these state transitions were kind of making sense you know this table of you know deriving things was a bit confusing to me uh but then i just you know uh thought about it offline and now i think uh i figured it out so i'm gonna share with you what is my understanding of what this is okay so now let me now um switch to my own slides that i prepared for this uh for this problem all right so if you remember we had a uh example one where we had a five-day uh example one where we had a five-day uh example one where we had a five-day uh stock price list uh one two three zero two right and we start basically from day zero and we can basically either buy or just you know wait right and uh and this is like the three states that i'm defining actually let me start by defining i'm gonna just make a brand new slide and start um showing you guys what i mean by these three states right so i'm gonna actually go here and make stuff on the go we have empty we have frozen we have holding those are the three states that we have right and now let me just make them a little larger not really okay let's just do it like this so when we're empty of course we can uh we can you can go from empty to holding by yeah the color is fine by what by buying right so this action here would be called buying so if we buy we go to holding uh and if we stay in empty like we don't do anything while we're empty uh oops yeah something like that or something like this yeah that is when we're like uh not doing anything right so it's like uh hold or you know rest right and while we are holding we can actually still keep holding so once we're in holding what we can do is that we can keep holding the stuff right hey this is better i wish i could add more points here uh how do you do that actually add more points uh um for my shape i don't know how you add points to it alt shift control doesn't really work okay all right fine um then we're just gonna say that if we rest we're gonna stay in holding but also we can go from holding to frozen by selling right so if we have a cell action instead um we can go from holding to frozen uh so we have a one day freeze right and after our one day freeze we'll definitely go into empty right yeah we're definitely going to empty oh let me just yeah put something there we'll definitely go into empty and that is by the action of uh rest we just wait right basically you just rest and uh you will go into empty actually you know what let me just put this here it's a little weird looking that way but anyway this is what we have right now okay like this maybe let me just make things a little bit uh normal yep this looks better right so this is our basically our state transition uh so now let's go back into presentation mode and uh because this looks better right we have the state transition like this so we have three states and we have basically three types of actions rest buy and sell and they're not like totally symmetric for example you cannot stay in frozen state all right so now let's switch to this uh tabular view where uh we can be switching among these three states but we're also looking at the state on each day specifically and we're basically uh comparing that against the price for each day so that it's easier for us to calculate what's happening uh anyways um so um if we just look at it this way we can solve this by uh so-called dynamic programming in a uh so-called dynamic programming in a uh so-called dynamic programming in a forward direction it's um but you know what when actually when i was like learning about dynamic programming you know in terms of a theory uh people i always uh learned it as like a backward direction algorithm i'll explain that difference in a bit but let's just you know stick with the forward direction which is more suitable and intuitive to this to the stock buying selling problem and then i'll show how it could be generalized or equivalent to uh the more usual traditional backward dp uh in that form so now let me just start on this and uh because i'm now going to start some editing i'm just going to switch to this editing mode right and what are we do we're looking at here so if we compare what we had before in this transition uh for among the states and we look at it here um let's start from day zero and because we're going forward we're gonna basically examine what is possible and what is not on day zero okay um for example let's see if on day zero it's possible to just stay empty uh yes of course we can right and uh is it possible to be holding on day zero no because holding means that you already have some stocks if you don't have any stocks it does not qualify as holding so let's be you know actually more specific uh on that so this empty leg has stock you know this is like no stock right when you're empty of course that means you have no stock oh let me use a different font maybe let's choose yellow yep so that means you have no stock if you're holding of course you know you definitely have stock right uh but when you're frozen of course that means you have no stock as well because you just sold something so you have no stock uh therefore at the beginning of the um day one because we haven't bought anything yet um uh so um we cannot be in holding position so i'm just going to put it put an x here meaning that it's impossible also we cannot be frozen because frozen uh only happens after selling right so i'm not going to say this is a frozen state because this is literally just day one we haven't saw i haven't sold anything yet so the only possibility is to stay in uh empty state right and then that's it and we're gonna move on to day one using zero indexing right because in zero indexing the first day is day zero and the second day is day one all right so on day one let's see what can happen um well on day one we also i mean uh let me just put down something here as well you know we use we're gonna use we're also gonna track our cache right track a cash at each state you know at each on each day yeah uh you know before action before and before any action before taking action right so here is here's what it is on each day we can take an action either we hold or we sell or we you know buy right but there's definitely like an amount of cash in the morning you know before the market uh like just when the market you know uh starts or even before the market starts you're going to have a certain amount of cash in your hand and we're going to track that we're going to use that number and we're going to write that number into um into the circles here so on day 0 you can buy oh that's you can buy uh you can also um uh let me just actually make the text black that way yeah you can see them uh on day zero whether you try to buy the stock at price one or not um before you take any action your value is at zero right so we're going to write our zero there um and actually i'm gonna make a modification to that say track our maximum possible cash each day before taking action and that when we use the keyword maximum this is where you know dynamic programming comes in and we will find that sense will make sense as we go on all right just so just now trust me we're gonna use this number to represent our maximum possible cash uh each day before taking taping the taking the action on that day so this is going to be uh definitely zero right because on day zero whether we buy or not you know uh in the morning we're gonna have zero asset um well then on date on day one let's take a look at this empty state is it possible that we are gonna be empty on day one yeah of course so why is that possible we're gonna start using some arrows to draw why it's possible because if we didn't buy anything on day one on day zero and uh we just you know don't do anything and just rest we're gonna have a value of zero uh on uh in state empty on day one uh but there is another possibility because if we look at our transition um like state uh state machine here another way to uh go to empty if is if we were frozen previously right but is it possible that we were frozen previously well um you know what because this is impossible so you know although theoretically it's possible but in reality because we couldn't be in the frozen state on day zero so this is like impossible so the only value that you know this value uh can take is value zero okay let's move on to holding so we ask ourselves um is it possible to be holding a stock on day two on day one sorry on day one yeah it's possible if we had purchased the stock you know before day one right um so that is possible and we're gonna just start drawing the line so um it's possible if we were like previously holding right but because this is impossible like we cannot be holding on day zero so this arrow is now just no meaningless but there's another possibility if we just bought the stock on day zero l as uh as the action on day zero then we would have acquired a stock uh at the price of one uh on day zero and now in day one we will be holding and what is the value what is the cash value we have right now what for if we're not selling anything then we are still gonna have um uh well because we have spent you know if you buy something now you're all you have is stock right but your cash drops so actually it's going to be minus one here why because you need to spend some investment in order to obtain the stock right so on day one you're gonna have one stock but then your cash flow is minus one so that makes sense okay so that's all the ways that you can uh be holding on day two let's take a look at frozen is it possible that we are frozen on uh on day one well in order to be frozen the previous day has to be a selling action and for the previous day to be a selling action the previous day itself has to be in the holding state because it's only in holding state where we actually have a stock if you look back here right holding state uh is only possible if you already have stock um uh before that date right so we have to be in the holding state so it's gonna be like this and this but since this previous holding state on day 0 is impossible so we're going to call this as x which means you know it's an impossible state it's an unachievable state anyways right so uh let's move on to day two then so on day two again we start asking ourselves is it possible to be an empty state on day two well it's of course possible because what you can do is that you can basically uh um inherit the empty state like you don't buy anything uh on you don't hold anything on day one so you can continue to hold nothing on day two uh and that is going to give you um a cash value of zero since you have not bought anything um your cash is at the neutral value uh another way to stay to be in empty state uh is if you had uh excuse me if uh you had sold something on the previous day which means that you will be oh no you have sold something on the day before yesterday so then you had because you know there's a cooldown requirement right so that means like um if on day one we had we were like in frozen state then on day two we could be in empty state but since this state you know we have shown before that it's impossible to be in frozen state uh on day one so basically this line does not provide any uh alternative values for this empty state whoops empty state on day two so that's all possibilities for empty state on day two let's move on to holding state on day two so is it possible to be holding on day two well um in order to be holding there are two possibilities the first possibility is that yesterday we didn't have it didn't have anything and yesterday we actually bought something so there's that possibility so if that's the case uh so on day one we bought a stock uh at the price of two so then our net cash is going to be net cash flow or our net cash amount is going to be minus two because uh that buy that buying action uh on day one has cost us you know two dollars so we're at -2 but there's another so we're at -2 but there's another so we're at -2 but there's another possibility right if we had bought actually previously on day zero and we were holding it on day one then we can actually um you know have a net cash value of minus one and uh here is where the maximum you know here's where the uh the maximum thing comes in because um in the end we want to you know maximize our kind of like rolling uh cash on our rolling cap you know our net cash gain in the end uh we always want to maximize our cash amount at any state so we're gonna inherit uh this cash amount from uh holding on day one so we're gonna do that because now minus one is greater than minus two so we take minus one value here so again the reason of you know taking a maximum is that you know um all the actions forward can you know can be um forward in the future can be something that we decide later on and we're just you know look looking back to see what is the you know uh the maximum rolling uh net cash uh at any state uh on a particular date and that is what we're looking for like we're trying to build the maximum uh cash history we're trying to build our maximum cash history so let me just write that down here just if it makes more sense you know we built uh we built our maximum cash history his uh history yeah this is what we're doing here we're building our maximum uh cash history that's what we're aiming to do here so our maximum cash history here is now minus one now let's take a look at the third one here uh frozen is it possible to be frozen on day two well um we could because if we want to be frozen on day two that means we must be selling something on day one and it's possible because uh this holding state for day one is possible right so uh what's the value here um so uh at the holding state on day one we had an uh net cash value of minus one but since we sell uh we take the selling action on day one that's going to correspond to a price of two dollars so we're gonna have we will obtain like a two dollar uh selling reward and minus that you know uh one dollar uh um cost price uh our um total net cash uh value is at one here so one equals to 2 minus 1 right so our net cash value is at 1 here so that's for day 2. now we're going to repeat this process onward and take a look at now what is the maximum possible cash value uh just cash right at the empty state on day three so one there are two ways to achieve an empty state on day three number one is if we were in empty stating day two and that will give us a continued value of zero another way to achieve empty state on day three is if we were frozen on day two after selling something on day one right so uh if that's the case well because the frozen action during the frozen day you basically just rest and do nothing you don't have any change in your cache value you just copy this value here and since this value is one is greater than zero we take the maximum like we uh like we specified here uh we are going to use one here so that is the value for the empty state on day three now okay we move on to um holding the value the cash value of a holding state on day three and what are the possibilities well there are again two possibilities possibility one is if we were empty and we bought uh something actually uh on the previous day so that means we bought uh one stock at the price of three dollars on day two so uh today what do we have well we have minus three dollars because we had like a deficit now we just turned our three dollars into one stock uh and one other way is if we just hold if we hold on to our existing stock from a previous purchase in that case we just directly copied the on the cash value from the holding state from the previous date and that is -1 and now because -1 date and that is -1 and now because -1 date and that is -1 and now because -1 is greater than minus 3 we're going to reduce -1 here reduce -1 here reduce -1 here all right so we just calculated the holding state value on day 3. now let's move in now let's move on to the frozen state value on day 3. is it possible to be holding to be like in frozen state on day three yeah it's possible that means we were selling on day two and we could because on day two we could be owning the stock um and let's take a look at the selling value on day two it was three dollars so we had a minus one cash net cash uh amount and now we sell it we sold it at three dollars so now three minus one equals to two now we had uh now we have a net cash value of two dollars here in this frozen state on day three all right so now let's move on to the final day four for empty state again uh we're gonna take a look at these two possibilities the first one is just uh keep holding uh keep uh resting and uh keep ourselves in the empty state and the values of course wait it's not zero uh sorry about that it should be one we just inherit that value of one from the previous day right uh and then one other possibility is if we uh we were in the we were in like the freezing state uh previously uh and because uh you know spending the frozen state spending the uh the time you know in the frozen day doesn't really gain us any cash we're just going to copy the cash value here and because 2 is greater than the 1 here we're going to take 2 as the value for empty state here and for the holding value there are of course again two different values two different possibilities the first one is that if we bought something on day three uh and on day three the stock is almost free it is indeed free so uh we do not have a drop in cash and in addition we now have one stock uh so our cash value is one and then um what about our uh what if we hold on to you know the previously owned cash uh stock then we will have a value of minus one but since minus one is less than one we still take the one value uh by you know buying a stock for free from day three all right what is the value of frozen state on the last day well if it's frozen state that means we just sold something uh um uh yesterday so on day three so let's represent that with this arrow here and if that's the case what is the selling value well unfortunately if we've sold the uh the stock on day three that's the you know the worst thing that you can do you're just giving away your stock for free so you're still going to have a deficit of minus one all right so is this the end uh we're looking at you know a net cash value of two one and minus one here can we say this is the end of it no not really because you know what ins remember in holding state we're still holding one stock here right um but you know um what we can do we can still take one action on day four right uh remember we can still take that action so let's actually um uh um i guess what we're gonna do is we're gonna um use a uh let's change this color of this uh filling change the fill in color here we're gonna use a yellow as like the final value okay so our final value for being in the uh being in the empty state on day four is still two because we don't hold any stocks but if we were in like if we were in the holding state on day four then at the end of the day you know this is like day four end of day let me just say that you know just to explain a little bit more intuitively day four end of the day you can do like a plus two here because why because you have still one stock and you can still sell that stock on that day uh and then basically clear it right after declaring you're gonna have a value of three um and then what about the other one here you're just gonna do minus one because uh if you were frozen you know at the end of the day you're still maybe you're still at the same value the next day you're free but at the end of the day you still have the same amount of money so this is our obvious champion here so i'm just gonna uh surrounded by a uh by a green thick green edge to say okay this is our optimal solution right um because at the end of the day on day four we have three dollars and what are the states that leads to it well we can now backtrack uh it's gonna be this as well right and uh let me just make it thick it's gonna be this as um it's gonna be this state right um make it thick it's gonna be this state um yeah that's how we uh we went to that state right uh yes uh and then it's gonna be uh this state let me just you know give it an outline make it thicker uh and then it's gonna be this state right because these are the actions that are leading to the optimal value there so we're going to just highlight it there here we go uh and why was that because you know um for all these possible actions you know actually there was like a preferred action at each um leading to each state we should have like recorded that so actually let's run that again right let's run it over again um because we wanted to record it so for day zero it was basically like that for day one uh what's the action that you know lead to the value zero here it was this so i'm going to actually um make this thicker okay make this uh like yeah three pound thick uh and then for this one of course it was this action that led to the uh this so we're gonna just use the format painter to highlight and then for this one uh well it was this but then i mean it's a uh infeasible impossible state and for day two empty uh the value of these two empty is this one here so hey format paint uh format paint this we're gonna again format paint now for holding state on day two uh how did we get here by you know holding it for this state for the frozen state in order to get value of one we were seldom on day two right and then uh for day three uh to get the value of one we were actually taking this uh this line here and then for this holding state on day three to achieve minus one we were what we were doing we were actually uh just still resting um for this frozen state here to achieve the value of two we were actually selling right and uh for dave on day four in order to achieve number of two here we were doing the uh the yeah um the resting after the frozen state and then for to achieve the number of one here uh we were basically getting free stock on day three um and for the last one here because this is the only way you can go that's it uh right so now what are these thick arrows right so let me just uh write that down um the thick arrows meaning optimal uh decision right optimal decision at each state um or actually leading to each state right leading to each state for example yeah the optimal decision that led to this state having a value of minus one is this arrow so yeah uh so that is why when we have selected our um best value at the end of day four we can just you know backtrack these thick arrows to find our trajectory and uh you know basically find out our decisions so this is uh this is like um how using dynamic programming in a forward direction we can solve our problems and i'm going to show you actually the equation that um that represents it so the equation that represents it is the one uh on top so you have a g of x k j well what does it mean the symbol g uh is a function symbol this function is the maximum um is the maximum cash value given the state in the bracket right the maximum cash value that you can accumulate up to this point um given the state inside the bracket and what is the state well x um x of k and j um what this means is uh so x of k um it is k is like the day index or the uh is it uh no not really okay xk is like uh hold on a second yeah so k is the time index in our case we have like 0 1 2 3 4. so k equal to zero one two three four it's a time index and j um j is the actual state index we have three states so j could be zero one two uh you know depending on how we define our states so uh the k index is our time index the j index is our discrete state index uh for example if we have like k 0 j 0 and if r 0 means um uh means the state of um empty then that means okay uh at day zero we're empty so that's what k zero would mean so anyway this g function which is the maximum cash value of the corresponding state it could be we can express this as a recursive relationship and it depends on um uh depends on the uh on these following things right um first um it's a maximum like overall it's a maximum function uh and the iterator is uh let's say uh the iterator is uh you know the state we were like a day before right so k minus one means this is like a day before and i is uh you know the kind of like the state that we were uh from yesterday so then uh so in this bracket we have two compo two parts the first part is a uh arc reward so what does arc reward means it's the uh the reward of you know uh of performing an action on a previous day so for example if on day k minus one you sold a stock uh and then you landed at uh this may be a frozen state uh on the current day then your arc reward is going to be uh you know uh whatever the stock value was on yesterday so this is the arc reward and uh let's make another example if we were holding um if we took like resting uh as the action yesterday then the arc reward is of course zero like if you don't buy or don't sell then of course you're not getting cash or losing cash at all so that's what arc reward means and then plus um this uh this is the same function uh symbol plus the maximum cash reward value uh on a day before right so on day k minus one uh at the state i so again i could take three values zero one two representing the uh empty state the holding state and the frozen state so basically um this is like the uh kind of like the uh recursive relationship for your dynamic programming uh but it is somehow in a forward direction the sense that you were relying on a previous day information to calculate the current day information so you're basically going forward in time uh while you were like well you calculate this thing this these rewards in uh in a recursive manner uh and this g we can say that you know it represents the rolling reward in the past uh you know up to the state of x k minus 1 i uh yesterday so this is the forward direction but you know this is not how normally people formulate dynamic programming and the backward direction is actually how people formulate dynamic programming recursive relations which is the one below i'm going to show you next um how we could solve the same problem actually in the nominal uh representation of a dynamic programming done in the backward direction so i have a slight for that let's uh let's take a look and see how we solve this same problem uh but flipping the direction so that you know this dp problem is going to be your textbook dp problem and you if you have learned dynamic programming somewhere in this manner you will immediately recognize it so now let's get into it uh first let's uh take a look what's the difference if you go back to our forward direction you notice that we um we list the days um in an ascending order day zero all the way to day four and our price of course is accordingly uh in the correct um you know time forward order but now when we solve this in the backward direction we actually flipped uh the order of um of the days and now day four is the first one and day zero is at the end the reason for this is that you know in order to apply uh transfer or transform on the stock by this stock buy and selling problem into a standard dynamic programming form uh in the backward direction we this is what we had to do uh and i will explain in the very end uh why we have to do so and uh and that will basically explain maybe uh your question now i think you might have that question now like why do we have to do this backward uh how why do we have to flip the days so now let's just uh take this problem as a standard uh dynamic programming problem uh in which now let me just show you the formulation here uh in which this is how it uh how it works so in a dynamic programming problem uh you could either be like minimizing an overall cost during a doing a process or you can be like maximizing your overall gain in a process in this case we're maximizing like a gain so we're using the max symbol here and now this g here it has a different meaning the g what it means here is that it means the maximum reward uh you can get onward right like from now on all the way to the last day uh let me just actually write that down because this is important let me uh yeah put another label here right this is like the maximum reward onward make some reward onward uh from current state and time yeah so this is what this uh this g means and uh let's just do it that way make it a white uh well previously our g when we were defining our problem in a forward direction it meant um our maximum reward uh you know maximum rolling reward so far uh um at this current state and time right so these are different slightly different but you know in fact they've been quite different things previously the maximum rolling award so far at this current state and time is the accumulation from all previous histories right up to this time and when you know in the standard uh dynamic programming backward direction what we would like to uh calculate is the maximum reward onward in the future uh from the current state and time on like if you land at this state you will be certain that you know the best thing you can do in the future uh until you die or until at the end of the game is that much and you and that's it like there's a limited future i mean there's a limited future of games that you can achieve and um basically that's your cap that's your ceiling that's your cap right um so it's like okay it's not very exciting but you know it's a certain thing that you can rest a certain um that you know if you're at that state uh then the g value at that state is the maximum amount of reward you can ever get moving onward if you don't screw up or actually if you perform your best yeah that's what it means uh to be the g or the maximum reward onward from the current state and time in the standard uh dp backward direction definition whereas previously this you know variant this actual variant this forward direction variant yeah let's just actually call it variant forward direction variant in this variant rg was defined as the maximum rolling reward so far at this current state and time so it's like the wealth or the money we've accumulated so far if we're in this state at this current time and the future we don't know the future could be sad could be really awesome but we just don't know right so that's why i say that you know to compare these two um directions you can you know casually just compare it as investment versus work you know in the world of working you know like you know if you work hard at the end of the year you're gonna get x amount of salary and if you work very hard and you get promotion all the time uh until the day you retire there's like a cap right there's like a maximum amount of money you can make by working very hard making all the right decisions uh you know uh work your relations with your supervisor and whatnot you know do your best at work uh that's the maximum amount of reward you're gonna get um uh until you retire right or until you die uh so the this is like the conventional dynamic programming uh perspective actually why not let's just you know call it the work perspective of dynamic programming right so yeah work perspective that's a first okay that's my invention now it's official we're gonna call it work perspective dp uh and then this forward direction variant is actually the invest perspective of dp so yeah so this is where you are like kind of like your own boss with your own money uh and uh you're looking at you know what is the maximum reward i have at this current step and uh the future is something um the future is something uncertain and we have to you know uh recursively calculate to basically to find out the answer whereas you know in the work perspective dp you know you kind of like start with the maximum answer or like the uh the best result already and then you just calculate backward till the current time uh and basically your objective is to you know to not screw up uh that best reward that you kind of already knew ahead um but then in this forward direction uh if you're making rewards then you always start looking at you know what's the current uh what's the current rolling reward and what are the actions you know in the future that can they can you could build up my uh asset and build up my uh maximum reward onward so yeah so this is how i can best explain um this new variant of forward direction and backward direction um okay so back to you know i'm going to walk you through this uh expression uh a little bit so in the traditional or conventional dynamic programming expression uh if we're talking about rewards then the reward at any uh time or any day k uh within the state i is going to be um the maximum of all possible combinations of arc rewards and uh you know maximum onward rewards i'm gonna remain this uh onward reward right in the future uh rolling reward onward reward yeah so um max reward yeah let's call it uh onward reward or best reward how should we call it best reward in the future you know just onward reward okay onward reward right uh the best onward reward uh from uh next state uh on the next day plus the arc reward by taking certain actions on the current day which leads to the state j on the next day on day k plus one so in principle these two are the same i mean if you flick flip the time direction uh one expression becomes the other so um it's just that the backward direction expression is more popular is and it's how bellman i think back in the 1950s when he invented this algorithm of uh bellman's principle of optimality uh came up with so this has become this becomes like the uh established expression of dynamic programming and now we're going to solve the same problem now uh in that fashion so now okay with all that explained now let's look at the problem again we have uh reversed the dates and then we're going to basically change our perspective and think of the reward in a different way now we're looking at the maximum reward onward from current state and time and we're going to start from the last state and so on this empty state on day 0 we're going to basically ask ourselves right what is the maximum onward reward now onward means looking back right because now time has been flipped so onward means you know going to the right but there's no more um days to the right so uh so it's gonna be actually uh empty so we'll be at zero well let me actually now do a little bit of a change here make the text color black yeah so it's gonna be zero and for holding uh first let's check if this possible if this state is valid um if this is like in holding state then um then you know a day before right onward which in other in uh in other words a day before or yesterday we must be having some stock but that is impossible like right this is like the initial day already and a yesterday we couldn't be owning any stock yesterday so this state is uh is impossible same thing with the frozen state because in order for the frozen state to be possible uh then yesterday we must be selling but there's no yesterday after this right this is it literally the initial day so all right we have zero action x so moving on to day one uh is it possible to be an empty state well uh if we want to be an empty state that must mean that we um uh we either were empty yesterday or uh we were in frozen yesterday so those are the two possible um possible scenarios and we actually want to you know draw these arrows now in this direction because it's almost as if we're making a decision and we're going to land at the state although the decision was actually made yesterday now we reversed the problem uh we inverted the problem and now we want the arrow to kind of like um now in the reverse direction as well so these are the two possible uh scenarios uh and uh because this scenario is impossible so the only scenario possible is going from empty from yesterday to empty today and so we're gonna assign again zero here and holding on day one well um there are two options right again uh if we were holding yesterday like this arrow if we were holding yesterday then we today we can just stay rested and keep holding but this is impossible right we put an x here but another possibility is if we were empty yesterday and we actually bought something yesterday so this is the arrow and it's possible and we need a cash value of one to buy that stock so right now our maximum onward reward is going to be uh minus one in this case is it possible to be frozen well um the only way it's possible is if we've sold something um yesterday but since uh on day zero we couldn't be holding there's nothing to sell so this is basically impossible we're gonna put an x here all right day two uh empty state again it's possible uh there's two possibilities one is like we keep um resting and uh by holding nothing and this will give us a continued value of zero or the other possibility is if we've sold something on day one and that is uh infeasible so we basically just have this one value here for um the holding state is it possible well it is we could either just keep holding and then we just use the same value uh same maximum um onward reward of minus one here or we could be uh buying something uh yesterday uh and that would give us a value of minus two because the price yesterday was minus two but then minus two is less than minus one so we still take minus one here what about this frozen state well uh if we want to be frozen on day two then on day one we must be selling so that's the only possible way that this can go and what is the maximum reward onward well um you have to take uh um the stock as being like already sold and so the onward value is going to be one because uh there's a minus one net cash amount but then because a selling action was uh performed on day one uh so actually moving onward you're going to have a value of one here so now let's move on to day three for empty there's again two possibilities one is just you know keep resting and uh we keep the value of zero or uh we could be uh coming from like a frozen state uh yesterday and uh because frozen state is not going to change anything in terms of cash amount so we actually would have one dollar cash instead of for empty as the maximum onward reward so we'll take one there for holding again there's two possibilities one is that we continue to hold on the other one is if we uh bought something is if we bought something on day two so if we continue to hold that's going to give us a continued value of minus one for holding but if we bought something on day two that would cost us three dollars and plus the existing character value of zero that's going to be minus three it's gonna be less than minus one so we take minus one instead for frozen state on day three there's only one possibility that is uh we sold something on day two because the price was good three dollars uh with existing cache amount of minus one we will get a value of two here now let's move on to day four last day uh again for empty there's uh one possibility of just you know staying with that uh mtm uh empty value on day three which is one or we could be selling on day three which was really a bad choice because you would be like uh basically giving your stock away but you know what um because this is a pretty high value even if we just you know sold our stock for free on day three following this uh we will still have like a value of two so it's not that bad but uh can we be holding on the last day yeah we could and uh one possibility is that we just continue to hold what we already had uh with that one stock or we could be you know selling something on day three which was uh which was pretty bad right like we were selling on day three uh if we were selling on day three then um sorry buying ah i'm sorry buying but not selling buying uh because now day three if we were buying at a zero value we basically got a free stock and we're gonna inherit that uh cash value of one so it's a pretty good scenario here we have one stock and we also have some cash and frozen uh for day four to be frozen we had to be selling on um on day three right and that was a pretty bad choice because uh we gave that uh out for free well i was wrong about you know this line here let me just redo this line so for um for this day four to be empty the second alternative was to just stay idle during a cool down on day three and we basically don't have any change in our um in our cash value so that's why this uh highest value here was two so i just corrected what i just said uh all right so we now have the full list but is this everything well not really right because again we need to on the last day we need to clear our value like we might still have some stock here right so we're going to do day 4 uh end of day clearing right day for clearing uh at the end of day we're gonna do that and let's take a look at the value here let's just use a link to represent that and this will be two because we don't have any stock on day four uh but what about this holding option here because we still hold some stock we're gonna actually clear that on day four at the end of the day so this will lead to three because we had a uh a plus two here right a plus two in this direction uh and uh what if we were frozen or if we were frozen then there's no change in the cash value because the only thing we can do is to you know rest it rest for the entire day so we're gonna have a value of minus one so this is now pretty obvious uh this is the better choice oh by the way we again forgot to add the uh arrow that uh that indicate the best action uh from any state onward so let's redo that again so um for the day zero of course uh there's no more further action uh so we didn't have to do anything like that but for this day one the optimal action is actually taking this one so we'll make this thicker right make the sticker by painting it with three pounds and then for this next state the best thing to do is to again by start buying some stock and then for this one since this is the only action possible we're gonna give it yeah a thick line arrow on day two the best value uh the best option the best control action or the best action is still like uh stay rested right and for this minus one here uh um it is when we uh inherit like we just keep we if we just keep um uh keep resting right and for this one here it is achieved by selling the stock we bought yesterday now uh on day three this one here is by following just you know resting on day two uh and then the for the holding state on day three the value is achieved by you know keep resting and for frozen on day three this is the only action uh for to empty on day four the best value was obtained by uh resting after the frozen state uh for holding state on day four this was achieved by uh by buying that free stock uh then for frozen state on day four the best action well it's the only action here so all right we just built our again you know optimal control action mapping some call it the optimal control law basically it means the optimal action to take at any given state so indeed if you look up any state here it's going to have one um you know thickened arrow that indicates where to go next and in the way in a way we could just take a look at what's the maximum value at the beginning and then we're going to just follow these uh thick arrows to um to find our uh our optimal trajectory so that is how i'm going to do this um and we're again highlighting the uh optimal trajectory here um right and then this one will just outline and give it the thick outline uh next one will be this one here with the thick outline the next state is frozen uh so we're gonna highlight that with a thick outline the next state is um uh holding well we should say the previous state like the previous date state holding and then on day zero we should be empty because that's the only thing possible all right so this is the optimal trajectory and uh our dynamic programming solution as if we were doing it in the backward direction which was the standard direction that dp was first defined for all right so uh that's it guys let me just uh you know give you a summary of what we just went through we went through the problem formulation of this stock buy and sell with a cool down problem first with its uh state machine but it's a slightly modified state machine than the leak code answer because i think my definition is more intuitive we have an empty state which means that we don't hold any stock we also have a holding state which means that we're having a stock and we also have a frozen state that is basically a one-time state after uh we basically a one-time state after uh we basically a one-time state after uh we sell a stock and we're just going to sit in that state for a day and it's a state with no stock in our pocket and then um after the frozen date you know uh which we rest uh through the entire day then the next day we are empty again and we are able to buy or you know rest uh just or idling uh also like when we were holding we were we are still given the option to you know rest and you know keep uh in the holding state so this is the state machine uh and then next we moved on to formalizing this problem in a forward unconventional uh dynamic programming uh as a former as a forward dynamic programming problem and uh our intuition was basically that we want to build our maximum cash history from day zero and the value that we're assigning in each of these state circles uh represent the maximum possible cash each day before taking any action and then we just basically perform such uh calculations step by step onward until the end of the day and then of course uh on day fours because the special day it's the last day we will have another uh day four end of the day clearing where we're gonna you know clear any um holding stock and change it into cash and then just compare the cash value at the end of day four and find our champion and work our way back to find the uh optimum uh choices and trajectory if we want to i mean if the if all this is about is just to find a value and we don't need to you know uh look up those things anymore and then of course this is the most textbook correct dynamic programming way of formulating this problem and it would have to require a reversion uh an inversion of the time direction because you as you can see we're actually starting from day four and then you know ending at day zero uh that is unfortunately the case because this is like finally this is the something that i would like to say to wrap up the theory part of this is that in the standard dynamic programming formulation which is the backward direction formulation your reward has to be a reward um uh in the type of onward reward in the future right um it cannot be like the rolling reward type which was like all the reward that you've accumulated so far in the past it has to be like the onward reward into the future right so this is like the difference between the uh standard backward direction dynamic programming and our forward direction variant of the damage programming which is just an inversion of the problem in terms of the time direction everything else is the same as you can see here like you can just uh a mirror image these uh these you know graphs you know these dots and lines you'll get this right so there's nothing um uh inherently different it's just you know two different directions or ways or preference of representing the same problem uh and i offered like a casual uh kind of like uh metaphor you know to differentiate between this forward direction perspective in this backward direction perspective so uh i guess in my mind you know um the standard backward direction uh calculation uh is like calculating your salary uh in a works perspective right um because then the reward is calculated like the uh the accumulated reward is calculated like as an onward reward so you're gonna start looking at you know uh for example if you're just working you're gonna start looking uh at the day you retire like what's the maximum uh level that you can achieve uh on the day you retire maybe it's the company ceo uh or maybe you're just a technical tracker it's like a cto or uh you know tech lead or you know principal engineer something like that then um you basically travel backwards uh in time like okay what's the year before i retire what's the second year third year before i retire all the way down to your current you know work year here and then you're gonna see okay how much money i can make at any year on any year in any like i guess job title job position so this is like a work perspective calculating your income you're going to be tackling the maximum reward onward from the current state and time all the way to the day you retire right um so there's like a cap of how much money you can make uh just by looking at you know your current year uh and between your current year and then the year you're going to retire maybe it's going to be 30 years 20 years 10 years you know depending on which what age you're at or you know how you project your retirement uh this is gonna be how you calculate how much money you're gonna be making uh in total uh from today on to the day you retire right this is the work perspective of uh dynamic programming and on the other hand if we calculate actually on the problem in the forward direction you're going to be looking at an investment problem because now the um the reward is different it's going to be like a rolling reward it's going to be looking at all the money you have right now or at any like position or role uh or you know your current portfolio and then you're gonna just move your way forward and accumulate as much uh this is called an arc reward uh as much as you can along your way and then you know uh and then you know until some certain time in the future you're gonna calculate what's the maximum amount of money that i can make from today on with this with the current asset uh until like uh maybe the day you want yourself to retire so this is like the investment perspective dp uh they could be used to save to solve the same problem but these perspectives are just different okay uh and that is how i kind of like can best explain this and there it is guys um now the next thing i'm going to do is to actually implement uh one of these variants i think i'm going to implement um let's say i think i'm going to implement on the forward uh variant right and then um and then see how it goes all right so now let's uh go back to our problem and apparently we don't have any submissions um and we're gonna just work on prototyping this now this is problem 309 and we want to build our dynamic programming um in the forward variant style right so what we do is uh in dynamic programming of course there's going to be like a i guess a for loop right further to just basically walk you from day zero all the way to day four even you know day five or the uh the end of day for day four so we're definitely gonna build a for loop here right four uh um for p in prices right um yeah paying prices so the reason why i wanted to iterate the content of the uh the list instead of you know the index of the list is because you know look up all the content by indexing the list it's gonna cost time um but i guess because we're doing recursive relationships it's better to actually use index so i'm going to stick with index now um so for indexing we need to first find what's the length of the prices array and then we're going to now use a range function to represent that now it's going to be in range in so now each k is going to be an index on the prices list and what do we do well if you look at this um graph again what we're doing is that on each day you know look at this recursive relationship uh on each day we're going gonna be calculating the uh the arc reward uh towards any possible future state as well as the uh the rolling reward in the past that we have so far right so we probably want to define the initial rolling values of our three different states right so let's just define that as well in here uh let's say our state zero for um for our state uh in empty uh one for our holding state and two for our freezing frozen state right so um and do we need like a table to re to remember everything right this is like important because we only need like a memory of one previous uh days like um uh one previous days uh maximum rolling reward uh in order to move forward so we don't need to remember you know the entire history we just need to remember yesterday's history okay um right actually now let's start something like here this was our previous uh idea and it was not so good uh now our so problem 309 uh with a forward dp variant uh solution the first thing i'm going to write down is that uh we do not need to remember all uh um right um like max rewards uh for all history omr max reward for all history we just need the most recent history yeah just literally yesterday right like i yesterday that is ie that is yesterday um and what is mr is a maximum uh reward let's add a rolling there rolling maximum reward let's call it rmr rolling maximum reward for our history we just need the most recent history from yesterday so this will make this will this makes the space complexity a pleasant what a pleasant um of one yeah so that's what we're gonna do um so for our empty so let's yeah what is um rmr right like rmr is um uh rolling maximum reward uh we have we will have make it like uh rmr is gonna be a list right um with three elements and it'll be let's see what should be that should be zero impossible so let's make it zero none is it possible um yeah maybe it's possible let me just uh make it that way zero none right and moving on right moving on um for k in range n we're going to start on um k equal to zero which should we already kind of like calculate it right uh yeah so let's actually start from k in range of one n so we're gonna start on the second element and what we're going to do is that we're going to apply now these iterative conditions of this right we're going to see how many things we need to compare for the maximum well for um for rmr1 rmr0 which is the um uh you know uh the yeah which is the reward the maximum reward like the maximum cash history uh maximum um rolling maximum reward while this is a little bit uh hard to say it and you know in one second rolling maximum reward okay or rmr yeah let's just call it reward okay um reward so the reward on day one is going to be uh um it's going to be r1 so it's going to be r1 let's just call it r you know uh our one uh our zero right our zero we're just updating it uh now this one is what there's two ways to uh yeah there's two ways to try to calculate it first is to use the value of from the previous uh previous actually we should use our new right yeah this is a better way um our new zero because you know we don't want to end up modifying things um from yesterday from history now our new zero is equal to the maximum between two things um the first thing is um continue to rest so it's going to be the same r value from yesterday uh our new r0 right r0 and the other one is um i guess uh the previous value of the frozen state yes uh yesterday's frozen value uh yeah yesterday's value yesterday's frozen state value yeah yesterday's frozen state value plus zero so yesterday's frozen state value uh so that would be r2 yep right that's it and uh um how about the next one the value for the holding state well for the holding state um we could there are again two different ways one is we take uh the reward value of yesterday's empty state value right and then we're going to minus the price of the stock yesterday right so max between r0 minus the price of uh of yesterday so price k minus one uh or we could continue to hold from a previous hold so we're gonna take uh the previous hold value uh r1 yeah yep uh and the uh our new three our new two you know what let me just uh somehow initialize the our new uh with something okay so that at least it'll have a memory there now r2 equals the max between well actually r2 there's only one way to achieve a frozen state that is you know take the holding state value from yesterday and plus the sale value of uh the stock price so we're going to do there's no max edges are from yesterday's um hold value and plus the price yesterday k minus one yeah um i would say we don't want to look up the list twice so i would rather just you know price equals to this uh price yesterday right price yesterday i'm gonna just do that and then just gonna do that yeah price yesterday right so now we updated uh this what are you gonna do are you gonna say update r yeah so r becomes the uh our new uh our yeah our new becomes the art but looking at it um do you think we really need like two lists are in our new to rotate this stuff um well the new first element relied on the first and the third element right the new second element relied on the zeros and the first element the new second element relied on the first element so i guess what we can do to avoid doing that is to perform this first because at this point r1 hasn't been modified yet uh and wait but then r2 would have been modified already we can't afford that so this r2 has to be before that but then our zero is modified so we had to put this before that now r1 relies on r0 which is not modified yet which is great uh and price yesterday r1 yeah you can't do that because this one relies on r1 okay anyway i give up i think i'll just keep two arrays of um r and r our new r and r new and we're gonna just you know do an update like that all right so i think this is all this is everything really uh and then after this for loop we'll be looking at you know the values on the last day uh and then we're just gonna do a clearing at once you know clear all remaining clear you know uh um clear the uh holding stock value on last day right so of course we're gonna have like uh at the end of the day we're gonna have like an r array and then the day r becomes our new so it's the same thing uh so we're gonna just make our uh one right we're gonna choose r as the array to work on is equal to r1 um plus the uh the price value of you know just uh the last day right yeah minus one is gonna be just yeah clear it at the last value there and then we're gonna have an r array basically it's gonna be like three different things uh we're gonna return what max of uh of r right i think that's it um i think that's uh basically it let's see if it works okay um right run it well there's something uh right i had thought about this so you cannot initialize them as none basically but so then what should i initialize them as if they cannot be not basically we want these values to be never uh like selected if you want them to be never selected you have to make them like very negative right because we're maximizing so if you make these x values like very negative you'll make sure that they will never be selected so what is the um yeah negative value you can get there so the highest price you can get is like a thousand so if we initialize these as like minus ten thousand will be probably pretty sure that they will never be selected right just as an overkill it's an overkill but uh let's see well ah this is again wrong we are expecting three right are we let's see one two three oh two we're expecting three right we're expecting three uh but somehow we got a answer of uh of four so how is that happening um let's just you know hand calculate this a little bit okay we take this array want you know actually let's just uh try it one two three we're all here we're already here so we can um basically inspect the progression of the r array at each step right we can do that and we can basically debug uh using that so now let's put our debugger on uh now we you know at the end of which uh at the end of each for loop we're gonna just look at you know the r value right so we're gonna do this oops this yeah we're here already good all right we're at this um k equal to one right so k equal to one uh what shall we expect um so day one we should expect it to be zero minus one and a very negative value there so let's see our new zero minus one and a very negative value that's correct so let's uh just stop again now k equal to two we expect to see again zero minus one that's correct and let's step again and we expect to see one minus one two um one minus one two that's correct so let's uh move one step forward we should be expecting two one minus one and we have two okay that's where it went wrong it shouldn't be two it should be so things went wrong when k equal to y k equal to four right so why would it go wrong when k equal to four let's see when k equal to four we're just basically going to calculate price yesterday right price yesterday was zero which uh makes sense price yesterday was zero and then for the um yeah for the empty value it's gonna take the maximum between 1 and the frozen value from yesterday so if we just take a look at r you know that's basically yesterday's list wait hold on why is uh r also 2 we shouldn't have updated r yet ah okay let's uh let's do this again okay we now know where to look at all right let's put on the debugger again and we're going to stop on this line here well i guess we have to restart the kernel to make the debugger working again right we put our pointer here right you know the fact that our new and r are like basically synced instantly before i update them that's scary that tells me something maybe is wrong about you know the memory location let me just uh move forward now r is zero and then two minus crazy values okay so they are actually different okay that's actually good news so when k equal to one we're basically seeing like r and r nu so r represents um the initial thing like zero minus right and r represents uh the actual calculated value for day one which is zero minus one minus a lot um right so zero minus one minus a lot which is correct so the next step is where you know our r becomes zero minus one why is that i mean the r here should be it should always like um i mean why i mean r after the update r should be what our new was previously right so when k equals to uh now k equals to 2 we shall see that you know our new has updated but r is going to be whatever was before so 0 minus 1 like minus 9 99 minus 9999 but here we're seeing that uh our r is zero minus one but why is that this is quite strange you know like i didn't tell r to update at all oh maybe this is not the right way to assign or to update the rs i mean that's the only thing that i can think of that could be wrong right like this is not how you update r if we do r and then our new this maybe is how you assign it right so let's just uh make it make an example if so for example if p is equal to one two three and then p new is equal to uh you know four five six and if you want to update p with p new just by saying p equals to p new let's see what p is four five six okay hey it does work but what if we say p this equals to p nu of this it's the same that's a shame because now hey actually now it works so i mean this line did have some magic i don't know why but uh no it actually works which is crazy you know um i guess i need some python memory and list assignment knowledge uh to see what you know yeah let's just look it up don't python um assign a assigned list to another list outside in one list to another how do you do it uh list one list two let's do equal to list one oh so you see this is like maybe when you change list two this one has been changed as well right this is like shallow copy or something oh right okay to make a copy right okay so i guess i was right so this is actually now a um a deep copy okay this is a deep copy um whereas r equal to r nu is a shallow copy so what are these things well if you don't know i previously had looked up you know the difference between deep copy and shallow copy on another occasion so basically a deep copy is a copy of the content of the variable whereas the shallow copies just copying the address of another variable so if you just copy the address um it's like okay uh okay um how should i say this if you just copy the address let's say your parents live in florida okay uh and uh when you know uh register for your amazon account and you just you know copy your parents address and put it as your shipping address then whatever you order is going to be shipped to your parents house right that's what i mean by saying copy but if you actually you know instead of copy their address but copy the entire thing and place it in another place that's like okay you basically buy another house but exact the same size and look of your parents house and this house is now in where michigan okay now in michigan and this is your house although you know everything in the house is the same this is a deep copy of the house instead of just the house address then you put this michigan address into your amazon account then you can actually receive your amazon packages in your very own michigan house which is exact which look exactly the same as your parents house but it's on a different address does that make sense all right so in this case we actually need um we actually need a new copy of r right because yeah so actually um because r is the one that we will be returning in the end we want this to uh always update so our new is like our temp our template temporary variable right and you're always using r to actually wait actually i just want to keep you know these two values at two different locations um we don't want to point to yeah we don't want to point we may not want to create a different address for r as well we just want r to use the same address but when we were updating r we just want to use the content of uh of our new yeah that's all i think that's uh that's how you do it and uh right that's right and let's submit this to the you know to the solution here and see if it works right it's uh working for the first one what about the uh yep that works too so let's submit it accept it there we go all right so above average performance let's uh submit it a few times a couple of times still above average okay good another one still about marriage so all right we are confirmed that this is an above average uh solution and it's actually the dynamic programming solution so uh yeah this is uh working pretty well and we just implemented this dp in the forward direction uh we could have implemented in the backward direction as well um so but i mean it's not necessary you can do this um you can do this on your own uh because it's just gonna you know flip the um recursive uh relations and now you're working on the onward reward in the future instead of the rolling reward in the past and you're gonna build your for loop from the last index uh which is now you know the first index anyway because you flipped your problem right um and then you know to the first index which is uh in reality the last day in the stock market so anyway uh this is our today's submission um so what we did let me give you a summary is that you know we um i learned from this uh solution of dynamic programming uh um with state machine kind of offline trying to digest what's going on in here uh and you know the names and the diagrams in here was a little bit you know confusing to me so i had to kind of like create my own graphics to figure out what's going on so i used my own i guess duplicate um my own kind of like remake of that solution and then this is my solution uh both in forward direction and backward direction but we implemented the forward direction code and also i made a comparison between what is the classical dp recursive um equation in the backward um fashion compared to what we have been using uh in this particular problem using a forward direction variant uh there although they're all the same uh you know doing it in forward or do it in the backward or forward just requires you to inverse invert the uh the direction of your time or your progress and then just reformulate the problem with the uh inverted um uh time and uh i made an analogy saying that okay the backward direction dp is like calculating uh your work salary towards you know the day you retire whereas uh the forward direction dp is looking at you know the rolling reward in the past up till now that you've made so far uh and then looking forward to see how much more you can gain so that you never know how much you how what's the maximum amount of money you can make until you actually uh recursively moved to the last day where uh where you work uh whereas in the backward direction you kind of like know immediately what's the you know the maximum you can achieve by starting from the last day you work and then you're just going to calculate backwards and then find out realistically um how much you can make from where you are at the status you are on the day right today so uh that's it guys that's the summary hope you liked my graphics and my explanation and i will see you in our next video peace
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
142
hey guys welcome back to another video and today we're going to be solving the lead code question linked cycle 2. sorry linked list cycle 2. all right so in this question we're going to be given a linked list and we want to return the node where the cycle begins and if there is no cycle we're going to end up returning no so there is a cycle in a linked list if there is some node in the list which can be reached by continuously following the next pointer internally a pos is used to denote the index of the node the entails next pointer is connected to note that pos is not passed as one of the parameters and notice that you should not modify the linked list and we want to do this in constant memory all right so uh this is one of those questions where i feel like if you don't know the algorithm which is in play uh for solving this question you won't really be able to uh solve it so the algorithm that we are going to be using is called the floyd's algorithm and it's a really simple and a kind of intuitive algorithm so let's take a quick look at how that looks like so let's start off by building our linked list so this linked list that we're going to have is just going to be numbers so we have one pointing to two let's point that to three and then four and then five six okay so that's enough so now let's look at a condition where this linked list is the end of it okay so after seven over here seven is going to point to none so when this happens there is a certain stop point so we go to one two three four five six and once we reach to seven the next uh value is not so that means that the linked list has a definitive stopping point so in this case we're going to return null for the question but if this was a cycle what would happen is this value over here might end up pointing to some other value so let's say the seven instead of pointing to null is actually going to end up pointing to the number let's say three okay so seven is going to now have a pointer going from seven all the way to three so basically in this case what's happening is we're doing one two three four five six seven and then from seven we go to three again then four five six seven and three and there's the infinite cycle that keeps going on and on now the question is how exactly do we identify such a cycle so let's take a quick look at that all right so over here we're going to be having two pointers okay and uh this method i think you might also be knowing it as a rabbit in the tortoise method so you have two pointers one of them is going to be the slow pointer and we're going gonna also have one more called the fast pointer so i'll denote slow with s and fast with f okay now both of these pointers over here are gonna start off at the head node and the head node is nothing else but the very starting node so in this case it's going to be one so s and f both start off at one now why is one called slow and why is one call fast now the reason one is called fast is because the fast pointer for every one step that the slow pointer takes the fast pointer is going to take two steps so let's see what happens so in this case let's go into the next iteration so the slow pointer is now going to take one step so now our slow pointer is going to be over here so now that the slow pointer took one step the fast pointer is going to take two steps so we take one and then we do two and now our fast pointer is going to be at three okay so just to make it easy to understand let's remove the old values so let's just keep continuing this pattern and if we have a cycle what is going to end up happening is that the fast pointer and the slow pointer are going to end up meeting at some point so i'll just go through this step by step real quickly and you should see how this happens so now the slow pointer is going to be over here and the fast pointer is going to be one two so now it's at five so now let's look at the next iteration so i'll just go to the color green so over here the next pointer so slow would be over here and fast would go one two and now it's going to be over here right so now i'll just change the color again and now the slow pointer moves over by one so this little pointer is over here now the fast pointer is going to move over by two but now you gotta notice that since it's a cycle it does not end but what will happen it goes to three and now it goes to four so now the fast pointer is right over here so let's erase it so it's more clear so this is where we ended off with so the fast pointer came to the value four here and the low pointer is over here so now let's go to the next iteration so slow pointer moves by one and now the fast pointer is going to move by two so one two and now it's going to be here so one thing that you want to notice what happened is the slow and fast pointer ended up meeting at a point now when they both end up meeting at a certain point what that's telling us is that we have a cycle and if we did not end up at the same node at any point that means we do not have a cycle so since fast and slow are both at the value six currently at the same node that means that we do have a cycle okay so that is part one of the question we have a cycle and let's say just for quick uh comparison so let's say seven actually ended up pointing to none so in that case what's gonna happen is once the fast pointer reaches seven it won't have anywhere to go and it will obviously never reach the slow pointer so in that case we're directly just gonna return none since we will not have a cycle if that was to if that was what was about to happen so this over here is step one and we got that done okay but now the question is how do we know where the cycle starts at so to find out let's just look at this as it is so the cycle starts at the number three over here right and the reason we know that is because seven points all the way back to three and the cycle always starts at the value three so three is going to be considered as our starting point and we want to understand how can we actually come up or reach to that value so to do that what we need to do is we want to store the value of our fast pointer so the fast pointer here we still want to keep that in mind but we can get rid of the slow pointer okay so let's remove this and again the fast pointer like i said is going to stay in the same place so the fast pointer ends up staying over here now what we're going to do is we're going to have another pointer and this another pointer is going to start off at the head node okay so let's call this pointer slow again just for the sake of just to make it easy so now this pointer over here it's a new pointer and it starts off at the head node so we're starting it at the head node over here and the fast pointer we get its value from the previous iteration that we did so now that we have these values what we're going to do each time both of these values just ignore their names of slow and fast because that doesn't matter in this case right now each iteration they're both going to move one step so in this case the slow pointer is going to move one step so now it's going to be over here uh simultaneously the fast pointer is going to move one step and it's going to end up over here so far nothing happened but now let's go over it again so now the slow pointer is going to move one more step so now this little pointer is over here and now similarly for the fast pointer it's also going to move one step and the fast pointer the seven points to three so it's going to go all the way back to the three so now what you want to notice is that they're both now again at the same point and this time whatever point that they are currently on actually represents what the starting value is in other words i'm representing sorry i'm talking about this point over here and that makes sense so the three is the starting point of our cycle so once this happens in our second iteration that means that we have found the starting point so again real quickly we're first finding the cycle using the slow and fast pointers and if there is not a cycle we return null but if there is a cycle we're going to store the previous fast value that we had we're going gonna go on to the next part which is finding the starting point and over there the fast pointer and the new pointer which starts off at the head both move by one iteration until they reach a common point and the common point which they reach is going to be the starting of the cycle which in this case is the value 3 and that's what we end up returning all right so hopefully all that did make sense and let's just code it should be pretty simple once you understand how this algorithm over here works all right so real quickly let's start off by doing the first thing which is finding our cycle and before we do that we want to define our variables so we have a slow pointer and we also have a fast pointer now the slow pointer and the fast pointer both start off at the head node and again real quickly the headnote starts is given to us in our function okay so now that we have this over here what we're going to do is we're going to go inside of a while loop and we're going to stay in this while loop until fast has some sort of value in other words we're going to stay until a fast is not equal to none and we're also going to check if fast dot next for the next value is not equal to none so if both of those values exist what we're going to do is we're going to end up going inside of our while loop now inside of our while loop the slow pointer over here is going to move by one iteration so slow is now going to be equal to slow dot next and simultaneously the fast pointer instead of moving by one iteration is going to move by two steps so fast dot next and then one more time dot next since it's moving two steps now over here what we're going to be checking for is we're going to check if the slow pointer and the fast pointer ever end up colliding at a certain point and if they do end up colliding we can directly stop it over there and we're going to break out and at this point what's going to happen is we're going to store this value of the fast value right so the current pointer where the fast value is going to be stored and we can use that for the next part so in this case uh if we end up breaking out over there that means that we do have a cycle but what if we don't have one and in that case we're just going to do an else statement and in that case we can just directly return none since we do not have a cycle and that means we're not going to have a starting point for a cycle okay so now we have we know we have a cycle and now in this step what we're going to do is we're going to identify the starting point and to do that it's the same step so instead what we're going to be doing is i'll be directly referring to the head but just to make it simple let's just come up with a new pointer so let's just call it pointer and this new pointer over here is going to start off at the head okay and what we're going to be checking for is we're going to go inside of our while loop as long as the pointer is not equal to the fast pointer over here and while that's happening our pointer is going to move by one enter one step so pointer is equal to pointer dot next and simultaneously the fast value is also going to move by one pointer so fast is equal to fast dot next and we're gonna keep going into the into this while loop until we reach a point where pointer is equal to fast and when we reach that point all we're going to do is we're going to end up returning our pointer and that should be it for our solution so let's just submit this and let's see what happens and as you can see our submission did get accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thanks for watching
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
352
so here we are given within data stream input of non-negative integer A1 to n input of non-negative integer A1 to n input of non-negative integer A1 to n and we have to summarize the number seen so far as a list of design intervals so I have made a small presentation regarding the question and explaining the example which has been given in the question and then I will explain my Approach and then we will code this question and then after I will explain my code and let's try to submit the question in Java and C plus right so the question name is data stream as design intervals right so here we are given three functions to implement first of them is summary ranges which is the name of class and the Constructor itself so we have to initialize our container which we will use to uh find the diskline intervals right and the next function is add number which will add that number into our container and into our stream which has been holding our value right and another function that we have to implement is get intervals which will return the set of design intervals which are formed from the numbers in so far like what is this one set interval so design set interval is being formed from the non-never intervals right suppose if I non-never intervals right suppose if I non-never intervals right suppose if I have a number five six seven eight so these are contiguous stream and a interval from them is 5 to 8. right and if I have a stream of number 5678 and 11 then my intervals and then design interval will be 5 to 8 and 11. right so let's look into the example which has been given in the question so in the question we are given with this query summary ranges so in summary range I will initialize this container which is the data structure which will we will use that will return the interval at the time and add the value into it next where is adding number so I have to add number one so this one is being added here then next word is get interval so only one is present in our data structure so I will return one comma one as the design interval up to down then I am adding 3 here so 3 will be added in our data structure right so ah next query is create interval so up to now 1 and 3 are only added in our data sector therefore 1 comma 3 and 3 comma 3 are only interval that has been possible for that right so next query is adding number so I have added 7 here right so next query is get interval so from these three numbers one three and seven I can't make any uh defined intervals so like the design rechargeable for from this is one comma 1 3 comma three and similar Commission so next uh next query is little bit interesting we are here we are given with an add number and the value which we are given is 2 right so this 2 will make this one two three as contact version right so then our interval will uh become 1 comma 3 and 7 comma same seven right and in the data structure if we can see that if I can sort this data structure at the moment what we can do is I can form intervals easily so I can use a set here which will help me by sorting the number and storing the non unique storing the unique values like uh okay so next query is adding number which is six so six and seven becomes a disjoint interval so 6 comma 7 will come the next interval in our set of intervals so whenever we get intervals like the next query is get interval so I will return one comma 3 and 6 comma 7. so for this question what I supposed to what I uh intended to use is set like in the set what we can do is we will insert the data directly and set ensure that the value in the set should be sorted and non-unit suppose if we have a 3 here and non-unit suppose if we have a 3 here and non-unit suppose if we have a 3 here right so this 3 and 3 will be uh again pushed into the stream and there that doesn't help us in calculating any interval because 3 is initially taken into the consideration so having a unique value our in our data structure is important so we will use set here so uh let's dive into the coding part so in my code instead of using a simple headset what I have used here is tree set so I have initialized myself into the summary ranges Constructor so after that I have added the value whenever I get any value into my Adam so in the gate interval part why what I am doing is that we I am getting an interval into the error list and adding them into the arraylist and I will combine about them into the 2D integer and will return it last right so as it is given that my set my stream of the number doesn't contain any non negative number so I will start my first interval as minus 1 comma minus 1. so I will iterate over the set up to now which is being made from the insertion from the atom so if my left is less than 0 so initially if it is minus 1 so I will assign that left and right value to the current value that is selecting the first element and if the value of in the set is equal to the right plus one that is the if it is contiguous as my set is sorted as my set is a DOT sorted data structure so that will be a possible condition so I will increase my right value to that value right and increase the uh increase the range of the current render one and if it is not happening so what I'm what I will do is I will add that current interval into my intervers arraylist and then in slice the left and right to the current value and at last there will be an uh there will be a last interval which has been left to add into the intervals so I will do that and At Last I have converted that RL H2 to the 2D array so if you have any another approach for doing this error list to our account version so do comment below if you have any good approach so I have converted that and send it as a response right so let's try to submit this so it gets accepted in Java let's try to submit this question in C plus so the test case given in the question is passing let's try to submit this question so it got accepted in C plus as well I hope you liked the video thank you for watching see you in next one
Data Stream as Disjoint Intervals
data-stream-as-disjoint-intervals
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals. Implement the `SummaryRanges` class: * `SummaryRanges()` Initializes the object with an empty stream. * `void addNum(int value)` Adds the integer `value` to the stream. * `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by `starti`. **Example 1:** **Input** \[ "SummaryRanges ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals "\] \[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\] **Output** \[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\] **Explanation** SummaryRanges summaryRanges = new SummaryRanges(); summaryRanges.addNum(1); // arr = \[1\] summaryRanges.getIntervals(); // return \[\[1, 1\]\] summaryRanges.addNum(3); // arr = \[1, 3\] summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\] summaryRanges.addNum(7); // arr = \[1, 3, 7\] summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\] summaryRanges.addNum(2); // arr = \[1, 2, 3, 7\] summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\] summaryRanges.addNum(6); // arr = \[1, 2, 3, 6, 7\] summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\] **Constraints:** * `0 <= value <= 104` * At most `3 * 104` calls will be made to `addNum` and `getIntervals`. * At most `102` calls will be made to `getIntervals`. **Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
null
Binary Search,Design,Ordered Set
Hard
228,436,715
212
hello and welcome back to another Elite code problem so today we're going to be doing problem number 212 word search two so we're given an M by n Board of characters and a list of strings and we need to return all words on the board each word must be constructed from letters of sequential adjacent cells where Jason cells are horizontally or vertically neighboring in the same letter cell may not be used more than once in a word so we're given something like this we're given a board we're given a list of words and we need to construct this and so it's going to be difficult to do some kind of DFS or something because the length of this word list is very long but this is n by m where n and M are very short I think they're like 12 karat 12 uh only 12 spaces long so when you see something like that when you have a huge word list and a short board so you are probably gonna have to do some kind of search but something like a depth for search makes a lot of sense with backtracking and the reason we can use backtracking is in order to store indices we visited earlier like let's say we start this o in order to store indices we visited earlier it really matters where we got there from so for example if we get here it really matters where we got there from like did we get here from this o and if we did get here from the so did we originate it so or did we maybe start here and then go to here and so when there's all these different combinations and just because you get to an index doesn't mean you all these iterations are different it really matters where you got there you're gonna have to do something like backtracking as opposed to memorization because all these different things can't really be recorded like you'd have to record the exact path and then you're storing entire arrays which is not great so whenever you have an array of a path you typically want to use backtracking instead and so the other thing is when we Traverse how do we really know if we get a word well one thing we could do is we could have a path and then every time we get to a letter we just so let's say we go this way so we have Oath right oh you could be like okay we have Oath is oath in our dictionary we have some other things that enter a dictionary but that's going to get expensive rather fast because this words is really big so is there a better way to know if this is in our dictionary or if this is in our words without traversing it every time and there is actually a better way to do that and the better way to do that when our words list is long but all the words are kind of small and we have this small board is using a try and so the basic concept of a try is it's going to be a path so let me just demonstrate so it's going to be a variable let's just say this is the try and it's going to contain every letter in it and then every letter is going to point to another try so for example for oath we're going to have a root so this is going to be the root instance variable of the try then it's going to have a every single try is going to have a dictionary of children with keys being a letter and then the value being another try so like this is the root let's say now we go to O we get to another try this o has an a right get to another try this a has a t get to another try and then an H here and then also if try to share the same letter so for example this root can have an O and then this can point to like let's say of if of was a word or something like that so we're gonna whatever node we start at we're going to start at the root we're going to Traverse down every time and we're going to ask ourselves so the other thing a try has that's kind of important is every time we Traverse down a letter so there would be extra try here at the end we would say okay once we're at a try all we have to do is we can have a variable a Boolean for the variable called like let's say we call it end and if n is true that means we've reached the end of a word and so we can iterate through this words oh we can iterate through this words dictionary one time take all of these words and make a try so for example let's see what a try would look like for all of these words so starting with oath right so let's delete this and let's do that so we start with oath remember we have this root node so let's just call that root node we go through an o go another try go through to an a so go to another try T another try H another try now we've reached the end of the word so we're going to mark this equal we're going to say this is an end and I'm just going to make this red and red means the end of a word so we also have P so p is a completely different it doesn't have any of the same letters so this dictionary once we're at this try this will have a dictionary of every single letter that we used words for so it would have it would add this p and then e and a have another try down here same thing this is showing that we reach the end now we have rain or we have heat sorry so eat is completely different as well so e a we're not sharing the first letter then this is another try the end of the word and finally rain so rain doesn't share anything either so our a all right and okay and this is the this and so when we Traverse down like let's say we're at oath so we start at the root we go to O then we go to a then we go to T then we go to H and we see oh we're at this end node that means this is a valid word and we're just going to keep track of the current word like we're just going to have some kind of current uh array that's going to keep track of every single letter that's in our path and as soon as we hit an end node we're going to add whatever current is to our result but keep in mind we can't just go back as soon as this happens because there might be a longer word that contains this word so for example this oath might also contain a word like Oaths so even though there's an end we have to keep going until we backtrack fully so you can see like this would be a word as well so we don't our con our return conditioner wouldn't be if we just hit a word we'd have to keep going but we can have a return condition where we are at some try and we can see okay does this try have any paths from it does this have any letters in it if not we don't really need to keep going because there's nothing in here so we can just return there so that would be an end condition as well as if we check every single index in a backtrack and also keep in mind for these tries words can share letters right so let's say this is a root so we have e but we might have ears Maybe could be a word so then it would go down the same path so it would go to EA but then it would go here and to this try and this would be an end node so that's kind of how a traged it represented we're going to have a dictionary of letters as keys and then they're going to point to other tries we're going to start our root and we're going to Traverse down and we're going to have we're going to use this n variable to know that we have a result and we need to travert we need to start at every single node in this um in this grid and we need to try to Traverse in every direction using backtracking so let's and yeah by the way so we can look at also yeah so this is going to give you a lot of hints to do things like that when you see this m is really small this n is really small that means backtracking is going to be something useful because if let's say this grid was like a thousand by a thousand then if you backtrack that's going to get really expensive and also you see this words this word length is really big so you don't really want to compare every single node you're at to the words like where if the sword length is only like 10 words then we could easily just compare every time instead of using a try because it's kind of small so hopefully that makes sense and let's just start coding it up so first of all we're going to have a try class right and the try is going to have so actually for our try I don't think we need to pass anything to it so we're just gonna have it in it try and then we need self.children try and then we need self.children try and then we need self.children equals this empty dictionary right and self dot end equals false we can give our try a character but technically we don't need to do that because these should all be connected so then we need to go through this list words and we need to make this list of tries so this would actually not be a try this would be a try node so now the try is the actual try is this full tree type looking thing but all of these are actually try nodes okay and so first we need to make a root and that's going to be our root note that we're just going to start at and then we're going to start we're going to keep starting at the root node and go down all of these words to make our actual try so we can just say root equals try node like that it doesn't take any values so now we just have to iterate through every single word so for a word words and then we have to iterate through every single character as well so for care and word so for word and words first we have to start at the root so we can do something like this curve equals root and then we are going to Traverse down every single character so if care in Cur dot children yeah if so it's actually if not so for example when we don't have um when we don't have these children we need to make them right so when we start with our initial root like we start with our root and we're going down some word like word when we're at this route we check the children the W isn't in there so now we need to make it so every time the character isn't in the children we need to add it in and then we need to go to it so if character not incurred our children then we add it in there right and so we do Cur dot children care and then we create a new trinode and then now we just simply Traverse or because we would have made it where it's already in there so occur equals children care then once we Traverse that whole word so now we're going to be at the tri node that's the end of the word and now we need to make this end true so just Cur dot end equals true okay so now we made all of our tries and now we need to use this DFS backtracking algorithm to actually search for all these nodes so first we're going to want a couple things we're going to want some kind of sort of backtracking it's good to have a curve array and a resume right for the actual output so we can just have res equals this and then Cur equals this and then our curve is actually going to be a list of characters and then we're just going to join those together and put the put it in the residents we actually have a word So Def DFS and the DFS is going to take an index and it needs to take a node because we need to see what Tri node are we in I believe so we're going to fasten the route to start off so it's just going to be a node okay so like I said if the node were in has no children right that means that we can't go anywhere so we can just return straight away so if no dot children and we guess we can just say like this if not no dot children we do need to actually check if we're at this node we do need to still check if it hasn't so like if we're at an end node even though this node has no children that we're still at an endnote so we would have to append that word so that's the first thing we can do so if node dot end that means it's true we do need to append this curve so we just need to do res dot pend and then we need to join current so join occur okay so now we do that but then we need to keep going because this can have more children so if no if not no dot children we can return here I believe now what are our other cases well if we have children we need to actually DFS into all of these letters and so what we would do is let's think so the way we would do this is we would get another thing we can do is we can add this directions array this is always useful for DFS so directions equals like this zero one negative one zero negative one okay so let's say we're here if we try to DFS into one of these we could only DFS into one of these if it's actually in the children so if it's not of the children we don't need to DFS it for example if we're at this zero and a is not in the children then we don't have to go there so the only way we would have to DFS is if it's a valid index and if it's a and if it's also in the nodes children by the way so this index would actually be a real column and so another thing we can have here is this as well equals length board and Link or zero this is good to have for checking if we're inbounds and things like that okay so yeah so we need to check all these directions and get new directions let's do that so four I'll just say Direction in directions new row new column equals rho plus Direction zero and column okay now we need to check if they're in bounds so if new row is so we need to check if everything's in bounds and it's a valid and there's something there so here is this less than rows and zero it's about this new column lesson columns and so remember we need to check if this letter is actually in our children so if board new row you column in and then this would be node dot children okay so now we have everything valid I believe now we can backtrack to it and so we would say we would just call DFS on that so we would say something like DFS new row you call them and then this node would be node dot children and then it would be this letter right here right so that's what we would pass in I think that makes sense otherwise we don't even have to DFS into it okay and now let's think about do we even need a return value I don't think so I think once we go through all these backtracks we're not really modifying anything we're just updating where to go from here which I think is fine okay so I think that looks good so let's try to just see what that looks like and see if we have any issues oh by the way do we need to add to Cur and remove from Cur and things like that's another thing we would need to do actually yeah so actually we do need to do something so if this is a valid location uh how do we do this so I think actually instead of checking this let's think about this so we're at a root we're going to pass something no I think this is fine actually so what we do need to do is we do need to actually add it to the curve here I believe do we need to do that here no I think we're going to do that here yeah we're going to do that here so it's going to be right over here we need to add that here so Cur dot penned board row column that way yeah so we get to so let's say we're at this o we check is this a inner o yes it is so then we go to a and then we need to append here and then what we are going to do when we Loop is when we Loop we don't need to go to I mean we could have a check here as well for that actually but no I don't think that would make sense well so we are gonna we're gonna have to do in our Loop is we're going to start with our root um we're gonna start with our root node and we're going to check is this letter are all these letters in our root note and if they are then go there if not we don't even have to start there so for example if we look at our picture right let's say for this one our starting letters are e-p-o-r letters are e-p-o-r letters are e-p-o-r so then any letter that's not in like once we Traverse this whole thing if it's not epor we it's not going to be a valid start index so we can skip all those okay so let's just double check this code just to make sense we have directions we have rows we have our this uh this should be fine res curve so once we're at an index we need to append to the curve okay makes sense so the other thing we need to do as well is because this is a backtracking I think right before we return we're going to need to delete what we appended here so we can just pop to delete and I think that makes sense so like let's say we're here we go to a we append but then we return We pulp okay I think that makes sense to me if no dot end that looks good that looks okay so let's just try this code and see what kind of bugs you're into oh by the way so we do need one other thing so we are going to do this nested Loop where we Loop through this whole Matrix and we check if we can do these so let's do that so four row in row and range rows for column range columns so remember we need to check if this value is actually in the children of the root node so if board column in and then where's our root node right so it's going to be root dot children yes then we can just pass it in with the root I believe yes and then in this DFS we're going to yeah we're going to pass it this next thing so we actually don't want to pass in the root I believe we want to pass in the node that is in the children so this kind of same thing like this so if board we would call DFS or we can just use this so this would be row column root dot children row column uh so this is column okay so now that we did that yeah so we're going to append the curve here so that should be fine so let's return the res here and I think that looks fine we're probably gonna have some errors it's definitely complicated code so dict is not callable okay row column root dot children board row column I'm interesting did I have too many parentheses here yes so this needs to be brackets and so this does as well I suppose right so this needs to be brackets because it's like this is like this let's try that okay so we have an error so we have oath and oeat so why do we have O8 that's a bit strange but for a second one it works but for this one it doesn't so for some reason we are appending this o every time so why is that you're fast forward row column that looks fine is there oh eat too many times I think oh I see the problem so we have this return but we still have to pop regardless so we still have to pop here because we appended so let's try that okay let's take a look hopefully that's fast enough we might have to make some optimizations if it's too slow like I think there are some optimizations that I remember doing this problem um but let's see okay so oh wait okay so we do have okay so that's another thing I probably wanted unique yeah so it wanted unique uh answers yeah and so what we need to do like let's say this is OA and things like that so we need to have one more data type pretty straightforward so this res can actually be a set now we can where are we adding to the res let's take a look res dot append so instead of res dot append we can just do res dot add now we just return res I think this should work as a list anyway let's see yeah I think it'll just convert it for us and let's see if it's too slow and if it's too slow we're gonna have to make some other modifications to this it might be too slow I'm not exactly sure because this one I remember when I did this only code it barely passes so okay words a output a so what happened here okay so it looks like we are going back and forth which is a problem so we're coming here yeah so we're coming here and then we're coming back and so we aren't we probably do need uh like let's see what that would look like actually in this code so let's say we had a okay say we had this a and let's try to walk through it and then we are looking for AAA okay so it's going to go in this a it'll add it to the curve so let's just say our Cur is a we're here then we are going to go here and yeah so then we're adding it now we do go here which is a problem so we need to have some kind of thing where we can't go back to I know that we were already there and so we do need to have a visited set I think is what we need set and then simply for backtracking what we need to do is we need to do the same thing here we need to add the node to our visited set so therefore we can't go back and forth so just visited dot add and we can just add row column here then we can remove here so remove I believe okay so visited.adrow column okay so visited.adrow column okay so visited.adrow column visited.remove row column and then we visited.remove row column and then we visited.remove row column and then we also need it here okay so we need one more check right so we need this is going a little a lot of Bounce that's okay so we need new row column not end visited and this actually needs to be here I guess we can split this up so we can just split these up a little bit to make it cleaner codes of this then we can have an and here and then here and there okay so something like that oh so let's try to see that okay so we have an error we have Oath and we expected oath and eat so I think that means we are all right so this should be removed okay definitely a lot of stuff for this problem it's not super easy and it still might be too slow so we'll see okay so it pass which is good this one down sorry about my cat for a second that this definitely is a tough problem for sure there's a lot of room to make errors and when you make a solution if you forget one of these optimizations there might even be more I think there is actually one more that I'm forgetting but if you forget any optimizations I think it's really close to not being able to run on the code even yeah like when I submitted this how close was this to I think this is still not like eight top solution so I think there's another one let's see how many uh just to double check again yeah so we're only beating 20 so it's definitely a close one and you can have time limit exceeded if you have some issues so think of the time and space complexity let's make it tricky for sure so time space okay so what are we doing we have this directions array which is negligible this is negligible we have a tri node for every single letter in every single word and so that might be our limiting factor but let's or actually this will that's that space so for our Tri nodes we actually go through every single letter of every single word so that's going to be let's just make up some variables again here I just say w equals word length right and not um n equals word count let's say so that part is going to be W Times n to go over every single letter of every single word and make these tries okay and then we're going to do this backtracking so backtracking you will have repetitive operation so you will be checking multiple nodes because it matters where you got here from so for every single node we can go to every single other node and then we can go back but I think that won't be as expensive compared to this making of the tries because these are only 12 by 12 like they're very small so I think that part of the code should actually be negligible compared to making these tries so I think most of the time is going to be spent making these tries if I'm correct and the average backtracking is pretty much Brute Force so it's definitely not an ideal solution but we do have a visited array so we can only go from every node to n by m but like I said even if you do like n by m by n it's still 10 times 12 which is not that big so I think that part is negligible and I think our time complexity is going to be mostly towards building this try um you can correct me if I'm wrong or I might edit this later if I am but um so space so we are going to make these tries and these tries can technically if all the words are completely different and start with completely different letters then our space is going to be the same thing it's going to be W Times n because we're going to have a try for every single one of these and then are we making anything else so we do have a res which is going to be every single it could be up to every single word which would be also W Times n and we have a cur which is just going to be the length of a word maximum and we do have a visited set and we have a rep and we have uh I think we have one more set no this is just a set so this visited set though is basically negligible because the most it can ever be is 10 by 12 so that doesn't matter so I think the space is this as well all right so this was quite a long problem and I hope you enjoyed it and if you like these kinds of videos like And subscribe and I'm going to continue making more so thanks for watching
Word Search II
word-search-ii
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_. Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. **Example 1:** **Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\] **Output:** \[ "eat ", "oath "\] **Example 2:** **Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\] **Output:** \[\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 12` * `board[i][j]` is a lowercase English letter. * `1 <= words.length <= 3 * 104` * `1 <= words[i].length <= 10` * `words[i]` consists of lowercase English letters. * All the strings of `words` are unique.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Array,String,Backtracking,Trie,Matrix
Hard
79,1022,1433
228
foreign thank you foreign coming up thank you foreign welcome to this tutorial on solving the lead code problem summary ranges in this video we will tackle an interesting problem that involves efficiently finding and summarizing consecutive ranges within a sorted array this problem asks us to take a sorted array of unique integers and return the smallest sorted list of ranges that cover all the numbers in the array exactly each range is represented as a error B if a is not equal to B and as a if a is equal to B in this tutorial we will walk through the intuition behind the solution and dive into a python Implement implementation of the most optimized solution without further Ado let's get started well the problem requires us to find and summarize consecutive ranges in a sorted array to do this we need to identify the start and end points of each range let's break down the intuition step by step well to begin with we need to check if the nums array is empty we do this using an if statement if not nums if the array is empty we immediately return an empty list then we initialize and empty list called ranges to store our summary ranges this list will eventually hold the smallest sorted list of ranges that cover all the numbers in the input array well we then we also initialize two variables start and end and set them both to the first element of the input array these variables will keep track of the current range as we iterate through the array now we iterate through the remaining elements of the array starting from the second element by examining each element we can determine if it is consecutive to the previous element if the current number is consecutive to the previous number it means we are still within the same range in this case we update the end variable to the current number efficiently extending the current range and the other hand if the current number is not consecutive to the previous number it indicates that the end of the current range we need to add this range to our range list to determine the format of the range we use an if statement to check if the start and end are equal if they are equal it means we have a range with just one number in this case we add that single number to the ranges list if the start and end are different it means we have a range with multiple numbers in this case we add the range to the range list in the format start Arrow end after adding the range to the ranges list we update the start and end variables to the current number this prepares us to prepare this for the next range if any once we finish iterating through all the elements we need to handle the last range we use another if statement to check if the start and end are equal or different and append the corresponding range to the ranges list finally we return the ranges list which now contains all the summary ranges by following this intuition we efficiently identify and summarize consecutive ranges in the sorted array the algorithm keeps track of the start and end points constructs the output in the desired format and optimizes both time and space complexity the time capacity of the solution is O of n where n is the length of the input array why is it Big O of M well we iterate through the entire array once visiting each element exactly once this is and this is because we have a single Loop that goes through the elements of the array starting from the second element therefore the runtime of the algorithm scales linearly with the size of the input now let's move on to the space complexity of the solution the space capacity of the solution is Big O of 1 or Y is it a big of one although we use an additional list called range to store the summary ranges the space it occupies does not depend on the size of the input array um it remains uh constant regardless of the array length additionally we use a few variables such as start and end which also occupy constant Space by having a constant space complexity we can efficiently solve the problem without incurring significant memory overhead even for large input arrays so to recap the time complexity of the solution is Big O of M indicating linear runtime and the space capacity is Big O of 1 indicating constant space usage understanding the time and space capacities of an algorithm allows us to evaluate its efficiency predict its performance with larger inputs and compare it to other algorithms for the same problem and there you have it we have successfully tackled the summary range problem from with code congratulations I hope you found this tutorial helpful and gained a solid understanding of the problem and its solution if you have any questions please let me know in the comments below and if you enjoyed this tutorial be sure to give it a thumbs up and subscribe to the channel for more coding tutorials tips and tricks happy coding and thanks for watching goodbye foreign
Summary Ranges
summary-ranges
You are given a **sorted unique** integer array `nums`. A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive). Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`. Each range `[a,b]` in the list should be output as: * `"a->b "` if `a != b` * `"a "` if `a == b` **Example 1:** **Input:** nums = \[0,1,2,4,5,7\] **Output:** \[ "0->2 ", "4->5 ", "7 "\] **Explanation:** The ranges are: \[0,2\] --> "0->2 " \[4,5\] --> "4->5 " \[7,7\] --> "7 " **Example 2:** **Input:** nums = \[0,2,3,4,6,8,9\] **Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\] **Explanation:** The ranges are: \[0,0\] --> "0 " \[2,4\] --> "2->4 " \[6,6\] --> "6 " \[8,9\] --> "8->9 " **Constraints:** * `0 <= nums.length <= 20` * `-231 <= nums[i] <= 231 - 1` * All the values of `nums` are **unique**. * `nums` is sorted in ascending order.
null
Array
Easy
163,352
977
hey what's up guys and quite here - tech hey what's up guys and quite here - tech hey what's up guys and quite here - tech encoding stuff on Twitch in YouTube and I do all the Waco problems I got a million up right now not a million but a lot so check those out if you're looking for solutions on leak code problems and explanations so yep that's what we're doing right now we're doing this one it's called squares of a sorted array so given an array of integers a sorted in non decreasing order I don't know why they don't just say increasing return an array of squares of each number also sorted in non decreasing order so we see the array is right here negative 4 negative 1 0 through 10 increasing order and then we have 0 1 9 16 100 these are the squares of these numbers also sorted and you can see that you know negative 4 times negative 4 is gonna be 16 so that's gonna be right here and they come on time so that one's good we want it's right here so just to show you kind of how that works so basically the trick to this problem in solving it now optimal speed space is just accounting for these negatives kinda that's the only tricky part here so we're just gonna use a two-pointer approach so what we're gonna two-pointer approach so what we're gonna two-pointer approach so what we're gonna do is we're gonna take a pointer and set it to the last negative element so we're gonna have a pointer here in this case and then we're gonna have that point or decrement because that the FIR the first element the last negative element here is gonna be the smallest positive element when we square it negative 1 times negative 1 is gonna be 1 so we're gonna want to put that in to the right before the next negative element so we're gonna have our one pointer cover the negative elements and go in decreasing order and then the other pointer is gonna be at the first positive element and it's gonna go in increasing order because increasing from the smallest positive to the biggest is going to give us the smallest Square to the biggest so let's just start doing that so first of all we're gonna grab the length of our right here and then we're gonna do set our first pointer so let's say we have we can just call it positive Poynter I'll just so I can make this clear for you guys so positive pointer is going to be equal to zero right now and then we'll do a wild positive pointer is less than and so while it's less than the length of our array we will do oh no and a positive pointer so the current element is less than zero so while we're while are positive while we didn't get to the end of the array we're looping through the array and while the elements are still negative then we're going to increment our pointer positive pointer right so now once we break out of this loop we've gotten to the we've passed the final negative element so if we were on negative one here it would still loop through and then we'd be on zero right now so now we want to set our second pointer so our negative pointer is going to be set to positive pointer minus one so now our negative pointer is set to the index of the first negative element right perfect so now we could set up our new sorted array for a square sorted so we could do int stem I'm sorry about that int sorted squares I'll call this array as they go the new int of size n it's gonna be the same size as our initial array here and then we're gonna have our final pointer or find our counter so we'll just have a counter is at the zero to kind of increment our array as we go and yeah that's pretty much it now all we have to do is our loops so while negative pointer is greater than or equal to zero and positive pointer is less than n we are going to do a check if a of negative pointer so if the square of the negative element is less than the square of the positive element I don't know if these naming conventions are really good for a video but I kind of want to I hope that you guys it hopes you understand then we're gonna set our sordid squares array sorted squares of counter and you can increment within right here or you can increment separately I'll do it separately so you guys can see better sorted scores of counter is gonna be equal to a of negative pointer times a negative pointer because we want the smaller of the squares because the square of a negative element can be less than the square of a positive element obviously and the square of a positive element can be less than the score of a negative element for example three squared is nine but negative four squared is sixteen so nine is gonna get it put in before sixteen so we want to do that check here so you know if the negative element is less than the square is pop squared is less than the positive element we're gonna put that in our array first else we put the positive element in our array from the first two sorted squares of counter encounters once again just a little counter variable to increment our array as we go positive pointer there we go and that's pretty much the main loop here we do have to obviously decrement our negative pointers a negative pointer minus equals one at each loop and increment our positive pointer as we put these elements in and then also our counter like I said you could have just incremented it right here if you wanted both times but you don't have to so now that we break out of the loop this means that either our negative pointer we've hit the last negative element or we've gotten to the end of the array in that case at the last positive element so we just have to get those edge cases here so well negative pointer it's greater than or equal to zero because one them could be at the end but we still have to account for the rest of either the negative elements or the positive elements while negative pointers greater than or equal to zero then we just add our final elements here sorted squares of counter is equal to a negative point D commenting again and then it's gonna be the same type of deal here once again and you also have to make sure you count for the counter Wow positive pointer and just the same conditions up there but one of them will break out so we have two these are just edge cases counter hopefully you guys understood this solution as I went through I tried to name it so that we've made it better for you guys to understand I might have made it more difficult and then our race should be filled and sorted order of all of the squares of the original elements so we'll return not answer but sorted squares and let's submit it hopefully it works for strong positive pointer not a statement line 35 positive pointer plus equals 1 sorry incrementing that a lot of code there we go success that's pretty much it hopefully you guys understood that I tried to write it in a way that would help you guys understand that just a two-pointer method we're that just a two-pointer method we're that just a two-pointer method we're storing everything new into a new array so I guess that's open space and it's linear so good run time here the pointers with the negative just going backwards on the negative elements forward on the positive elements and putting them into the new array it's the smaller of the two squares one at a time so that's a check out my other videos if you can everything is in description then just watching you and I'll see you later
Squares of a Sorted Array
distinct-subsequences-ii
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
String,Dynamic Programming
Hard
2115
95
Hello everyone, welcome to me, we are going to do channel 54 and you can also see the playlist of DP construction. If you want to understand DP from the beginner level, then okay 95 is the medium mark but it is very easy because we have already done it. I have solved the question, I have given its link in the description. It is a similar question. Okay, so the code from there can be used here also. Okay, the name of the question is Unique Binary Search Tree Part 2. Let us understand that the question is very small and very simple. That you have given the interior, okay property, know that if this is the route then its left side value will be less than this route and the right side prestige which has exactly and notes of unique values ​​from one to one is okay return unique values ​​from one to one is okay return unique values ​​from one to one is okay return d answer in other Order can be made into examples. Look, one here, its right side is three, left side you, this is binary search history because see, its right child is bigger than one, it is bigger than one and its left child of three is smaller than three, you are this. This is also binary search history, this is also binary creation, this is also forest research, then okay, then what do we have to return, send the route of every binary search history, just like this is binary search history, what is its route, forest, ok with us. Just send the route, the result is fine, so what is its route, so let's see how we will approach it and we have already solved a question whose name was to find the possible full binary tree, today what we have to find which is the possible binary search tree. So the structure of both the codes will be exactly the same, okay, we will make them in a very simple way, okay, now coming to the approach, how will we take the approach, okay, so see, before increasing the approach, learn one important thing, you will know that. If we take Maa, this is a binary search history of mine, then if this is a complete binary system, then what does it mean that this is also true in itself and this is also a sister research history in itself. And this is also a balance seat in itself. All the trees are binary in themselves. You must know this. Okay, let's move ahead. What was the example? Okay, meaning, what values ​​can be there? It Okay, meaning, what values ​​can be there? It Okay, meaning, what values ​​can be there? It can be a forest, it can be you. It can be free, it can be 4, it can be five, it can be six, okay, I showed you a little fear above, in this example, you are seeing that it can be 123, so see, root one can also be formed. Here it is, look here, √1 is root, you look here, √1 is root, you look here, √1 is root, you can also become root, so everyone should get a chance to become root, otherwise what will I do, I will root this once, then I will root this once and so on, okay If there is a route then everyone will have to make a route, so I will show you an example that if I take a mother, I have made a route for four, look, everyone will make a route one by one, but I have made a route for four and now I am showing six how you can proceed. You will do it, let's take four as a root, I am fine, so sincere is binary, so what does binary mean, if four is a root, then on the left side of four, there will be all its small values ​​which will be smaller than four, so the all its small values ​​which will be smaller than four, so the all its small values ​​which will be smaller than four, so the thing is that If four is the root then it will be the left child of four which will be all the subtrees on the left side of four, their value should be smaller than four, then I can take the value from here only. Right means from where till where I can take the value. I can take only the values ​​from start to i - 1 to can take only the values ​​from start to i - 1 to can take only the values ​​from start to i - 1 to create the leftmost children of four, to create all the leftmost three, to create all the things on the left. Okay, this has already been done till now. It is clear because what happens in binary is the root and on the right all are capitals so let's reduce one. Let's make this and see that if the four root is formed then what I said will be left on the left side so that I can make subtrees. I am, that too should be one, three and this I have made it the root and what are the values ​​on the right, it will and what are the values ​​on the right, it will and what are the values ​​on the right, it will become 516, I will make it, this was I + 1, this become 516, I will make it, this was I + 1, this become 516, I will make it, this was I + 1, this was my end, okay so I will collect all the binaries that can be made here, how many are being made on the left side, b1 on the left means life is chosen and on the right, then on the left b is chosen one and on the right b six means once life. By pairing b1 with these two, I chose left and right. Okay, from left, b one, from right, b six, similarly, what can I do that four is my route, b2 from left, b5 from left, b from right. B Six From here it is understood that this time I have paired these two with b2 and then similarly I will pair these two with b3. If you see then whatever left BSTC I have will come in the vector. I will have as many left BSTCs as I have. This thing will be understood and look at the loop. I know that he has posted it on similar question. If you remember, I have written similar question at the top of the description and have also given a link to his YouTube video. If you go there then you can see it. Logic has also been applied there that whatever was done on the left side was that the complete binary tree had to be extracted, it is okay that what is here is finally extracted, then whatever was found on the left side was taken out, whatever was found on the right side was taken out on the left. Picking up each one from the side and pairing the saree from the right side. Okay, just like you were doing it here, the logic will be there as well, so the code will be there from the same. Okay, this is clear till now, understand this thing. If I have gone, then we have to pay attention to two things, first of all, we have to give everyone a chance to become a root, see, I have just made this a root, while I have come, where will I start, everyone also has to make it, so I came from here. I will start by making it the root, let's take the mother, then later I will make the I bigger and make it the root, then I will become the I and make it the root, okay then I will make everyone else's root, I will have to do these two things tomorrow, the left ones will take everything. And to get all the things on the right, here I will get vector of trees, not research factor of tree, vector of tree note, I will name it R, it will be a better name from here and right BSTC will be found from here, then the same one. But if we pair them by applying a loop, then our question has become very simple. See how I said, whatever is the value of N, I will write a solve function from one to one and there are more values, this is it, now solve it. Look, I am defining, I will write exactly what was told, it can never happen that the start is given greater and it becomes start = end, meaning if we start = end, meaning if we start = end, meaning if we take the value of n as one, then you see start is b1. If there is one more, then what will happen in it, if we take the same value, then what does it mean, there is only one root, so I will just make a simple root is equal to you, made a new note, its What is the value of the start? The same is collected and value of the start? What is the value of the start? The same is collected and returned. Hey, we have to return the value of the vector in the vector. But if it is not so, is it? So what did I say, I will root everyone, one by one, I will root everyone, I will start from the start note and I will root everyone one by one, Start I &lt; Who will be on the right side from Start to I showed you above from plus one to and so what will it give me? Left BSTC, Right BSC factor, I make the root one by one, I made a new note root, it is equal, you are okay and who will be on its left side, okay that's it. What do we have to do at night? It is okay to return the result and if you have not seen that similar video of mine, then watch that also, there you will get the code, it is exactly the code, okay, so let's code it quickly and see, we have simply explained it here. It is written and the content is small so wider memorization of this question will also be reduced but science here we can memorize it also then we will do it ok two variables are changing so what will happen to me to fascinate me by taking two variables And what we are returning is returning a vector of trains for each value. Okay, so I will take a map and start and its corresponding result, this is what has come, see that too differently and now let's quickly finish the code. But before making the court, you can check the time complexity, it can be made as per the formula for making whatever is possible, because there are so many notes, so after visiting each note, I am making it. Okay, if you read more to make more notes, then n g. If it is, then the total time complexity is ours, it is okay, if you do not remember this in the interview, then date briefly, fine, you can tell me, if I change the number of murder number to M, then it is okay, then do not write much here, just say. Two number of catalog number would be the number of binary search, multiply it by N. What is N? The power of N/N is 1.5. power of N/N is 1.5. power of N/N is 1.5. Okay, 0.5 doesn't mean there is no root turn. Okay, 0.5 doesn't mean there is no root turn. Okay, 0.5 doesn't mean there is no root turn. Their power is 1.5. Then Their power is 1.5. Then Their power is 1.5. Then what will happen here is the power of four. The power of N/N what will happen here is the power of four. The power of N/N what will happen here is the power of four. The power of N/N is 1.5. Okay, this is the value. is 1.5. Okay, this is the value. is 1.5. Okay, this is the value. Keep this in mind. Slide: There was a mistake. Keep this in mind. Slide: There was a mistake. Keep this in mind. Slide: There was a mistake. Okay, now let's code like it was explained. We will do the formation of binary exactly where what is starting, what is one ending, what is n. Okay, from here we will return whatever result will come. Okay, solve our function. Even after writing, I know what it is, okay, and if start is my greater den, that means I have exhausted all the resources and I don't have any children, then I will tap return here, okay, and yes, we have to return in vector, right? So not just tap, form the vector like this and return it, show it by creating the vector like this, okay, I will also show you the Java code right now, okay if start is equal to you, what does it mean that there is only one note child, okay then we What we have to do is okay and if it is not so then I will try to make each note the root, the solution will be from start to I-1 and which ones on the right side will be from I-1 and which ones on the right side will be from I-1 and which ones on the right side will be from I+1 to and so I+1 to and so I+1 to and so I will do the retracement tomorrow, so from there I will get the result as usual. As usual, the left one is fine and push back in the result. It is simple to return the result to this route, we will also memorize it and it will pass because the constant is very small. Yes they have this question with out memorization, it is very easy to memorize it, one this start and this another change is happening, okay but on this start n, whatever was the result of the vector for these, I will return from here and If it is not so, then I will store it at every place before returning. Okay, I have stored it here. Correct results are obtained after doing late memories or not. Let's see after submitting it to India. It should also pass the date. Cases great, now let me show you the Java code, I have given the link in my description of Getup, you will also get the Java code below, but I will show you the Java code here, so look, this is the Java code, the complete code is here. We took this DP for memorization which I had taken in C plus ok here also from start and ran till in but look ok
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. **Example 1:** **Input:** n = 3 **Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 8`
null
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
96,241
91
hi all welcome back to cracking the fang interviews today i'm going to be talking about lead code number 91 which is decode ways this is again a recursion or dynamic programming problem that is very popular in interviews it's been lately asked at google amazon microsoft salesforce and i've also seen being asked at facebook so let's dive right in and try to understand the problem first of all so and here i have a snippet from lead code so what we have been given is a dictionary which maps every character from a to z to a number so for starting from 1 to 26. so for example a character here and i'm just going to call it a variable x could map to some value 10 and where x is a character and you can it's a deterministic value you can simply just keep you know following along so c will map to three d will map to four and so on but just to simplify the discussion today i'm gonna refer it by variable x uh to explain the problem better and what we've been given is another string which we are asked to figure out how many ways it can be decoded in so as an example if you're given the string 2 to 6 and we have characters which map from 1 to 26 by default the way 2 to 6 can be broken down is 2 can represent b or the other 2 and 6 can represent i'm guessing it's going to be some character so i will call it variable x and the other way this can be broken down is 22 which would be i am going to call it variable y again where y is some character you which you can figure out but this is a valid way to decode just to emphasize on that so 22 and 6 would be again x right since we are assuming 6 is mapped to character x so there are two ways way one and b2 to break down two to six and what we've been asked to do is uh figure out number of ways in which we can decode it and i mentioned this in my previous video about the climbing stairs problem whenever you are asked number of ways um it should prompt you to think about breaking down the problem into individual sub problems so here breaking it this way sub problem number one breaking it this way so problem number two and these algorithms are typically recursion and you can later optimize these the runtime of recursive algorithm which is usually exponential to with dynamic programming by saving solutions and convert this into a polynomial time and when i say polynomial what it means is as an example exponential runtime could look like o of 2 power n this is exponential polynomial could be o of n square as an example or even o fn anything which is ah which is a power of uh n wherein is the uh number of uh the size of the input given to us all right i hope the idea is clear what the problem is asking us to do we have been given a map we've been given a string we are asked to find the number of ways we can decode it so i'm going to emphasize on the concept and try to break this down the problems problem down into sub problems as i said and if you haven't already i recommend you check out the climbing stairs video before we go any further link is in the description the climbing style problem is a good fundamental problem to figure out how recursion and dynamic programming works i have explained it in more detail there and i am sort of using the concepts from the other video so i will pause the video right here check out the climbing stairs problem and come back all right so let's come back to the problem uh so if i give you a character if i give you a string three uh this maps to how many ways can you decode this if i just give this to you as an input how many ways you can decode this uh you can decode three to c and again this is given to us in the dictionary therefore num ways a string 3 can be decoded is one right and if i give you an empty string you can you cannot decode this right so again this is another base case that we are going to use so an empty string can only be decoded in one way which is no way and this is very similar to the climbing stairs problem check it out i'm going to go to the next case so this is case number one this is case number two and let's look at case number three if i give you a string which is more like one two three four five how many ways can you decode this so if you start from the left you can either start by one as by itself or take one to write as a character so one could map to a character and even one two has a valid mapping in the map given to us so the number of ways you could decode that would be num ways two three four five i'm assuming i am able to decode one plus number of ways you can decode 3 4 5 where i'm assuming we can decode 12 so the constraint given to us is any number which is between 1 and 26 can be decoded so one can be decoded 12 can be decoded but as an example 34 cannot be decoded uh which is here which could be the next step of the recursion i'm just putting it out what the constraint of the problem is and to sort of solidify this idea further let's take this string and solve it further ah again i'm gonna say num ways 2 3 4 5 can be decoded as b which is 2 and plus numbers um three four five right and so on all right so uh let me make a quick correction here i'm making up a new example just to add clarity so if the number is 2 4 2 7 4 5 the way you would decode that is b plus 7 3 4 5 and the reason i did that is you can if you start here if your pointer is at the beginning of the string you can decode 2 which is b but you cannot decode 27 as it's not going to be in range this is a better example to understand so you're forced to take 7 3 4 5 as your preceding string you won't exercise the other case like we did here where we took one two so you cannot take 27 because it does not fall in range so that's the important concept i want you to understand similarly if you break this down further you'd have to break this up as seven plus three 5 you cannot break it down as 73 and 45 because this is out of range all right so now let's start by looking at the code for this problem i'm gonna directly talk about the dynamic programming code and you can the recursive code is going to look ah very similar to this expression if you want to start there and the runtime for the recursive code if i were to start with the recursive implementation will be o of 2 power n since you can add max take 2 branches while decoding and this is very similar to the climb stairs video again i highly encourage you to check that out before we look at the dynamic programming solution so now jumping into the dynamic programming solution the first thing we do is convert the string into a list so what that does for us is it essentially allows us to iterate um at each uh each number at a time so 2 3 4 and so on so we've been given a string 234 we break it down into a list of strings or characters let's call it that then you figure out the length of this and you create a memoization table which essentially stores your solutions one thing i'm doing here and i really want to emphasize whenever you write a dynamic programming solution always think about storing your base case and for that you will need one extra element in your dynamic programming array which is the solution to the base case and where the base case is coming from is this if you have an empty string you the number of ways you can decode that in is one i want to make sure i highlight this so this is the base case you care about the other base case is if you have a single character sorry a single digit the number of ways in which you can solve it is one so these are the two base cases we are going to care about so what i mean is if you have this number 2 four and you're storing solutions at the cliff of this uh if i give you this empty string the number of ways you can you'll be able to solve this is one this is the base case essentially and yeah you know we will go backwards from here so this is the extra element uh we've added with plus one here and the value for this is one we set the base case um what we do is we discussed there's another base case where you're just given one um character one uh one number to play with which is four in this case you can if any time you're given one number you there's only one way to decode it so you set this here as well and what you do is you trade from here so length minus 2 so this is length uh length so this is length minus one this is length minus two the reason this is length is uh we create uh length plus one uh as the size of the array and we are indexing from zero so uh the index for the this last position is l length so we start from here uh in the for loop uh and if we hit zero um so if we had two zero and four uh we let's see how it solve it so the number of ways you'd be able to decode four is one uh the number of ways you'd be able to decode an empty uh string is 1 but 0 by itself is not in our valid range which is x is between 1 and 26 so anytime you hit zero you simply keep the answer zero again we are initializing our memoization array to zero and if that's not the case we check if we can form ah a number which is between this range of 1 to 26 the ascii characters if we can do that we decode this number as itself meaning just looking at the previous uh solution sub problem solution and the solution right after so in this example uh 3 4 can is not something you can uh sort of decode because it's not in range so you'll just look at one level behind and mark it as one this is the step but in the case of two three you are able to break it down into two and two three so the number of ways you'd be able to decode that would be looking at the previous solution at 3 meaning you're decoding as 3 but looking at a solution for 3 4 and also decoding it has 2 3 and looking at the solution for 4 so that would be 1 plus 1 2. so the final solution is going to be at index 0 and we return that i hope the idea was clear and this is going to be a linear time algorithm as you know we are sort of iterating through uh this once and the time complexity for this will be often the space complexity is essentially this uh memoized array that you've put together the space complexity is also going to be linear it's of the size of the given input awesome i hope this made sense and please feel free to send in your questions in the comment sections uh if you like the video please like it share and subscribe to our channel we'll be um sharing a lot of exclusive interview questions asked
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
417
So hello friends, welcome to the new video of Ticket, today is our 70th day, we are going to finish it soon, Pacific Atlantic Water Flow, okay, this is a medium type of question and what is the question trying to say, you can read the statement. There is a link to both the question and the answer. I will give it in the description. For now, let me explain what the question is. Okay, so if the numbers are written here, it is like this, here is five, here is three, here is van, like this. That water goes from highest to lowest, so if water can go to both Pacific Ocean and Atlantic Ocean, then include it in the output. A list of lists of outputs will be made. For example, if it is five, then it means that If you want to include rows and columns, then five can go up, down, right, left. If you do not take it diagnally, then neither can you go up and down. Now tell me one thing that there are two conditions for the flow here. First, there should be a small address in front, only then. It will be able to flow by going and the second one in front should be equal, then it can flow from five to van, it is small, then it can also flow from van to van, if it is equal, then it means it can go to the Atlantic Ocean. After van, it is straight. Atlantic Ocean is talking about hair, it will be able to go from three to one punch to three because it is small, it will be able to go from three to one, it is small, then Atlantic Ocean has become, can the Pacific also go, then from three to two punch, then the question of money i.e. three to two punch, then the question of money i.e. three to two punch, then the question of money i.e. Well, whatever row column this one is, it will be added to our output answer. There is one thing here, if we do brute force technicality, then we can see each particular that this one will also go, you will also go. Isn't it all these, even the money can be spent, there is no problem in the question, if there will be repeated work here, that is, if I saw for the punch, then I will also see for three separately, so what will happen in the root four technique? All the rows and columns of it will be cleared because tell me the time complexity because now we are doing repeated work here, so what is the way to avoid it, one way is that we know that Pacific Ocean here means topic and left side. If the question of money also comes then these money will go to every corner. Talking about hair, right and bottom go to the Atlantic Ocean. Okay, so one thing we can do is to do it with DFS. Okay, BF is DFS, something. You can also do this, for now I am telling you the method of DFS so that we can also look at the question once again that if we go from top to bottom, will we be able to reach the Atlantic? Talking about hair, if we go above the Atlantic, it means that we should not do this to people like three punches. Let's go to one and go to Atlantic, we have to move backwards, how to move backwards? Look, if the one in front is bigger, it means it will be bigger or equal, then can we go to three, because three is bigger than one, so we are taking the opposite case. That is, we will not go out from inside, we will come in from outside, then if our water can flow inside and can flow at any place, it will mean that the money in question will also go to some other column and will be the floor of the Atlantic Ocean. If water also flows on the same row column then it will become our common and we will take that common in our answer. Okay, so we will keep in mind that give greater and equal tu case will work i.e. N one will not work if we go case will work i.e. N one will not work if we go case will work i.e. N one will not work if we go outside. If it is inside then I will hold the row in the initial. What we will do once is that we will hold the first floor and look at all these columns, come down from the Pacific Ocean and do the same in the bottom one and then do the same in the right and left ones also. Okay, so this was our question and you must have understood, let's come to the answer, so this answer is basically accepted and I have also submitted it, okay just do it now, so I thought it is visible, okay, the submission is also correct, so one If we tell you that in this question I mean easy, then it would seem that Han Bhai, it is easy, so we have taken more columns for each day, the length of the front is the length of height, I will look at it in the description only, it must be visible in the figure. The initial height will be whatever its length will be and what will be the height for the column, we will take the height of zero, I have already told you this many times, how many are there at zero, so how many are there at one, two, three, four punches here? If there is a punch, then we will take two sets. Okay, keep this thing in mind because we know that it should not be repeated again and again, so if there is already value inside the set, then it is okay and finally, which will be the output which will be our answer. Let's take it as empty, then we will end the app in it, later we are defining the DFS, okay, it has four parameters, first row column is from office, third is visit set, I have done this many times, previous problems. I take the visit set to see if the visitors we have already visited are not reaching that place before and each previous site means this was necessary, why was it necessary because we know that the previous one matters that if the The one which is smaller is taken out only then water will flow from the next one, same thing here, this one condition will return nothing, why see, if our row problem is already present in the visit, it means it is repeating then don't. Look brother, our row columns are less than zero, this is our equal tu, when it goes out of bounds, if equal tu give greater then we will let it reach, equal tu itself got caught in row and column, if equal tu is there i.e. There should be one less. If tu is there i.e. There should be one less. If tu is there i.e. There should be one less. If seen, it is one less than zero, then if it is behind or ahead of zero, it means there is a problem or there is another case that if our height has been taken, it is okay, then do not get confused. It is written that it is flowing below or see it like this, it is happening above the floor, wherever the flow is happening, just see that the height of the raw column should not be small, it should be big and if it runs evenly then the flow will flow. It will be possible to come inside, it is okay and if it is our case, that is, all these cases are false cases, then return nothing, we will not do anything for them, if it is not so then initially it will not happen. Our row and column will be added to the visit set and we will run this operation on that row and column, do DFS four times, okay, you can do it by taking a loop, but there is no problem in doing it like this, up, down, right, left, okay, then you Bottom left right, so we did the same thing one by one and add all the parameters initial, we will add the same row and column to this one because it was there, right, now we ran this loop, first for C in range columns, okay so. For whom did we first run 'C' in the range column, run 'C' in the range column, run 'C' in the range column, we took it as zero, 'Row' we took it as 'zero' we took it as zero, 'Row' we took it as 'zero' we took it as zero, 'Row' we took it as 'zero' i.e. which row is ours, which is the first row, this i.e. which row is ours, which is the first row, this i.e. which row is ours, which is the first row, this money was also questioned, 'Who is the first row?', we money was also questioned, 'Who is the first row?', we money was also questioned, 'Who is the first row?', we took this row and the column will keep changing. That is, we are going to reduce the different columns to these five columns. We are going to start from the first of all and from the side of the row too, we will enter from the bottom, right? Which will be the last row minus one, so here punch one, all these columns. If we catch and go up from here, then to go up, first of all, we know that money also comes from above, so we have taken it, and whatever will be the height of zero, meaning cry, then it will remain the same for us, this also has to be written here. No, this also has to be written here, it is okay because our Roman Reigns van will remain the same, the column will keep changing, if we look at it from the Atlantic question, the rest is the same, only what is below here is the Atlantic Ocean, P means money is also a question, we have the column in Talking about RAW. See, now let's talk Rocky, that is, we talk about the first column and if we talk about the last column, then the column will remain fixed in it, so the initial first column was zero, the last column will become minus one, the cases were above from and the first one was money. Okay, this headline is fine, so we have divided these two, we have checked which one will go in the Pacific, which one will go in the Atlantic, now what to do is that the final look which is ours is actually its time complexity, you of M * It will become actually its time complexity, you of M * It will become actually its time complexity, you of M * It will become N and it is also present in Atlantic. If you want then adopt it in the answer. If you had taken the answer from our first then it would have made a list of lists. This was our small code, now I must have understood it and I will also give its link in the description and we are very close, I have given it in the play list to solve it
Pacific Atlantic Water Flow
pacific-atlantic-water-flow
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`. The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_. **Example 1:** **Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\] **Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\] **Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below: \[0,4\]: \[0,4\] -> Pacific Ocean \[0,4\] -> Atlantic Ocean \[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,3\] -> \[1,4\] -> Atlantic Ocean \[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,4\] -> Atlantic Ocean \[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean \[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean \[3,0\]: \[3,0\] -> Pacific Ocean \[3,0\] -> \[4,0\] -> Atlantic Ocean \[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean \[3,1\] -> \[4,1\] -> Atlantic Ocean \[4,0\]: \[4,0\] -> Pacific Ocean \[4,0\] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. **Example 2:** **Input:** heights = \[\[1\]\] **Output:** \[\[0,0\]\] **Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans. **Constraints:** * `m == heights.length` * `n == heights[r].length` * `1 <= m, n <= 200` * `0 <= heights[r][c] <= 105`
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
null
942
okay cool 942 di strain match given a string s that only contains I or D that n is to go the length of the string we turn any permutation a of just some way such that for or I guess suffice you can add and well yeah a survival item it 10 the next car gets bigger if not then if it's teeth and it's smaller okay and they all have to be between 0 and n and 10,000 okay and I suspect it's some sort 10,000 okay and I suspect it's some sort 10,000 okay and I suspect it's some sort of query haven't we had a deal at the end for example ITV then this asked such as for and it career maybe okay nothing it's just greedy wait you just you have numbers from the top and the bottom or over them or fun and the end and I just kind of keep adding them Topanga we gonna die with D that's my guess and then playing out of it we took a hit who i mr. tenets matter what number I guess Hawaii man mr. Lipscombe no that's fine I think that should be called to say number two head on the tail you finally learned how to use this tip thing you just click on it I actually did another know that for a couple months so you made laughs I'm laughing so that's right oh cool let's go for it cool uh okay well I don't think I'd take you late my thoughts on this one very well to be honest I just kind of went for a couple of things but I guess most of it most of what I thought was just that and some of that is kind of matter to be honest which is a little unfortunate in that like if your day with this is medium maybe I would have thought a little bit harder about how greedy could be wrong maybe yeah so I don't know if I kind of have like better cheated that way that makes sense I think some of that was like because it's easy that's one and then you look at the constrained and is your ten thousand so you know it's come here Fabio and maybe I'll n log n but like just doesn't seem like an N log n type form but maybe some kind of longest increasing subsequence I think then again not again but again it's easy so I figured probably oh it's over bent and it's kind of weird that so much of this is kind of a little bit matter e but so what that is greedy I just figured like well I don't know how I came upon it to be honest I just thought well it's greedy there may be on every decreasing then you know that you want the three years big as possible because then it doesn't matter what the sequence is like because if it's increasing you take the smallest number then you could essentially ignore it from the rest of sequence where like almost like a recursive e thing type thing where you chop like just sub the sub sequence will be also good so I think that's you start why the greedy works and I'm kind of proving it fish probably now but uh for example you'll get the same answer offset by one number if we take the substring which is just tid and so forth I think that's how I kind of have an intuition for it and I mean if I wasn't into me life I would try to explain that a little bit better why would it be very slow in an interview because I think I wouldn't have excuse me cuz I also knew that this would take like I don't know I'm minted to write so that I could kind of test my hypothesis really quickly I was just like trying to prove everything for which I'm an interview you know I wanted to do that and have to be confident about you and it's until like you really surprised him when you're like yeah actually yeah I mean I've I had a rant about in greedy solutions on interview qualms before and this is kind of I don't think this is an exception I mean some that is that what the code is pretty sure it's a you know it's not in enough like and it helps disproportionate what people have seen it and greedy or so it's just like weird how I describe it but it's like a real like maybe like curve and that's you're really confident we're like the puke oh very good and already erasing this problem they would get weight quickly and the people cooler maybe not as strong but doesn't know anything you know like they only believe in greedy or like you know they believe in greedy so they just some way the greedy solution and hope that's why we're oh yeah I need to read up what that means but I feel like for me and maybe other people where my skill level which is a lot I think the thing is that like I feel like every time I do I assume something is greedy I get burned like I'm like oh actually now it's dynamic programming in so and so therefore like every time I see something that I think it's greed I'm like very suspicious and then it actually takes me longer than someone who might not you know think it's dynamic programming so I don't know that makes sense that's my logic anyway oh yeah I mean I think yeah you just have to prove to was it called just you know fair I feel like I am NOT maybe that's just one of my weakness maybe I should practice that but that's harder to practice sometimes because like I look at a list of greedy solutions then I just know it's greedy like greedy prompt that no is greedy so then it's hard to contest with that we're like dynamic program for example I could still practice it because knowing something is a dynamic programming solution it's not good enough you still have to figure how to you know how to draw the dependencies right for example and how to program it if you will in the right order which is also like not the same family problem oh yeah I don't have your viruses in your impression I think I hope that uh I eventually get about get disease in question did I feel like this is also one of those farms where like yeah ok you saw me and I did in a couple of minutes per like you give me another day where I don't know maybe I ate is over too much for lunch and maybe a little bit you know less optimal for and maybe I just don't get it and that's something that I'm aware of myself which is a little unfortunate but um yeah but they're still using a lot of people like it so maybe there's a easy discussion greedy thing yeah good all right cool I think that I'm gonna say about that one so you know well and like it's like five lines of code so there's really not much to clean up the code and also I forgot to talk about complexity which is clearly off and uh and in terms of return space because that's outfit sensitive so you have to be on event so you can do better than that but all one extra space on top of the output sensitive complexity
DI String Match
super-palindromes
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
Math,Enumeration
Hard
null
22
Hello friends, welcome to the new video, question number 22 Let's generate code for parents, this is a medium level question, this is a question about backtracking, you people will find this question on the internet, it has been asked in Facebook and Microsoft, let's start with the right function to generate all combinations. Of value from different places, what does it mean? You would have got 12345. Anything can happen. According to that, you have to generate all the combinations of value formed parents. Let us understand this question in detail. Let's see the example. N. Anything can happen. 12345 N. If your If there is one, you can use an open racket, you can use a project and create value from different places, your two is two, you can use open rapid or you can use it for employment and create value from parents, MP3 is so. You can use these open rapids, you can also reduce Jatin and in all the ways value is created from paralysis, if you have made it pure, then keep one of yours open, use a glass of it and you have made welcome friends, if it is Pattu, then yours. Use two your rapids, use two close brackets and you have seen two ways value can be created from parents, you have given three, use three open rackets, use three close back ends and you have seen five ways value can be created from princess. So some observations will have to be made in this, the first observation is that if you have an entry then use your three open rackets, use three close ends, then the length of the string which is ours will be six. Okay, one more observation will have to be made in this, as many parents as these are important. All those who are starting are generating, they are starting with open racket. Okay, so let's take an example. Let's take two of them and after generating, we will see how the parents will be generated. Okay, so there are some rules in this. Have roll number. Vansh, all these are just different, it is starting with open racket, it is okay but now you neither have a decision, you have two choices, now you can use open racket also, you can also use it, just first of all you have to start with open. But you will move ahead, now you can play open rapid and you can also play close racket, okay but for how long you have to play open racket, there will be some limit, somewhere we will stop, if we take some examples then for how long will you play open racket. If N is our two then we can hit two open rackets and cannot hit more than that, then one more condition is coming that as long as your open racket is less than the van, keep hitting it as it will be equal to inches, there we will stop. Because we are Guru, after opening it, we will get two, so we will stop till it is less, let's put it, okay, so we are going to do it, we are going to keep it open on the left side and put the employees back on the right side and so that the sequence is maintained. In view of marriages, so that the left side will be kept open and the class will be held on the right side, so let's start so you have put the open racket on the left side, okay, you have put your closed back on the right side, okay now we will explore the left branch, now again we have two The choice is the decision. Open racket will be placed on the left side. If you look at the right side, can an open racket be placed? Already, if you have already placed two apane rakhegi, then the open racket cannot be placed on the top. This branch has crossed ours and we are ahead of this one. Can't go, okay, now we have to put a clothes rack on the right side, so can it take time to close or can it take rolls because right now the close rack is less than our open rack, keep it open, we had two, so we installed only one after looking at it. So right now it is not such a big issue, but we have to see one more condition that if we have more closed rackets then it is okay for us not to put extras, then we should always have less closed rackets than open rackets, till then you keep putting more like open rackets and When the close racket becomes equal then you stop, okay then let's add one more role that the project will run continuously till the time it is less than the open racket and as the close and open become equal then we will understand that now we are not planning the project. Okay, now let's do more exploration and we will see that the left side is crossed and there are two stars in the right branch. Okay, and the left side has to be fitted with an open racket, the right side is closed racket, so an open racket cannot be fitted. You have already raced. Yes, okay, let's cross here and on the right side we will put a close bracket, so can we put a close racket, now we have a closed back side, we have one and open rackets, we have two, so close, but we also have less, so we can put a close begum. Okay, now it is equal but at that time we could have estimated that our projects were less. Okay, now let's do Explorer again and from this point also we have Arpan 201. Okay, what are we going to do on the left, it will take us 15 minutes on the right. Secondly, if you want to bowl then first try open rapid. You cannot bowl with open batting. Can you bowl daily while sitting? If you bowl after seeing you, then the close rackets will be extra for you. If our condition is fulfilled, then close Beckham cannot bowl. Okay, so you will see that now we cannot explain further, so we will go back and then we will explore that now we will ignore from this point, the decision is on this point, we can apply it by opening the left side and you can go and apply it on the right side. So you will see that the open racket is still in use, so we have installed the open racket, there is no issue and if you have installed the closed back, then you will see that the clothes rack will be our extra. Okay, the closed back door is the open racket. You are still using an open racket. There was a close, so now if you put a close rack in the right branch, then the clothes rack will become your extra, so we cannot put a close back here. Okay, what are you going to do, now the right branch has crossed and follow the left branch. Here too there is 244 on the left side, what do you have to do if you want to put an open racket, then you will see that there are already two open rackets, so you cannot put an open racket, well, a closed racket can be put in this, everyday our racket may seem that we have less closed racket now, okay If it is then we will put it close madam and you will become equal to us every day. Okay, now you will see that we cannot do the explorer from the left branch, we have got the juice, we can ignore it from the right branch, so if you put the open racket then you will see that we will keep it open already. If there are two then you cannot put open rack and you will see that if you put close desktop then you will become extra in close rapid action. If there are two open rackets then they will become mud and if you cannot put even close wicket then you will see that you will not have any branch. Children, pay attention. So we have generated it, we have to pay attention to some roles, these are our basic rules, we can generate them by following them, okay, so let's come to the code and let's see how we will code it. All the parents that are going to be generated are the ones that we have. If we want to save it in a list, then we create a list, we name that list as result, it is ok and finally we return this list, it is ok in the end, so will you write a recursive function and all the If we generate benefit parents then we keep giving some name to this function, find all name is Dev and what all you will pass in it, we had discussed about this, I have to start with open racket and what will happen to me if I don't maintain the account also. What has to be done is how many opens have been placed, how many closes are there, so I say one open has been placed and one close will not be placed, okay and we have to pass this list also because we will save it in it, okay and we will pass this MB because we know. It should be that how many open rackets are to be kept and how many closes are to be put. Okay, so now let's write the recursive function once. In this, you will first pass your spring. Let's name it current. Okay, A. Open racket, how many is his account, close is Baikuntha, how many is his account and We will have to pass this list of ours, okay and how many open and how many closes we will be in it, and the information given to us in the pen is also passed. Okay, the code for this is simple. As you have seen, those conditions will be there, the first condition was gone. How many open rackets do you have to put after opening? If you have given us our dough then you cannot put more than two open rackets. Okay, if you sit open and put them, then how to do this in the village, let's make a call. Record nipple, then you will add open rackets. Which will be spring now, you will make your bread in whatever skin is given to you, okay, and you will say that the account of open has increased, you will not increase the account of clause, and there is nothing to be done in this, we have discussed the overalls. The closed bracket that we have done should be less than our open racket, till then you sit and keep playing every day and as soon as it becomes equal and stop, we had also discussed this, so here if you play closed racket, then now one of the Clauses Act. If you increase the account then we will keep knowing how many projects have been started by us, so this is the doubt code, you will see that all will be generated but we have not saved it anywhere, how will we save it? Well, if I say generate, then if my end is two, then generate is only one. Bed also and half come, then it was being generated like this, then some of it was also being generated, if it was generated in different ways, then finally our length of and of was also being generated, which was finally our length Praveen, this was also being generated. If it was, do you have to save these small ones as well or you must have kept only the but only one of yours, if you have to save only the land for, then we do n't have to save all the small ones, what will we do with this, we keep adding to our string. As much as our string is going to be created in the recursive function, then we will say that when its length becomes ours, I will end it with 'to', created in the recursive function, then we will say that when its length becomes ours, I will end it with 'to', this means if I have given 'to', this means if I have given 'to', this means if I have given 'to', then I will say basically, its length will be ' then I will say basically, its length will be ' then I will say basically, its length will be ' for'. Only then would you like to save me or if it for'. Only then would you like to save me or if it for'. Only then would you like to save me or if it was my house then I would say Strickland, if it gets stuck, set the phone only then will you ever save it and what will you do, you will add it to the list of results, okay, add it to it. If we give you anything else, then our job is done. Lastly, here you can do one thing, if you want that we do not want to explore further, then you can stop here now because we have already got the length and time, further length will be bigger for us. So you will go to the automatic route, you can also return it yourself, okay, then you should run it once and see, I accept and submit, okay, you will see this successfully submitted, there is more code, we you You can access my channel by going to the About section of this Google Sheet, in this you can directly see which interview questions' which interview questions' which interview questions' videos I have made, which list questions' videos I have made, you questions' videos I have made, you questions' videos I have made, you can see them category wise and can directly reach the questions. Whatever news related to the channel, you can see whether you have a date, what is the next video coming, thank you very much for watching this video and do it MP3
Generate Parentheses
generate-parentheses
Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_. **Example 1:** **Input:** n = 3 **Output:** \["((()))","(()())","(())()","()(())","()()()"\] **Example 2:** **Input:** n = 1 **Output:** \["()"\] **Constraints:** * `1 <= n <= 8`
null
String,Dynamic Programming,Backtracking
Medium
17,20,2221
902
hey what's up guys this is chung here again so this time let's take a look at today's daily challenge problem number 902 numbers at most any given digit set so this is a very interesting hard problem because this is more like it's related to the digits and it also asks you to use the dp concept to solve it basically this one is kind of like a dp with dj for the digits so that's kind of unusual all right so you're given like you're given into an array of digits and you can use any digits as many times as you want and you can write though you can write them in any sequence the only cons the only constraint is that you need to find the mean the numbers you write has to be equal or smaller than the target than this integer n here and it asks you to return the number of positive integers that can be generated right the total number of positive integers that can be generated given this digits array here right who which whose value is equal or smaller than the n here and there are some examples here so the first one like the example the 20 here right we have sorry we have a 100 equal is a target and we have four digits here and then we uh we have 20 total possible numbers whose value is smaller than 100 okay and here we have yeah i mean this one is pretty big that's why i mean similar but we have a much bigger output here right so on so forth yeah and here are some constraints here all right so given these two parameters how can we approach this problem right so i mean to solve this problem we have to think it in the in we have to split this problem into us into several small some different scenarios so the first scenario is what the first scenario is that you know as long as the total numbers as you guys can see so the numbers could be from one let's say the uh no let me change this one to big end here okay and then we have a since we're going to uh i'm going to have a string equals to a string dot n right and then i'm going to have n equals the length of the end string okay so let's assume let's say we have a the total target digit is and the length is n so from 1 to n minus one right oh by the way and the uh the digits is from one to nine so which means that we don't need to worry about the leading zeros okay so anything should be a valid digits okay so okay back to here so assuming so let's say the total length of this target is so which means that from 1 to n minus 1 we can use any number for each of the digits let's say the n is equal to four so which means that so the length from length one to from for length one two and three we can use any digits on each of the digits right so which means that what so let's say the digit is this four is this fourth number so with all the uh so with all the length equals to one right what how many options how many digits options we have four here right because we can put either of any of these numbers at this one digit that's why we have four how about the two here so let's say we have two digits and when we can use any freely use any of the digits that's why we have a 2 to the power sorry 4 to the power of two so because on each digits we have four options and since we have two total two digits that's why we have four times four same thing for three four to the power of three okay so that's the uh the easy case where uh whose length is smaller than the n right and so i'm going to write that real quick here so since i will just talk about that you know so for that you know what we have a let's say we have an answer equal to zero and then we have four i in range of i'll just remove this part here so in range to what one to n right so this is from one to n minus one basically you know and the answer is what the answer is like the uh the length of the uh the digits right so let's define the length of digits i'll just call the digits in here so it's going to be the length of digits so here we have the length of digits to the power of i right so that's the length smaller than n right cool so that's the easy case and the more difficult part is the when that when the length is the same off of n here for that we have to consider the answers digit by digit so what do i what does it mean it means that let's say the target assuming the n is like 2 4 6 7 8. so this is the end right and so what i mean by consider the digits uh one by one which means i'm so for this one i'm going we need to define like a dp here so the dp i so the dpi means that you know from i to from ice digits to end digits assuming the uh from ice digits to end digits like what is the total positive numbers integers by given these digits whose value is smaller than this part let's say we have a this is i let's say this is i and the dp means that from the current i's location to the end what is the total count for the positive integers whose value is less or equal than the than this part okay and to calculate that we have to there are like two cases actually there are three cases so the first case is like this i mean basically we will try each of the digits here right so at this location this is n right so this is and so we're basically we're going to try each of the digits so when we compare with the current digits of this end here and basically there are three cases right scenarios either the current digit is greater than is smaller than this one or equal than this one or greater than this one so whenever let's say the digits let's say the current digits is smaller than six let's say the current digit is two right so what does it mean it means that assuming the current digit is it is two it means that we can freely put any digits on these two on this two position right so which means that we can like use the uh we can just use this formula to calculate this case which is going to be the uh the length of the digits to the power of in this case is two yeah but we're gonna have like the uh so it's gonna be a n minus i plus 1 something like that so that's the first scenario where the current digit is smaller than the six right because since this one is smaller than this so we it doesn't really matter what we have here so that's the first case right so that's the and the second case is equal it's 6 is equal to this one so whenever the dj is the same as this one so what do we have basically we cannot freely put anything we can we cannot freely put any numbers here but it happens to be that you know since this one the same so it happens to be the dpi so the dpi will becomes what will become the dp i plus one right because the dpi plus one is the total valid count starting from here which is exactly the equal case for us because then what because whatever we have in dpi minus one it will be the same in this dpi here right because the c because the current digits is the same so we're are on the uh on the dpi plus one to tell us how many valid numbers we have and the third scenario is like it's eight let's say for example is eight so when that when it's 8 of course it's a this is an invalid case because this it's already this 8 is already greater than the 6 7 8 is greater than 6 which means that there's no more digits right that can start with eight that can satisfy our condition here and yeah i know we just keep going backwards as you guys can see here because the so the difference for this dp is that we have to going from going backwards from the end to the start because the uh from the current digits we have to rely on the uh on the on our digits on the right side and in the end when we're at zero we will have and when we have it at 0 the dp 0 will give us the total count right for the length who's for the numbers whose length is equal to the are the same as this length here and then we just need to accumulate that summarize that with this answer and that will be our final result cool so and all right so let me try to code this part so now handle the length equal to n right so like i said we need to have like a dp here you know at the beginning the dp they're all zero because we're storing the uh the valid count right starting from here to this is from i to n right and for i in range of the n minus one right like i said we need to start from the end and we try each of the digits right because we have to try it because for each digit we have a different scenarios here for each digit in digits so the first case is if the digits is smaller than the uh then the n string dot i right so if the current one is smaller we can just accumulate we have to use digits and to the power of up this one similar like this one but we have to calculate what's the remaining digits right so the remaining digits is n minus i minus one okay because the n is the length and the i is the index that's why we have to also do a minus one to get the remaining number of digits okay and so for the remaining digits we can freely use any of the digits right all right that's that so else if right i'll see if the digit is equal to the and string i so in this case like i said the uh the value will be the same as the dp i plus one okay because the current one is the same and we have to just use whatever we have from dpi plus one and then in the end we can simply return the dp0 right and then plus the answer because the dp 0 will stores the total result for the length that's equal to n and actually here there's like small corner case edge cases we need to be careful because we're starting from n minus one and we uh some we will do a dpi plus one you know so if the i is equal to n minus 1 and if we do an i plus 1 it will be out of the boundaries so that's why we can just simply do a check if the i we only do a dpi my i plus 1 if the i is smaller than n minus one right else is just one right so this is the case where the uh the dj is the same as the two four six seven eight where the uh this is the digits the first it is and the current dj is eight which is the same as this one which means that it will be plus one right that's the that's one count yeah or we can just do a padding here you know instead of initialize it to n here we can do a n plus one and then we set the last element to one i think either way is fine okay so i think that's it let's try to run the code here okay accept it submit all right cool so it passed and let's see what's next yeah so the time complexity right so the time complexity is the uh so what is the so the digit size is n and this one is 10 to the power of nine but we're getting so actually the time complex is only the length of this n which is the uh what i think the length is a lot it's log n right so that's the length of the this end here and we have a for loop of the length here and another for loop of this one so the and the digits here is yeah so this it's only a constant right so it's bounded so here we have up to nine that's why the uh the total time complex is still the length of this which is the uh the log n yeah and the space complex says same thing because we have a dp here that's why the uh the space complex is also o of log n yeah all right so just to recap right i mean so for this kind of like digits related problem you know the uh it's always i think it almost always will relate to uh to comparing the current digits because the uh especially when you need to compare if the digits is smaller than target or greater than the target so based on the current digits the you will have different options like what we have here so in our case i mean we calculate the easiest scenario first which is the uh the length which is smaller than the target than the n here which means that we can freely use any of the digits on each on any of uh any of the numbers on any of the digits that's why we have this total numbers and then we'll use like a dp to help us accumulate the case where the length is the same as the n here so for this case we have to use we have to loop through each of the digits because based on the based on who is bigger and who is smaller with the current digits we will have a different accumula we have a different accumulated account here right for the so for the dj which is smaller than the uh then the current then the card numbers right we can just freely put anything on the next few numbers and the reason we're using the dp here is only for the for this case for the case when the djs when the digit is the same as the uh as the as a current number in this case we have to use the count that we stored in the previous dp which is the dpi plus one and of course for the last case which we can simply ignore that and then in the end we simply uh just add two values together and that will be our final answer yeah i think this is a very interesting tp it's not like a traditional dp or this is just like a dp with the digits i hope you guys enjoy watching this video and i'll just stop here okay thank you so much for you guys to watch it and stay tuned see you guys soon bye
Numbers At Most N Given Digit Set
minimum-number-of-refueling-stops
Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`. **Example 1:** **Input:** digits = \[ "1 ", "3 ", "5 ", "7 "\], n = 100 **Output:** 20 **Explanation:** The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. **Example 2:** **Input:** digits = \[ "1 ", "4 ", "9 "\], n = 1000000000 **Output:** 29523 **Explanation:** We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. **Example 3:** **Input:** digits = \[ "7 "\], n = 8 **Output:** 1 **Constraints:** * `1 <= digits.length <= 9` * `digits[i].length == 1` * `digits[i]` is a digit from `'1'` to `'9'`. * All the values in `digits` are **unique**. * `digits` is sorted in **non-decreasing** order. * `1 <= n <= 109`
null
Array,Dynamic Programming,Greedy,Heap (Priority Queue)
Hard
null
1,408
hi my name is david today we're going to do number 1408 string matching in array this is an easy level problem on lead code and we're going to solve it in javascript so the prop is we're giving an array of string an array of strings here and we want to return all the strings in words this input which is a substring of any other word in any order so for this one we have this array of words and we can see s is in mass so we would return as hero is within superheroes to return hero and none of us is within anything else so that's all we return so what we need to do first since it's asking us to return an array we create a new variable for this so first thing create output array and that's going to hold the output we need next one so we're going to have to loop through this but we know that the order matters so we don't want to repeat like mass can't be an ass but as can be a mass so we want to sort it from ascending length so sort words to ascending length so now we got that we can loop through words and inside this we have to create a nested loop so we compare this word to other words okay and inside of this nested loop we will have a we will check if check create condition if the current word is in the nested word so we know that so be in order for the small words will be in the bigger word and if it is we will have to push current word to output and then we don't want to get any repeat of it so we can break and then after that we return output okay so let's get started that output equals empty array and now we sort their words so words dot sort a and b from length a dot length minus b dot length okay so we got this word sorted out now we do the loop no we don't need this or let i equal zero i is less than words dot length i plus and now inside that we do the second loop for let j equals i plus one j is less than words dot length j plus and now we have to check if it's inside of each other so if the second word the nestor word words dot j dot includes words index i we know we have to push it output dot push words index i and we don't want any repeats so we break now at the end of this we return output great now let's check nice yeah so we got it so the complexities since we're doing a nested loop we have to do o of n squared and the space complexity we know that we are creating an output array that is going to be big as the words so it's going to be o of n and that is how you solve this problem thank you
String Matching in an Array
find-the-smallest-divisor-given-a-threshold
Given an array of string `words`, return _all strings in_ `words` _that is a **substring** of another word_. You can return the answer in **any order**. A **substring** is a contiguous sequence of characters within a string **Example 1:** **Input:** words = \[ "mass ", "as ", "hero ", "superhero "\] **Output:** \[ "as ", "hero "\] **Explanation:** "as " is substring of "mass " and "hero " is substring of "superhero ". \[ "hero ", "as "\] is also a valid answer. **Example 2:** **Input:** words = \[ "leetcode ", "et ", "code "\] **Output:** \[ "et ", "code "\] **Explanation:** "et ", "code " are substring of "leetcode ". **Example 3:** **Input:** words = \[ "blue ", "green ", "bu "\] **Output:** \[\] **Explanation:** No string of words is substring of another string. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 30` * `words[i]` contains only lowercase English letters. * All the strings of `words` are **unique**.
Examine every possible number for solution. Choose the largest of them. Use binary search to reduce the time complexity.
Array,Binary Search
Medium
2188
1,288
Jhaal Hello Hi Guys Welcome To Dad Sales Today's Question Is When To Remove At Intervals In This Question Which Will Stop Intervals Where To Remove All Intervals Baithak Covered Boy In The Interval Hindi List Interval A Copy Squad And Interval Scene From A Different Only This Series nickel to have and beat them equality of doing so better returns in number of revenue intervals so let's understand this question example see in this list 2001 14821 and form a which vacancy date 144 entry ko monthly share and not getting kabaddi head to comedy short Intervals And 361 And Se Interval Between No That In The Interval 2.3 Thomas No That In The Interval 2.3 Thomas No That In The Interval 2.3 Thomas Equal To President Should Seek Cover In Trouble Due To Remove This Possible Because It's Already Present Hindi Enter The Stock Market Will Remove The Terrible And Will Determine The Original Avoid A That Are Yaar please forgive the monkey and * Kamat Yaar please forgive the monkey and * Kamat Yaar please forgive the monkey and * Kamat in sea vacancy Bittu ko mat is already been recovered in this son of Sudhir son of two Gomti Chakra interval Supreme Lord to remove the two Gomti swimming interview will be given for evil returns one and discuss in example 48104 cotton fabric Eleventh Vacancy Back Cover Interviews For Comment Because In The World And For Whom The Also Exists As President Internal Video Me Enter To Remove This Is Ki Beti Mumbai Central And Eastern The Evening Answer Sudesh The Question Not Look At You Approach Now This Question See The Question Is Very Simple But Powerful But You To The First Governor General Lord Vishnu With This Time The Will Not Listen That Ascending Order Basis Of This Time Swift Filmy One Comes For Due To Come Again Welcome A Ko Bhi To Achhi To At All Don't Forget Shri Ko Machli Comedy Been Converted Into Prominence Software Update Vihar Metro City Code For Selected As The Best Cadet But Will Do If Vector Interwar 2004 Interwar Se Z Not The Least Not And Up Resident Evil Returns Roti Interval Dot Size 100 200 300 Now They Are In This Case Which your program will reach willow dip condition daily date are you dare devil at least consist of only once interval difficult ishwar interval dominar account will be one delhi switch possible between sudhir will take into account equal to one will celebrate with one because no data is That it will be interested in this is not equal to be road will be at least one big brother will be at least one interval which will be novel and covering all the intervals sir counter affidavit start noida delhi yesterday to start the doctor in twitter hindi ascending order Descending Time Slot Will Do War Custom Pattern Discuss The Co Mute The Custom Batter Let's First Ride The Custom Batter A Ki Dot And Lag Cinema Custom Address Computer Only A Ki Doctor It's Right Custom Computer CC Bullet Return Max Batter Hai Apne Computer Is Din Name Of This Function And Arguments Every Passing RJ Devi Digambar Jain Bittu Intervals Interval And This Interval Correction 11015 Home Twitter To A Hint That We President And 1 And Similarly Vectors Secretary Also In Temples And Being's Name Mirch A Budhi Person Handed Over Website Interview Of Investors Sa time it is very starting from scene in the world who will choose backed music values and intimate scene after 10 minutes with oo started consuming it means in this study shot the short intervals basic course in descending order of the pending time and acid notification Will Return To 90 Student Video Member Custom Meeting Buddhi Typing Same Will Soften Desi Beat And In Time And Descending Order And Will Start From Not Sample Spontaneous And Wore This Time He Zerre Customer Nobody Does Not The Length Of Withdrawal Not The Least One Will Cover All The Point And Updated On Ki Intervals 108 Sisters Of Indies Equal To One And Will Be Equal To A Ki Intervals 201 Schedule Bad Intervar 09 Values ​​In This 201 Schedule Bad Intervar 09 Values ​​In This 201 Schedule Bad Intervar 09 Values ​​In This Thought And Daddy Ki If Parameters For Comparing Date Bhi Chaube Interval This Particular Interval Discovered And Fourth Inter Intervals Not Recovered So Start And Don't Topic-Special Starting And Don't Topic-Special Starting And Don't Topic-Special Starting And Don't Refer 2011 To Forgive And Beautiful Look At Some Thing If One Dos Sexual Internet Sites That I Plus That Boat Also Chilly One See When No One Will Dare Attack In Trouble Caused By The Interval This Is The World And Beat It For Intervals Of House 90 Is Greater Than Or Equal To Start And Intervals Are Now High Command Is Less Nikalti And Bismil Thc Basic Double A Particular And Intellect Which Were Standing Right Now Is The Cover Interval Subha Will Do Nothing Else Continue Select Features Example Suppose Beneficial In The Form Of Karo Ko Support Other Initial E On Karo Ko Support His Father And Sleep With Only Two Intervals Vinod Idea Music Jasmine Ko Batukamma And Some Interesting And Starting Start Value Is The zero-valued is Is The zero-valued is possible And Interviews of 136 Withdrawal Is Cover Inner Being Converted Into This World Will Continue Till And Vitamin C E O Tomorrow Morning Minute Sorted Vikram One News Main Nachu Aaj 12th Class Which One Oo A Time In Charges One And Will Be Influenced By 4 Wickets Starting And Will represent the starting point of time and in order for the interval 9 loop start from this induced into middle travel frilly and they are not hidden difficult come to the current 10 position so is video start intervals of the position of kar underworld don this is not Agri Vid U Ki Naav Badodiya Statement Will Update U End Will Updater End Value Will Update First Vikram Minimum of Current 100 Interval Ki Ko Ma 0 Under End Will Earthquake A Maximum of Current End Intervals Ki Intervals I Ko Ma One I Anil V Account Plus This With Example Now It's One And Internal From His Position Not Valid This Is Not Valid Notes Will Start At The Starting Of Wave 2K's Hunter And Vikram A And B Coming Maximum Thicker Maximum More Current End And Depending Valley Of Depending Value Of The Current Interval justice for all my attend maximum is 800 vidmate no stop this one end edit sukhbir wa veervar ko subscribe intervals not only for oo hua hai aur yash infaday buddhist 69000 note khabar sunao notification hai front swasth that has been updated and has been nominated for justice One and short and jaipur plus veervansh hai necklaces done so far account current account is to 9 international bluetooth next election 2013 ko masik again for this condition researcher at intervals of asbestos setting bull icon interval this great and start getting s301 disciple condition and position of this Current Interval So If End This Year subscribe this Video plz subscribe Shravan Underwear Continues at Doing All This Step Will Be Found Accordant Travel and Will Return Account Government Delhi Has To Do So Will Return To Only In This Case Fast Track Court Of This Question Demonetization Code Number One Thing To Note Here That Even In Another Class 10th Class Admit Due To Be Used For Running December 10 A Way That To Record Your Help Won's And Accepted Aayog Ne Jo Lagi To Video Thank You
Remove Covered Intervals
maximum-subarray-sum-with-one-deletion
Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list. The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`. Return _the number of remaining intervals_. **Example 1:** **Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\] **Output:** 2 **Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed. **Example 2:** **Input:** intervals = \[\[1,4\],\[2,3\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 1000` * `intervals[i].length == 2` * `0 <= li < ri <= 105` * All the given intervals are **unique**.
How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm.
Array,Dynamic Programming
Medium
null
279
That fans festival, the question above has been asked by taking minimum squares, you will get your number, you have to tell in how many minimum number of squares you can represent it, what does this mean, like if there is a note, then one can get pregnant by smelling only one number. If yes then the answer will be like disgusting two because I can appoint as both how many numbers can I subscribe and what is the minimum number I can subscribe like it is war the difference for 17 is 4 like this subscribe our channel So while talking on four numbers, subscribe and then subscribe, if not at all, then tell me, I am 10 and 506 and signing the meaning on an index, I give you, I have set it, so according to me, I will make the fiber innocent pipe. How many of my phone numbers can be made clean? You can start there but this is a completely different and opposite way. Let's try a new way to source. Zero on robbers cannot be specified for any number, meaning no other number will be included in it. One number is deposited from the campaign of one, this number can be presented as 108. Now I will do one age option above but on behalf of this Vada village, it can be said that from here and from here, how many will you get? Day, you could have said minimum from there, from here we see this here, inside I have seven square, you have number 11, from number 11 and you keep it aside, now here we have put the value 251 more and there is no other option. If there is more, then remove it here, see if subscribe and the remaining 22 numbers are one plus one, I feel that I have some problem here, look at this, now from inside the phone, I have an option, but let me remove it, okay, then the rest. Do tell me, it is free, that three becomes that pressure, okay, then 30 to 14, one option, four numbers will be taken, Sanskrit decisions on 1000 saved in 24, what is the second option, this is MS Word, sure that you have a cartoon on it, each other's total is 40. So this one number, this happened in real life, so we were in the past vs. Braun, the answer to the previous birth came to us, we will start off here that my mom will be made from this tree of one numbers, this time of any one, now half of it 1015 Special Thermal Officer, I am getting four numbers here. It seems that number 212 can also be check-in. I 212 can also be check-in. I 212 can also be check-in. I got a little late here too, it does not seem different. The stuff should have been a little clear on this number. Wherever the teacher and If I take out the name 'Open Squash' teacher and If I take out the name 'Open Squash' teacher and If I take out the name 'Open Squash' then I went with the thoughts, take out one named 'Three or then I went with the thoughts, take out one named 'Three or then I went with the thoughts, take out one named 'Three or Two Speed', 'Neech Zero', you know the Two Speed', 'Neech Zero', you know the Two Speed', 'Neech Zero', you know the definition, it takes 3 from here, see this in this way, Subscribe 1510, nothing takes place, from here, 3000. 1000 Subscribe to here I also agree that there can be problems. Now see, one of the pipe pipes is that if you take it then put it once, beyond that it is fine, one is all done. 10 to 12 stances from the shop. Stuart Broad has his own. Seven in 25, at what time does a pig's tooth stop breaking, four by four, so friends, come now to the next time, Hello viewers, welcome to two square cartoon, so I have reached here, it goes further, one plus one, this is only one thing, I don't understand it. Aa hey man, you play supervisor, you have an ideological child, now this four one reaches zero in one step, it is a broken puja shop, it is written and there is a chapter on 100, it is the champion square root, so this is the report-2010, don't go one Till it's all both have this is the report-2010, don't go one Till it's all both have this is the report-2010, don't go one Till it's all both have one it's also present don't go on the other one sir it's all in opposition to forest Shiva and delicious ok so 102 in that you have purse from two and 2017 way does from 12 someone like is the same thing Okay, so I say that we did darkness and the other one went, shut the other's tail, okay, 12 is a matter of understanding, as if only one understands, now let's move on to teaching interest, plus 2 is an option, take it out once, please send it, no. If it happens then either take it out on it, okay now see, I take it out, so come friends, we can use the enemy, we can use two, then ours will be able to come, how much is the tubeless minister, an important one for 12 2012, two can be subscribed, so either He subscribe to subscribe as if he hates subscribe to I have set one thing and got the place. Okay, now let's do it together, look carefully. If it is a marital relationship, then this one is cheaper than doing it. Either put it behind this or this one. Back Other Subscribe Meaning if there is war then I can do 101 or do I have importance here there is a clear winner subscribe toe Abe if I talk about name then vansh and to sarkar has reached here this trees near cartoon so I will reach here E want to were with high school in this way so that three are theirs, from here they feel scared, from here they seem to be Hindu, if we had made it if we did not pay attention then 1222 from here, they seem to be friends, from here there could be another candidate, so minimum this Zero became zero plus 121 and here Dot Cervi is the smallest leaf thing to get a job. Okay, tankers use water, so make sure to put a cross here in the lineage, I will use this, so I am there when you see here. Minimum one on 1341, which became OnePlus one two, still in the last 10 minutes with spoon turmeric, we subscribe the channel, ok, we would have complained 101 from here too, half the body is a woman till the time she subscribes, but do all this. It is feeling more difficult that I have made a horror movie comedy new cent and plus one [ cent and plus one [ cent and plus one 1000 hoti aur dp of wave hoti ki ab point is quiet ushe oil dainik urdu and sculptural aaoonga hai and beech mein chalega look dega gas stove From the band and how far did it come that J*Jain has got this From the band and how far did it come that J*Jain has got this From the band and how far did it come that J*Jain has got this letter published in which both of them are running like Sochle Khol I No Clue in Haryana, it is 1052 400 and it will run in such a way that whichever you keep it smaller, it will keep increasing or it will increase. It will be that we can go to this post by subscribing and finding the minimum. Int mean equal to two will be included. Put in it the daughter value meaning of how much is the remaining. Come - Jeetu ji. how much is the remaining. Come - Jeetu ji. how much is the remaining. Come - Jeetu ji. Okay, if you are a great leader, then by combining one and removing the other, you will remove the other here. The job has reached the morning place, there is only deep meaning in this list, if you subscribe, then in the next two days, make it plus one medium and my dear friend, enemy, why will it take hard work, everything is yours and you have taken one but Ujjain. If the Ujjain one is fine then we will return, BP will see them from here, submit this chapter and write that it is done, the said leaders will understand, let's meet in the question, thank you.
Perfect Squares
perfect-squares
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`. A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not. **Example 1:** **Input:** n = 12 **Output:** 3 **Explanation:** 12 = 4 + 4 + 4. **Example 2:** **Input:** n = 13 **Output:** 2 **Explanation:** 13 = 4 + 9. **Constraints:** * `1 <= n <= 104`
null
Math,Dynamic Programming,Breadth-First Search
Medium
204,264
1,768
Hello friends, welcome to Day 8 of 990 Days SC Prep. This is the first question of Lead Code 75. Lead Code 1768 Merge Strings. Alternatively, I have made such an idea that I will make separate videos for each question and on Sunday I will do a live one for which Inside you can talk to me and if you have any doubt then they can be resolved. Okay then lead code is 1768 Merge Strings Alternatively I will show you the question, this is the question, you have been given two words, it is an easy question, it is a question of strings, it is very Easy question I think lead code has also tagged it as easy. Two strings have been given to you and you have to create a long string by merging both of them alternately. Ok, very easy question. It is very easy. Pick up the character, then pick up that, this is how we have to pick up the characters, if one string ends then we have to append the other one, so like I discuss in some examples, let us have a string, I have a. B C and the second string is D FG H I. So how to make the answer we have to make? Picked A from the first string and put it in the answer. Then we have to pick D, then pick b, then pick e, then pick C. Then F has to be raised and now there is nothing left at the top, so G A I has to be raised from the bottom, then look at A then D then B then E then C then F A B AD B CA Okay and then in the last when A is finished. g a aa so this is an easy question, for this I told you what I did, I used my merge to sorted sort trick. If you look carefully, I used the same trick. So let us say one is a b c d and the other is let. As Se D B G H I K M Okay, so I put a pointer here, okay and created a string builder, I will append from the string builder and placed a flag which will keep on being true false so in the beginning that flag is true like If that flag is true then if it is true then I will pick the character from word one. If it is false then I will pick the character from word two. So I picked the first character from here, picked a, then appended a in the string builder and increased it from where it was picked by a. Next was the index, I moved it forward, index ok and flag falls, this flag falls, now the flag falls, so I will pick it up from word two, I pick it up from word two, so I picked up D, consumed it here and raised it and raised the flag again. Made true, see flag is equal to not, flag is true then it will be false, if false then it will be true, now flag because if it is true, then I will go to word one. If flag is true, then I will go to word one. From word one, I will pick B. Consumed, increased the index and toggled the flag. Now the bag is false, so I will go to word two, so I have G here, wherever it is at this time, like it is standing on B, so B has been consumed. Next. Increased the index and toggled the flag. Now if the flag is true then C is consumed from word one. Increased the index and toggled the flag. Now if the flag is false then G is consumed from the word below. Increased the index and toggled the flag to true. If the flag is true then I consume D from the top word and increase the index and toggle it. If the flag is false then I consume it from below. I consume A and increase the index and make the flag true. By making the flag true when I When I reached the top, I came to know that the upper string is finished, then I just put the lower loop and consumed I, K and A, so as long as both the strings are there, I can use the flag. I will keep consuming it. If one string is finished, I will completely consume the other string. So bring me its code. I will write it in front of you. So it is simple. I have made a string builder. Why do I have to make a string builder? If you add it to the string then it will be ok. Add is done, you will add it in the loop. Look in the loop. An addition is made of O in the string. If you add it in the loop, then O will become square. In the string builder, the one that is appended is of Ov, so I have kept I, which will rotate on the word one. Kept which will rotate on Word Two as long as both are within their limits, Aa has not gone out of Word One and H has not gone out of Word Two. Okay, so S is true, this could have been done through questions and other methods also, why did I do it like this because Just like this, I thought of this strategy, everyone knows the story of merge to merge array, okay, so I thought of it, so I used it, I kept one flag equal to true, which I will keep toggling every time, flag equal to not. Flag So now if I think carefully if the flag is true then I have to consume from word one else I have to consume from word two how will it be consumed String builder d append wave ka aa and the one we consume is the same Let's increase it otherwise if the flag falls then I will consume from word two. From word two we consume with the help of J and increase J only. Okay so sometimes aa is increasing, sometimes j is increasing and sometimes i is increasing. Is it ever increasing? Will one day come when one of these two will end? Our heat will continue only as long as both are there, one will end, so what will I do? I will put such a loop, now I don't. Do you know whether I is over or J is over? Okay, so I will put a loop of both. Look, I don't know whether I is over or J is over. The loop above Let Us is over because I was over. If this loop was finished then this loop will not work. If they come out of this loop, then I have written the loops of both below. If the upper loop is finished due to aa, then the loop above aa will not go down. If there is still left, the one below will work, if the one will not work, then there is nothing to be done in it, now there is no question of flag, now we just have to consume without any decision, so we just consumed it from I and inside it Only word two was consumed with the help of J, l was written and returned in the last. If you think about the complexity, then see that the length of the complex one is o n and the length of word two is m, so the total time complexity is n + m n + m. If complexity is n + m n + m. If complexity is n + m n + m. If you think of the crosses of all three weil loops, if we think of the crosses of all three weil loops, then this string has also been completed and this string has also been completed, so the weil loops are coming one after the other, so the total which is our two i and j has moved, it has moved across the length of both the strings, time complex T is n + m, time complex T is n + m, time complex T is n + m, if there is any doubt on this then you can ask me live, I think there will be no doubt on this, ok before going I mean I have put two important links in the description. You can use both of them. One link is for you to journal your progress with me. I have put its link and the other one is Sklar School of Technology. If you have any younger brother or sister, then I am using this link. I say that you should enroll yourself in the most cool Time Sna Scale School of Technology. Why is the child so amazing? Look, we are studying in a college. We have to find time for ourselves away from that college. Is it possible for anyone to study computer science in youtube4, now what is there in SST? What is good about SST is that in the curriculum, within the curriculum of your college, there was 50% CS, 50% within the curriculum of your college, there was 50% CS, 50% within the curriculum of your college, there was 50% CS, 50% was non-CS, there is 100% CS in its curriculum, the was non-CS, there is 100% CS in its curriculum, the was non-CS, there is 100% CS in its curriculum, the location is Bangalore, the instructors you had in the college were those PhD people, do you know who are the instructors here No infact the session has just No infact the session has just No infact the session has just started, the first year students went and played in ACM IPC, while the rest were second and third year students from everywhere. When the first year team from SST is going to play regionals, the culture has become a culture of code chef, hacker, rank etc. from day one, it is full of hacker attitude and finally the very amazing thing is that the promoters are there. Friend, they are Sequoia and Tiger Global and Sequoia and Tiger are Global, there are 110 unicorns in the country, out of 110 they have invested money in 60 of them, so when they have founder retreats etc., then all the founders retreats etc., then all the founders retreats etc., then all the founders of the unicorns meet among themselves, even the scalpers. If we meet, she is soaking in all the news till here, so I think that is why this is one of the best places to be. I will put the link in the description. If you have a younger brother or sister, then you can apply through that link. A fact you can also message me if you want to apply you can message me I have a coupon code so the application fee will also be reduced so you let me know all right let's meet in the next video thank you so much Bye
Merge Strings Alternately
design-an-expression-tree-with-evaluate-function
You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string. Return _the merged string._ **Example 1:** **Input:** word1 = "abc ", word2 = "pqr " **Output:** "apbqcr " **Explanation:** The merged string will be merged as so: word1: a b c word2: p q r merged: a p b q c r **Example 2:** **Input:** word1 = "ab ", word2 = "pqrs " **Output:** "apbqrs " **Explanation:** Notice that as word2 is longer, "rs " is appended to the end. word1: a b word2: p q r s merged: a p b q r s **Example 3:** **Input:** word1 = "abcd ", word2 = "pq " **Output:** "apbqcd " **Explanation:** Notice that as word1 is longer, "cd " is appended to the end. word1: a b c d word2: p q merged: a p b q c d **Constraints:** * `1 <= word1.length, word2.length <= 100` * `word1` and `word2` consist of lowercase English letters.
Apply the concept of Polymorphism to get a good design Implement the Node class using NumericNode and OperatorNode classes. NumericNode only maintains the value and evaluate returns this value. OperatorNode Maintains the left and right nodes representing the left and right operands, and the evaluate function applies the operator to them.
Math,Stack,Tree,Design,Binary Tree
Medium
null
907
Hello Aggarwal Welcome, what happened here was that there was a complete area of ​​our own and inside it there were two was a complete area of ​​our own and inside it there were two was a complete area of ​​our own and inside it there were two problems, if you understand it as yours, then one was that you have to make everyone else's, it is okay to make Find it's okay, both of them were our own problems if you consider them as probability, but now it can be a small integer or reduce it by one, leave this entire year, divide it into even more parts, what to do, okay? No, this is all of four sizes, we have converted it into 2 sizes, it is okay, we have converted till now think what can be in the size, give your answer okay, further you and I think, now a common thing will come out here, what if. This element of yours is fine, if it is A in both of these, that if A is present in both of them, then it is always being formed. Now think about it, this is a small element, because of this. Something or the other, the complete game is changing, so now what happened here is that if you clear your mind, first of all, you have to leave in the morning and first of all, take minimum leave from it, look at the specific minimum of your priority and leave only after the minimum. If you try then it will become yours. Okay, okay, those who do not understand the problem, there is no need to take tension. First of all, you are going to understand very easily what is trying to be said by this question, after that we will make an appointment and end. Finally Versus Implementation is ok so look here let's understand well what happened here that there is some error in it, ok there is some competition in that area and the final result is ok now let's see what competition happened in the face. This is also possible, okay, now this three and one cheat foot is also our sabar, similarly, what else can I tell, now tell me, what is the minimum in it, turn on the four bullet card, let's remove all these, okay, and after that too, there is minimum and If you want to go out, you will have to travel in it, otherwise no, now growth is not coming to your mind right away, nothing is coming to your mind right away, DP graph please back tracking, there is nothing, okay said, what question do you have and one more You have to go out, turn it upside down, it is absolutely right, leave it, okay, whatever different logic is trying to come into your mind, you are looking at them as to how they can be yours, okay, tell me one thing, it is best. Have you understood? Han, okay, tell me one thing, from where to here, from here to here, there was nothing in this too, first take a single, after that you will definitely get involved, okay, but when I come from here, what will happen, so what will you make? Ki agar three van tu four hai, it is okay and in this whole thing, if you are considering your van, it is okay, if you are considering your van, then which one will you take as a minimum, only one van will you take, it is okay, this is someone A for If you want to take the body, then what are you thinking of applying something like this on it, you can eat it yourself, right, it is okay, there is such a small presunt of the left hand, it will always be made. It was clear that Yeh Jo Tu Hai will come first on the left side. It is absolutely correct. Well, what is the one on the left? If the one on the left is small, will four come again? Is the matter clear? Do you understand what you did? If it is added to the group, then how many can be made and if the one on the right is added to the group again? If it happens then how much can be added, if the rider is not your own, if you make the light ones, then tell me 4, how many in the rate, if there is not even one in the right of four, then just take this man of yours, only one can make his own group, right. Who you are, okay, can he come in the first group, here in how many groups can he come, then there is no problem in all, but make the minimum element again 312 124, how much will he come, okay, how much will you come in this? How many times is the bullet about you going to come, let's look at the bullet once, it is clear, I have understood it, there is no problem, I have understood it, I just understood this approach immediately came to our mind, see it needs a lot of practice. It is okay there, it will take a lot of practice when you start getting clear on your own, then it is okay in the group, that is, just to the left of it, there is a bigger present than this, there is a smaller present, it is good for you, okay, this is the four. Four is present on its left. If it is smaller than the same, then it is not the same. Similarity is fine. Whatever elements will be done, then it is fine for van. You have to complete the number which is on its left. Look, where does a smaller number than this exist on its left? Han is doing the right thing, your van will come on time and the van will come on time, ok, now what you have to do first is to write to them first, it is ok if you try to code yourself, it is not too difficult, just try once. If you do this then you will forget it, then if there is any problem later, then your own people are going to understand well, so it is okay, now what happened that your own people are the first to come in the size of the error, so again and again Android and Shayari but how small are they. Present means for how long can it come and how long can it come once on the right, okay now what have you done at the time of initialization, you have initialized everything in the left, after that I took it that this All are small on the left and all are big on the right. Normally, what did you do that you gave it a sun base case because it is not possible that it will be a mines van because one of its own will definitely come, now there are many similar questions here. Have you always had sex? Okay, so try to call whatever little knowledge you have. Okay, definite answer. Okay, now it's three. What did you say when you left three? So what have you taken till now? Youngest Sansad again. Which one is smaller than that and the van till now, the latest one is the smallest one, okay, which one is the smallest one till now, the latest one, tell me, what did you do after that, if you calculate it, then you will know that there are four smaller ones in between. How many are existing bigger than, like four, where are our property to showcase, three, that is smaller than this, what did Han say, become, that is smaller than three, okay then it is smaller than 13, so remove the three, okay and also There was no one else and any leader is fine, only this one is existing, so till now what did you understand that if this one exists, then even give him whatever size he is, he will remain the smallest among all, that is correct. Okay, tell me three and what is its index, how much will be the difference, if you don't want this method, then tell me one thing, there is no problem because your answer is in it, you had made a factor named left in the left, similarly, the whole question of yours is on the right. It's gone, you do n't have any problem, there is no problem, my Redmi is looking like multiply and keep adding six to it, no problem, please open and return, okay then your look is gone, I have made the total, okay, what did you do in that, multiply left and right. Got it done, okay, now what is this percentage module? Percentage is the pearl that this answer is, it could have been quite big, so the question of mine, I had said earlier that we have to give it by reminding, with whom are we, with this Modi, is it okay? It is a module, there should not be any problem, after that, you have multiplied it, then what did you say after multiplying, now it has been multiplied, left and right, look here, left is right, with the element, it is done, it is okay. Get the add on done inside it, is the multiply product done, three is ok, then now when it is calculated, will six come, then that six will be equal, no problem, finally got the whole thing returned to the calculator, I hope you understand it well. Still if there is any doubt then submit the comment box, you have seen your run, it was yours, submit is done, ok thank you.
Sum of Subarray Minimums
koko-eating-bananas
Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[3,1,2,4\] **Output:** 17 **Explanation:** Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17. **Example 2:** **Input:** arr = \[11,81,94,43,3\] **Output:** 444 **Constraints:** * `1 <= arr.length <= 3 * 104` * `1 <= arr[i] <= 3 * 104`
null
Array,Binary Search
Medium
788,1335,2188
1,232
Hello everyone welcome to me channel question and it is really easy but generally in phone interview or in online assessment sometimes an easy question is asked then one of them is ok straight line here it has not been asked by amazon and question Let's look at it is very simple, you must have given the coordinates, you must have given us the coordinates, you must have given two things in each, X A coordinate, okay, so you have to tell that these points make a straight line in D X, all the points which Keep giving, are they making a straight line in the If there are two points then find out its slope. What will be its code net? Let's take So far it is clear, a very simple property of mathematics, what will we do with it that when there is any straight line, then pick up any two points in the straight line, pick up any two points, I picked up this, then their Whichever slope will be there, let's take it and pick up another one and then extract it from it. Okay, so what do we do here y2 - y1 / x2 - Let me y2 - y1 / x2 - Let me pick three points, first of all, okay, fix it, what will I do first, mother, take everyone's slope, I will take it from this, okay, everyone's slope will be taken from the first point, that is, the slope of 2 3 to 1 2. We have taken out three comma four, one comma tu's stop, if it is from slope, then it means we will be in a straight line. If everyone is ok, then first let's take out 3 - 2. You see, we are first let's take out 3 - 2. You see, we are first let's take out 3 - 2. You see, we are taking out x2 - x1 from this. Is this? It is equal, it is correct, see, both are equal also 3 - 2 correct, see, both are equal also 3 - 2 correct, see, both are equal also 3 - 2 1 will become 2 - 1 will become Will this one go This one will go 1 will become 2 - 1 will become Will this one go This one will go 1 will become 2 - 1 will become Will this one go This one will go My one This one will go my one Look here 4 - 2 / my one Look here 4 - 2 / my one Look here 4 - 2 / 2 A will go This you will go This one Both the cuts will be 1/1. Both are equal. Okay, 1/1. Both are equal. Okay, 1/1. Both are equal. Okay, now it is clear. Just pay attention to one small thing. We generally tell you to stress on this thing in the interview that you should show yourself how to find the corner. Now think for yourself. Here we take a zero in the denominator, so now your code will get fat, division by zero is okay, for that you can make it simple like this too. What is 3 - 2 * 3 - 1 3 - 2 * 3 - 1 3 - 2 * 3 - 1 cross multiply, take this there, is this equal, so see, what I will do is just simple, first two, I am going by the mother of all, I will come out of this, okay all. So, first of all, let's take out these two. Okay, remember, see what will happen. We will take out x2 - what will happen. We will take out x2 - what will happen. We will take out x2 - Sir, 3 - 2 will become 1. Sir, 3 - 2 will become 1. Sir, 3 - 2 will become 1. What will happen is x2 - What will happen is x2 - Okay, so what is this brother, what is its delta Delta A multiplied by this one, isn't it, you are great, you are equal, Delta It is from this point that the slope that is being created by meeting this point is not equal. Okay, so at this time we will say that brother, by meeting all these points, it is definitely not making a straight line. Okay, it was a very simple question. Let's write the code, it is a very simple way, we are just putting the same thing, first of all, here I have calculated what is its size, let's go with that, okay, our example is fine, so first of all, what have I calculated, brother, this is You comma 3 to 1 2, what will be the A of A, let's write it like this, okay look which are the coordinates brother, the one with index y2 - y1 is okay, what is the A of this brother, this one y2 - y1 is okay, what is the A of this brother, this one y2 - y1 is okay, what is the A of this brother, this one is not three, so here it will be 1, okay and y2 - y1 This is done y2 and its and y2 - y1 This is done y2 and its and y2 - y1 This is done y2 and its first one is clear till now my y2 - y1 what will happen Let's start with and everyone's slope will come out with this zero index. Okay, I's Both of them should be okay, that is, Cross multiply, what will happen [ Cross multiply, what will happen [ Cross multiply, what will happen If this is If this is not done here, then we will start the return in the last, checked by multiplication, OK, so you have to pay attention to these things, you will not know anyone in the interview. There is also doubt please in D common area ultra next video thank you
Check If It Is a Straight Line
sum-of-mutated-array-closest-to-target
You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane. **Example 1:** **Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\] **Output:** true **Example 2:** **Input:** coordinates = \[\[1,1\],\[2,2\],\[3,4\],\[4,5\],\[5,6\],\[7,7\]\] **Output:** false **Constraints:** * `2 <= coordinates.length <= 1000` * `coordinates[i].length == 2` * `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4` * `coordinates` contains no duplicate point.
If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value.
Array,Binary Search,Sorting
Medium
null
729
Ki 510 Welcome To My Channel And They Are Also Living Very Important And Famous Interview Problem MyCalendar Vansh Sidhi Like Share And Subscribe Attempting Interview Tips Interview Sharing This Problem Thursday Till Pen Drive And Subscribe And You Know It Is The CEO Of The Subscribe Free Quit Successfully and Returns Through It's Not Free Dangi Will Return Forms and Want to Know How to Solve This Problem subscribe The Channel and subscribe the Truly Representative Meeting from Shyam Subscribe Button Meeting with Subscribe Shyam Kunwar Life in the First And Meeting Acid Meeting Hai Like Its Vishuddha Meeting Can Also Be Accepted And Evil Returns Through That Is This Is Totally Problem Solved Viruddh Solution Like And Subscribe Will Keep This To-Do List Play List Veer 1000 Start End Time To Be Successful Meeting And Decision from nowhere new method for withdrawing subscribe with the meeting will you spend time in 2G successful walking and great and through effect collida and everyone will return forms its so what are the criteria of worshiping lakshmi subscribe meeting from visiting card definitely subscribe in the previous meeting K festivals start subscribe like this is the chief of staff meeting between 2 student of the year to my channel like this meeting is completely ignored due meeting is completely overlap devices pacific meeting cordiality start again as they can find fault with the stars like this start the Meaning of bje meeting completely overlapping subscribe can live with to one that nda second 151 k sonth raw 1955 will check bhi new start so staff banu meeting which we need to check if it is great then and subscribe meeting which will not listen and ladders in the And After B ed M ed Admission Will You Subscribe This Channel Subscribe Videos Not To Subscribe 9 Arvind Hardly Takes Two Minutes So Like Share Will Take This Point From College Meetings And He Will Release It's First Meeting With You Are Still Not Withdraw All Fears And Who Will Check The First Indian To And Start Is Loot Dash Lene To Subscribe And According To This Video Meeting New Year Ago Quick Start And Has Been Stopped And Have Thursday Subscribe Now What Is The Time Of The Time Increase The Time Total Time Times In Every Life For The Last One Will Come Into Times For This Time Complexity Of And subscribe The Amazing Something Different Types Of The Day Is So What We Can Do You Will Tried To That Sort Of magenta interested data structures so in java with adopted kids will help of which commonly used factory map and in c plus one is the mean that will win this time start time alone with absolute value and time so in this appointed street know how to check The New Interviewer Is The Success Fully Not To Worship In Any Of The Already Obscene Selected Meeting So What Will You Try To Find Out 20 Home Made This Meeting Life So These Three Members Have Very Important To Make The Life And In This Floor Off The Floor Eternal Video Floor Key Number Channel Subscribe And You Will See Ling Returns The Channel Please subscribe and subscirbe 21 Ki Hina Bar Retreat Map Ki No Veer Wedding Minute Par Meeting 1520 500 For Date Of Birth Using Start Will Tree To Find Out Who Had Till the ceiling floor of this is stand and such gender of this channel is unique wishes software predicate ceiling key suite with me to take no need to check the volume to the floor that is grated stop start 1000 and interview with David 210 The sun for 5th floor key will be null wild ceiling key will be time not mean that to apply the same condition show for this is the condition Neetu check is the key and turn of our new meeting is lesson value of this is pain and sorrow this It is better than salinity in ceiling, it is better than salinity, misbehavior, overlap, edifice of buffalo beach, stem and a list of some, already subscribe, meeting calendar and decisions, like overlapping, subscribe our channel, if you have not subscribed, then subscribe this channel by clicking on 1000 K. Our Video Represents Your Data Structure In Record Board Flash Light Will Use A Trap For Treatment Of Enter Key And Attracts Call Map Itself And Share Bellini Slice This Was That No Water Into And Justice Cut This Channel And Difficult To Find Light Interviews Of interior Udayveer and is like sin dot floor ki problem ki office jaana hai ki similari e will guide seal of starts from this vis ki is will be si link ki ceiling ki ya sauce will be ceiling ki ya sauce will be ceiling ki ya sauce will be stopped ceiling office start vvi good will Check also condition of this floor that is not tap that hand som you direct floor is a great dane and equal to start who is this also neatu like talash which is not interested in this will return forms online porn is not final a &amp; b value in end Is lahar da ki a &amp; b value in end Is lahar da ki a &amp; b value in end Is lahar da ki adi and this great dane seal efficacious The case so let's check the year problem or effigy value its do not included to be used in this case and new start this ki included for this and is not Saurabh Yadav this recommendation was written for Software Otherwise Village Map Hotspot Start From And That And He Will Return Proof Vihar Double Duplex Tried To Compile Record Festival Creative Thursday 112 And 50 Minutes Backward Gift Second And Third Sample A Tried To Give Some Id Hua Hai Record Accept What Is The Time Complexity of Dissolution Soul Space Complexities Festival Call Receive Breaking News and Times in the Floor and Take Off the Time Complexity Subscribe 2012 Video Solution Thanks for Watching
My Calendar I
my-calendar-i
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**. A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.). The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`. Implement the `MyCalendar` class: * `MyCalendar()` Initializes the calendar object. * `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar. **Example 1:** **Input** \[ "MyCalendar ", "book ", "book ", "book "\] \[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\] **Output** \[null, true, false, true\] **Explanation** MyCalendar myCalendar = new MyCalendar(); myCalendar.book(10, 20); // return True myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event. myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20. **Constraints:** * `0 <= start < end <= 109` * At most `1000` calls will be made to `book`.
Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added.
Design,Segment Tree,Ordered Set
Medium
731,732
1,774
hi everyone it's albert today let's solve the contest median question closest dessert cost and before we start don't forget to subscribe to my channel i'll be constantly solving good and classic clinical question with clear explanation animation and visualization now let's look at a question in this question we would like to make a dessert and are preparing to buy the ingredients we have n ice cream based flavors and m types of toppings to choose from and we have to follow this rule when making the dessert the first rule is there must be exactly one ice cream base and we can add one or more types of toppings or have no topics at all but there can be at most two of each type of toppings we are given three inputs base cost array is an integer array of then n where each item represents the price of the ice cream base flavor and topping cost array each item represents the price of one of the i topping and target is an integer represents the target price of our dessert and we want to make a dessert with a total cost as close to target as possible so we have to return the closest possible cost of the desert to target and if there are multiple ones we have to return the lower one in example one the base cost array is one seven and topping cost is three four and target is ten so the optimal cost we can get is uh choose base one which will cost seven and then take one of typing zero and it will cost three we won't take top one at all so the total cost will be seven plus three plus zero which is ten which is exactly target any example 2 with a given base cost and topping cost target we can consider the following combination we can choose base 1 which will cause 3 and then take one of typing zero two of topping one and the total optimal cost will be 17 which is the closest cost we can get to target for example three and 4 the optimal total cost we can get is 8 and 10. and the data constraint of this question is actually a big hint that the size of base cost and topping cost won't be bigger than 10. so for such a small dial size we can just use a brute force dfs recursion to solve this question which is the same algorithm that we use in solving last week's problem and the main idea is to try every possible combinations of base and topping and then we will update the total cost closest to target now let's look at the code okay and first we'll create a class variable res and it can be initialized to positive infinity and then for every cost in the base cost array will run a dfs function and a dfs function won't return anything and the phase condition for the dfs function is when the absolute difference between target and the current sum total is more than the difference between rest and target then we will update total to rest and if total is bigger than target we will just return from the recursive function and next is the dfs sub problem we'll go through every cost in the topping cost array and then try every possible combinations of the topping and then return rest at the end now let's see the coding action okay and here we'll be looking at example 2. the base cost array is 2 and 3 and topping cost is 4 5 and 100. so starting from the first cost in the base cost array we can try don't pick topping 0 at all and then a dfs sub problem would be the remaining subarray in topping cost which is subarray 5 and 100 but we also have different options that we can choose one of typing 0. or choose 2. and when trying these different combinations rest will be updated accordingly and next we can try the other base and again try zero one or two of topping zero and then recurse into the dfs sub problem so following this idea this process the optimal solution will be choosing base one and then one of topping zero two of topping one and the optimal cost we can get closest to target 18 is 17 and this will conclude the algorithm finally let's review because of a small data size of the input array of this question we are able to use a brute force dfs to solve it and the main intuition is to try every possible combinations of base and topping cost array and then update the total cost closest to target and the time complexity of this approach is big of m times three to the power of n and three is because we have three options of choosing toppings and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one you
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
1,523
hey everybody this is Larry this is day 13 of the lead code daily challenge hit the like button hit the Subscribe and join me on Discord let me know what you think about today's form uh 15 23 count our numbers in an interval range um yeah let me know what you think I just watched the Super Bowl uh so I don't know let me know which team you were rooting for and whether they won if you watched it if not also like what about that mid uh that halftime show um I actually forgot how many uh hit singles Rihanna has been it's been a long and good career okay so let's take a look at this prom I'd uh I mean this is easy though I should know it faster um I one thing is that obviously uh you should definitely still look at the constraint even though it's easy and given that this is 10 to the nine a four Loop would be a little bit too slow uh in most cases um there are really two ways you can think about it um you can maybe do some maths about you know uh the Delta and then like do some whatever um like uh on the parody and I think that should probably be good too uh the way that I like to think about it is um for these kind of problems maybe not this one is a little bit over complicated but if you're checking this video out uh maybe this will be something that you can learn as well right um which is um this idea of prefix sum maybe uh or I mean it's not quite prefix some because this is way easier than that but basically the idea of um you know counting the odds of between if we want to count the odds between uh low and high that is just the same as counting the number of odds which um between zero and high minus uh it's between zero and uh low minus one right uh low minus one because if low is odd then uh then low would be inside this range so this is where I kind of you know um uh this is where the prefix sum idea comes from or like the analogy you know before exam is definitely a more advanced topic but if you're watching this video hopefully it helps but yeah basically the idea is that okay let's say we have some number line right I'm asking very hard uh let's see about some number line right and then we have let's say lowest here and high is here right the idea is really simple is that we want to get the number of odd numbers in this range um which is just it goes to the number of odd numbers in this range minus the number of odd numbers in this range right exclusive of the lower bound and you can kind of see that if we subtract this from this you get this um so this is a tool that you obviously like I said you don't really need it for this particular problem but it is a problem it is a tool that um it is a technique that does come into play from time to time and if you and you may see it in other problems harder problems and this would be kind of the idea behind it so yeah so that's basically the idea and then okay so then now we can say return F of Pi minus F of low minus one have to be a little bit be careful because uh because low can be zero and then negative one you may do something funky um but yeah and then of course now we Implement F which is uh let's just say x um maybe if x is let's just take care of their Edge case it is a little bit weird but that's fine right um and then now uh this is easier right because basically if x is odd then you could kind of do the cases right if x is odd what does that mean right so for example if it's seven then and this is what I like to do is that I play around with small numbers to kind of make sure that I get the smaller numbers right and then you know because it's easy to get off by one otherwise right so the number seven we want to return four so I'm just guessing that is going to be um you know X plus one over two right and of course it is also the same if you do uh integer division for even number as well so then Auto thingies are kind of so you don't even need this because if this is an even number this would round down anyway so okay so let's give it a run it looks okay maybe you test a little bit more because I worry about this zero in one case maybe so uh zero one uh maybe one and then something like that right uh so it looks good let's give it a submit did I click on submit or did I click on whatever nope let's click on submit sorry what's in there it looks good 10 49 day streak not that I mean it's fast enough it's just fluctuation at this point um yeah and this is obviously just over one right this is of one this is our uh well this is odd one and then we do it twice so yeah uh and you probably don't even you know whatever just to kind of be clear um cool um yeah that's what I have for this one let me know what you think let me know how you did it let me know your really quick and short Solutions um so yeah anyway uh the week is coming up the long week uh I don't know it's just a regular week but uh so yeah so have a great week stay good stay healthy to good mental health I'll see y'all later and take care bye
Count Odd Numbers in an Interval Range
capital-gainloss
Given two non-negative integers `low` and `high`. Return the _count of odd numbers between_ `low` _and_ `high` _(inclusive)_. **Example 1:** **Input:** low = 3, high = 7 **Output:** 3 **Explanation:** The odd numbers between 3 and 7 are \[3,5,7\]. **Example 2:** **Input:** low = 8, high = 10 **Output:** 1 **Explanation:** The odd numbers between 8 and 10 are \[9\]. **Constraints:** * `0 <= low <= high <= 10^9`
null
Database
Medium
null
1,728
hey welcome back and today we're going to continue our journey to minimax and we're going to talk about this super hard problem cat and mouse and we're going to go ahead and read the question a game is played by a cat a mouse named a catamount and the environment is represented by the grid we have the rows and columns and where each element is a wall floor and we have two players catamounts or the food and the players are represented by different characters we have c stands for cat m stands for mouse and we have the dot period stands for the empty spaces we can walk on and we also have the hashtag are the walls that blocking cat and mouse are from moving so we cannot the cat and mouse cannot across the wall and we have the f stands for the food so we have cat and mouse and food and in the grid the empty spaces we can walk on and the hashtag stands for the wall that there are like blockers the mouse and the cat can play accordingly to the following rules so what are the rules we have the mouse can move first and then they take turns to move so mouse goes first and then cat and then mouse and during each turn the cat and mouse can jump into one of the four directions left right up and down they cannot jump over the wall nor the outside of the grid can jump cat jump mouse jump are the maximum length that the cat and mouse can jump at a time respectively and cat and mouse can jump less than the maximum length that we defined within the cat jump mouse jump staying in the same position is allowed so we can jump zero step all the way to cat jump or the mouse jump that we defined in the parameter and mouse can jump over the cat they cannot jump over the walls but the mouse can jump over that the cat for example the cat is right here and the mouse can jump over the cat as long as the maximum jump is allowed how will the game ends so we got four different ways the first way is when the cat occupies the same position as the mouse so cat wins so cat catch the mouse cat wins or the cat can go ahead and directly waiting for the mouse at this spot so that means the cat is smart and cat will directly go into the foot spot and just waiting for them the mouse to come over where the mouse will reach the foot first and then that's when mouse wins or we have the last tricky condition so this is actually a trick so after like a thousand turns if the mouse cannot reach the foot then catch wins but sometimes we have less empty spaces but sometimes that they are running in the loop so that's why we are on account the empty spaces so i'm gonna show you guys within the code so let's go ahead and write the code and we're going to learn this from coding okay so we can go ahead and start doing some coding we're going to define the boundaries m and n so we have the grid was being given so we're gonna go ahead and write rows and columns and we're gonna have a vetted it stands for how many empty spaces we have how many empty spaces we can walk on so we're gonna loop through every single grid to calculate it and we're gonna also find the cat mls and also the food where are they and grid i nj stands for each grid and as long as it's not equal to the hashtag that means we have a valid place to go and then we're gonna loop this four times and we're gonna find our cat and we find a position you know what let's copy this over again perfect so we have our cat so we need to find the males as well mouse will be mouse and the foot will be the food now we have all the parameters are ready so let's go ahead and write our hopper function which is our dfs so the reason we made everything to tuple is because when i cache the value so let's put the cache first bunk tools that are lru cache so you can go ahead and write your manual cache so we have been talked about this for a long time so this is the python trick to catch the values or you can use the hashmap to catch it so we're gonna have the mouse we're gonna have the cat we also have the turn so turn means like which uh which round which animal should go ahead and play the game so the mouse starts first so that's what we give in the game and let's write the terminated terminal condition so when's the base case wins the game will end so we actually given right here let's just copy this over so if the cat occupies the same position as the mouse so if the cat equal to the mouse or if the cat go into the spot where is the foot is then we return false so we are acting as uh the player as mouse so if the cat catches the mouse or if the cat going to the foot spot then the mouse loose and this warmer condition we have to be really careful so turn wheel tracking like how many runs we have been given and if the turn is greater or equal to divided times two the value stands for how many empty spaces we can go so if the turn go over twice as the empty spaces we have that means we are running in the loop then so the question is asking if the cat is running over 1000 so right here if the mouse cannot get the 30 within 1000 turns cats win but 1000 is not the constraint actually it's not a strict stricter constraint the stricter constraint is the valid spaces so if i keep running in the loop then we are eventually going to lose the game as well because we are running in the infinite loop so if the mouse is equal to the foot that means the mouse will win so that's why we're going to return to so first round is going to be the mouse turn mouse goes first so if the turn mod 2 equal to zero that means we are in the even we're in the even number so the mouse turn so for n stanford stands for next so next mouse in the next position we put mouse in we put the turn in so we're going to write a separate function next position to calculate where on the spot where the positions that the mouse can go so based on the turn we can determine if it's cut turn or the mouse turn and based on that we can calculate because we are given the maximum length that the animal can jump and based on that we also given the position so we can calculate what are the next positions we can calculate so we can we're going to write the helper function and same thing so we're going to write the minimax function so then we put next mouse in and put the next cat in and we put turn plus one because each round we uh plus one so if one of the run that the mouse can win we just return true because we are the mouse so we can win so otherwise we just return files so else so this is going to be the cat turn and based on that so we're going to calculate all the positions that our cat can go so we're going to put the next position and we're going to put the cat that we're going to put the term and we're going to calculate all the positions that where the cat can go and we're going to put the dfs as well now we're going to pass in the mouse we're going to have the next cat and turn plus one as well so the up the opponents also play optimally so that's why when we return false from the opponents so we just return false because we are playing optimally and otherwise we just return true perfect so now we are finishing the uh the function so we can go ahead write the helper function next position the next position so we're gonna have the next position and we're gonna put the position in we're gonna have to turn as well okay so given the position so how many jumps we can go so let's define the list and we're gonna return the list as well so the jump will be equal to um so if turn mod 2 equal to 0 that means we have mouse jump mouse goes even else we have the cat jump now we have the jump number and then we can go ahead and looping through all the neighbors right all the four positions so we're gonna have negative one zero one perfect so we're gonna loop through like exploring all the neighbors and then we're gonna find out how many steps we can find oh we can jump so we're gonna so we can stay in the same spot so that's why we're gonna go from zero all the way to jump so we have done plus one because python only allowed uh the exclusive we don't include the last number and then we're gonna calculate the next coordinate so that's gonna be a position zero plus the step times the dx and same thing with the y will be position of one plus the step times d y so we're exploring this so as long as we are within the coordinate then we can go and just one more thing actually it's supposed to be end so as long as we're within the coordinates so we can go ahead and rolling we can start like uh crowding but one more thing we cannot move if it's not empty spaces so we need to check make sure this is not a wall so we cannot across the wall so that's why when as long as it's not a wall so we can move otherwise we break so we're going to continue we'll break why because for example if the cat the mouse can jump like three spot right so for example on the left is a wall so the cat cannot jump over so that's why we're gonna break instead of continue so we're gonna break from this direction while looping through this direction we are checking one step two step three step so as long as we cannot jump that far so we break perfect i think we are finished so let's go ahead and call in the function we put the mouse in and we put cat in which we calculated on the very top and see if that works turn oh i'm actually writing the inner function so i shouldn't need this off we need to do some debug okay minor sorry okay it passed all right so let's do a little bit recap so what we're doing right here is that so we are calculating the valid so how many empty spaces we can walk on and we have the three coordinates we need to cache and we're gonna have oh so we're gonna catch the vet otherwise it's gonna be uh tle and we're gonna have mouse we're gonna have cat and we have the turn so all the conditions we calculated so this is actually given right all the conditions are given except this part so instead of like 1000 we put divided times two that means how many empty spaces we can walk on and as long as we are passing uh all the empty spaces twice that means like we are going over a loop so as long as we are in the loop then we return false that means the cat cannot win because we already go over that we're gonna go into the infinite loop so if the mouse reached the foot and then we are returned to because we the demands already win and the mouse can go and the cat can go each player played will play with optimal solution and we are done so all we does right here is the uh the find the next position so it's more like a bfs standard okay sounds looks great okay i'll see you guys in the next video
Cat and Mouse II
fancy-sequence
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food. * Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse). * Floors are represented by the character `'.'` and can be walked on. * Walls are represented by the character `'#'` and cannot be walked on. * Food is represented by the character `'F'` and can be walked on. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. Mouse and Cat play according to the following rules: * Mouse **moves first**, then they take turns to move. * During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`. * `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. * Staying in the same position is allowed. * Mouse can jump over Cat. The game can end in 4 ways: * If Cat occupies the same position as Mouse, Cat wins. * If Cat reaches the food first, Cat wins. * If Mouse reaches the food first, Mouse wins. * If Mouse cannot get to the food within 1000 turns, Cat wins. Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`. **Example 1:** **Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2 **Output:** true **Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse. **Example 2:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4 **Output:** true **Example 3:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3 **Output:** false **Constraints:** * `rows == grid.length` * `cols = grid[i].length` * `1 <= rows, cols <= 8` * `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. * `1 <= catJump, mouseJump <= 8`
Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value.
Math,Design,Segment Tree
Hard
null
1,705
That Welcome Back Price Today Will Be Seen The Maximum Number of Return Apples Problem This Problem Appeared in the Weekly Contest of List Ko Dr. Ko Cut Song From A Explicit Flex Reader Problem Dare This Special Kind of People Tree Traffic Date for Entries Contra Voucher Deputy Producer Apple Cider Free State Will Support After Their Descendants After 25th July 2014 People Will Feel Choked And They Can't Better Than This Temple Is Not Valid Points And Which It Onto Episode 520 Entries Profile Dhoop See Suicide Into Effect Most One Apple A Day Keeps The Doctor Away E Do Not Want You Can Keep Eating After First And As Given Twenty Years At Temples In The Maximum Number Of Couples' Facility Problems Is The Given Two Couples' Facility Problems Is The Given Two Couples' Facility Problems Is The Given Two Years Apple Cider And Its People Rather Plain By Apple Tree Turn On The Amazing Notes The Best for middle Twitter aspect for witch noose straight yellow pink and basically what we have to do is to remind us that we have to go to office so if we see its example then the example is given like one to three 52 Apple has been released and three to one 4280 Sudhir and condition in spite of that is present as is - closed If - closed If - closed If an apple is produced on Municipal Commissioner's Day then you try plus 1005 - We can fit the apple only till one who kid, plus 1005 - We can fit the apple only till one who kid, plus 1005 - We can fit the apple only till one who kid, after that we cannot produce it. From the validity of that Apple i till after this stage of i - i till after this stage of i - i till after this stage of i - Band only they claim to solve this example so it's right one plus three left side let's not reliable 2012 201 ewant hai tu MP3 theek hai na tu so ji Zero plus minus one on the road So this one on Apple 103 Test Pooja This is the guide 0120 So we can feed it here also You can also bring it here You can also bring it So for now we will press it here Let's do it again and it is affected that two one plus two minus one is easy-to-read two is Punjabi in minus one is easy-to-read two is Punjabi in minus one is easy-to-read two is Punjabi in today's till will be then we * You press it here and how two plus one today's till will be then we * You press it here and how two plus one minus one suited Stuart reason not that gallery Because here this tubeless one - from the middle of 1864 ours tubeless one - from the middle of 1864 ours tubeless one - from the middle of 1864 ours and we have already said that here we cannot use all these apps, we have used all these but we Unable to use, okay, so now we go to the third, a young man phone, third, what to do when three plus form - three plus form - three plus form - one is 60, which on fiber, it will come up to 6 inches, so we change them till six, 1234, so if we infuse, then die. But here bana is left and after this we cannot use par forever. Now four plus two minus one request is 6 - 151. request is 6 - 151. request is 6 - 151. Now we could not do this so basically we discovered all so now we can use all the First you can eat all the dough no problem skin tight with this money 12345 670 Answers for this stop now su look at this problem as an example once we have understood what we have to do then basically now how can we solve this problem So first of all the solution to Jack problem strikes us, he does this one that we both put that and in that we beat the birthday check that at this airport as many as when label and that is our I plus days of I - Bahubali, check the condition, days of I - Bahubali, check the condition, days of I - Bahubali, check the condition, that Dravid is the staple on Saturday, so if we can net, then place him and like this, we will move ahead in this IPL-5 - we will move ahead in this IPL-5 - we will move ahead in this IPL-5 - Mamta has less quantity people but others have approach half, so this How is the color approach, I explain its solution with lucky examples. We need apples that this will be and one is this bird Saudi Arabia, so if we go with this approach, then we will get this 0123 floor and 10060, what will we do or plus and minus. One, we took this dua pulse that we can eat 19th, but we are starting to shoot the starting scene, so here we will do square feet, here we will cut and these two ended with each other, zero's that now here But if our object is Apple, then one plus one - one on this bill that the one plus one - one on this bill that the one plus one - one on this bill that the distributor, so we will fit it here, you and three have made the payment by being curved, now we have this two plus years and what is our day second year two plus Six - If we do T-20 at this time, then we will do one and Six - If we do T-20 at this time, then we will do one and Six - If we do T-20 at this time, then we will do one and two here, we will cut this is also forced, now whoever goes to Apple, this is third day career, this is three plus possible minus one, this umbrella, this is till six later. So and we can only eat one of these so we put it here so this ₹ 1 and zero put it here so this ₹ 1 and zero put it here so this ₹ 1 and zero 1234 so four plus two minus one apps 16 - 152 These apps will not be valid 16 - 152 These apps will not be valid 16 - 152 These apps will not be valid and we cannot use them so we If we organize them, then basically we can use this method to get weapons, but now what is the correct answer to this, how is the camp internship that we have just taken in the fall of 2012, the zero fee typing that we had done in starting it? I remember him lying on the bed, so we can fit him in that school, here I can ask him like this, we are the DJ, he has Apple, he has him, we can break him here, like this we can If we can post them here, then by folding them like this, we can do the entire avery field and according to that, if we want an earthquake, then 30 Chobdar that monkey juice, we have proposed the club solution, the basic question that is coming in our mind is that it is wrong, then we We will have to think of some such fear father-in-law who will think of some such fear father-in-law who will think of some such fear father-in-law who will always give us the blood slide minimum deadline and with the minimum deadline, we can check that if this divider line is valid on this country and how many apples are left corresponding back to this blind, then we The first thing we will use that Apple is that you all have always maintained a deep minimum approach, there is a threat of a deadline, there is a deadline and the number of points is 100, we have to click on the account and the tagline in it is to convert it into minimum approach. Sleep, which kind of flour can add the most, get back, see why we can use it on medium, loot project, so we will use minimum amount of flour in it, that you will use that in it, days, how long that apple is valid, all that We will put this in it, we will take our date, we will do something inside that and how many correspondents of that samples line are back, yes, I have that, we will do something inside that, when we called them flowers, cannons, particular is left, what will we do, we will check brother. Wicket, we took out a tree, people took out a top first, crime vaccine, we will check in it whether we can do this particular apple on this oil and if Amit can do it, then in this experiment we will take out that apple and make it do something again. If we can't use it then it means that it wo n't be able to stop any of the upcoming candidates, so for this reason, we will give this apple a point of 100. It has a basic presentation, so we will see the light turn after seeing its blood. If we have more clear all software then the problem is great school today song and fast Harish cake do main English do something on looteri community store like normal cup applicants will make priority to find that pair that movie is Rawdi hai hua Is that your 100 boat banyan tree broken reception poor point bluetooth now we are from this na second one will boil people will royal look for wealth is letter and priority q size do a suite no words which acts like this is left and right the self why This person who took condition that to specify plus specific - but auspicious vacation equal to plus specific - but auspicious vacation equal to plus specific - but auspicious vacation equal to five states so how notification immediately applicants loot in this regard a glance footage of idols one comedy episode that nobody will do inch 11 applicant's all wicked all equal To say the fifth day of specific it is nothing of but forum politics like this condition will handle 309 topic effigy element in the field of do that wrinkles [ __ ] a by-product top and few days should not do this a by-product top and few days should not do this ajay ko on mp3 dot Is pata hai kul to i hai main itni byachand same condition tip condition that was your bluetooth setting set same condition proposes hair soft hydroxide s minus one critically injured in the condition that particular apple that were mated and not increase the account yasmin quantity art tarf bus Not I Will Again Put Into Practice Is The Full Form Of B A Bhi Aap Swapna Dosh Hai Ka Anubhav Field Mother Cow But Harmonious E Is A Tantra Account Or Immediately Draw You Ajay Ko WhatsApp Facebook Screen Compiler Loot Lo Phone Kahan Hai Main Nidhaal Campaign for Pregnant Ajay Ko Hai Sorry This Number Last 10 Test Radhe Aap Kaun Ho Show More Tomorrow Morning Difficult Time Limits For And Now She Will Win The Hearts Of Milk Plus Ashwini Titu Polls Bank Westpac Gaur Tak Particular Day Free Hi Advance Manner and Soft Cotton Shop Chat Organization That Sweet Has Been Accepted That Guys Like This Video in His Arrest Like Button Share the Video with Your Friends and Subscribe to The Channel Benefit Posting Regular Leader Limit Questions on This Channel Proper Nouns and Suggestions Press the Bell Icon And Subscribe Our Channel Thank You For Watching My Video
Maximum Number of Eaten Apples
count-unhappy-friends
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix “rank” where rank[i][j] holds how highly friend ‘i' views ‘j’. This allows for O(1) comparisons between people
Array,Simulation
Medium
null
367
hello everyone welcome to another one of my lead code videos and this one we'll do lead code 367 valid perfect square so we're basically given a number and we need to determine if it is a perfect square so for example 16 is a perfect square because two integers when you multiply four times four it'll give you 16. note that we're not allowed to use any built-in functions such as square root built-in functions such as square root built-in functions such as square root so what will be our approach for this so the you know the Brute Force approach since we know that it's only two integers that you can multiply we can try every single integer so we can do one times one two times two Etc until we either get to num or if we exceed them we know that okay then this is not a perfect square so for example if in this example num is 14 we'll do three times three we'll see it's nine we'll do four times four we'll see 16. so since 16 is already past num which is 14 we know that this is not a perfect square and if we got to 16 then we would just return true and this is a Brute Force solution so the time complexity will be o n because we'll try every integer from one to the square root of n actually o of the square root of n right because we'll try every integer from 1 up to the square root of n so the question is can we do better if you think about this you know these numbers are progressively increasing so we don't actually have to do it one by one we can actually apply the concept of binary search to find which number it is so in the binary search we usually need a minimum and a maximum so our minimum will be one because one is the smallest number that it can have and since it goes up to 2 to the 31 minus 1 you know our maximum will be square root of 2 to the 31 minus 1 and I computed this using a calculator and found that this is equal to 46340.95 and since we're only interested 46340.95 and since we're only interested 46340.95 and since we're only interested in integers this is just fourth six three forty so we'll basically do a binary search between 1 and 4 6 340 to find which number when multiplied by itself either equals to num or you know we can't find it so the time complexity of this will be o of log 4 6 340 and that's basically better than this because this is O of 4 6 3 4 t right in the worst case and this is log of that so this is much better algorithm so let's go ahead and code our binary search so first we need to Define our minimum and maximum variables as we have laid out below next we'll just do a loop which is standard binary search while Min less than equal to Mac so first we'll compute our mid which will be Min plus Max over 2. and then this bit will be used as the potential square root right so we'll try to see we're using this mid what is the product that we can get so here's our product and then we'll compare this product to num so if this product is equal to num that means we found a perfect square root of this number and so we'll just return true and otherwise now if the product is less than num that means the mid we got is too low and we need a higher mid to get closer to num so what we'll do is increase our Min to Mid plus one so that way we can get a higher mid next time and otherwise if it's not equal and it's not less than that means here product is greater than num so we that means we need a smaller product so what we'll do is Max equals mid minus one so that way we'll be searching from Min to Mid minus 1 for our next round and at the end if we aren't able to find a valid mid what will happen is these Min and Maxes will just go past each other right so if we never hit this case and this Loop terminates that means we haven't found a perfect square root of num and so what we'll do in that case is just return false so let's run that and see how that does accept it let's submit cool 100 runtime thank you so much for watching I'll see you in the next one cheers
Valid Perfect Square
valid-perfect-square
Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_. A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself. You must not use any built-in library function, such as `sqrt`. **Example 1:** **Input:** num = 16 **Output:** true **Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer. **Example 2:** **Input:** num = 14 **Output:** false **Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer. **Constraints:** * `1 <= num <= 231 - 1`
null
Math,Binary Search
Easy
69,633
133
Okay, so this is the clone graph, okay, its code is written and our test case is this tooth 4 is connected, so we have to clone it, okay, so initially what we are doing is we will check that the weather node is null and not. In this case, there is no null, so we will simply move ahead, so what will we do, we will create a node after getting the result, okay look at this, so we are creating this, okay, what is this, our final answer will return the result, this is the final answer, so now we are initially in it. What are we doing? We are storing the head value in it. Okay, you can see this, so we are storing the head value here. Okay, so what will we do now? Here we have created the result and Now our value is one in this, okay this is our result deep copy okay now let's move ahead we are making a weighted array one, we will make a weighted array of size, here in the constraint we gave 100 that the value of nuts can go up to 100 so we If we make a size of 101, then the shaded area will be ours, something like this 0 1 2 3 4 The size of the visitor is fine and seeing it here is not true and false, it is of note type, basically we will store the nut value in Visitec, we will know later. Why basically we are making Visitech of note type so that whenever that node is Visitech and we are cloning it, then in Visitech we put that value, yes, put its deep copy, otherwise we will have to keep a separate map. Yes, we will have to keep a separate map, okay, we have filled the taps in it is not necessary to track it so much, now we start DFS, what are we doing in DFS? A copy has been made of the head and it is passing through the wizard. Okay, its region will also be understood. Now the first node is initially which is noted in the question, meaning that one is yes, so now we have passed the initial one in it and have passed one of the result. And if the visitor is passed then basically what will keep changing in DFS, the value of the node will keep changing and the result will keep getting updated, our result will keep getting built up and the result will keep getting built up and what we will pass in DFS will be known further now. Okay, now look, here we come DFS has started, what will we do now here visitor of this equals to okay visit of result dot value here we can also do note dot value because the value of both will remain the same what is result dot value Our one will be stored here, we need integer value, so the value of one is equal to this result, that is one, so what will come in the value, here now this one will be stored, this one is not a number, it is a node, air node, V. R Storing in DI Yes OK Now let's go ahead with this Now what will we do, we will traverse the neighbors of the node that we have brought, right here, what are the neighbors of the forest, okay, so the first check we will see here is that this He is not already a neighbor. Okay, if not then what will we do again? The same process which we have done here, we have created a new result and stored the values ​​in it, so let a new result and stored the values ​​in it, so let a new result and stored the values ​​in it, so let us understand this here also. Everyone will pay everyone will make a copy, so what did we do here, created a new note, okay, stored the value in the new note, assign it to OK and this is the neighbor of the result, so added neighbors to the new note, so what did we do here, its neighbor I added this OK related name result was just one our result was just one so we added this ok now we will move ahead now what will be the DFS call Next DFS call will be our DFA with a key value two New node to and witted ok now what will happen here witted off say off this to equal tut y will be stored node ok now what will we do we will go so ca n't we store witted here on Why are we storing it instead of? We know that we are making a deep copy of it. Well, we could have stored it in VITE. Yes, we can do it. There is no problem in that. But now think about the initial case that we started from zero. So, when will you get it done for zero, please do it above, okay, you will have to write the code in two places, this is a single line, meaning it is on the string, okay, now it is done, what will we do now, or we have marked it as two. We will go to Neighbors. So, what is Neighbors? What are Neighbors? Okay, now we will go to Neighbors. Look, now we have come to one point. Okay, in this case, we checked if neither is active, then we will add the result in Neighbors. We will do it okay and what is the result here, you have to keep in mind what is the value of the result which is the current note after which this is our result. Now in this case I have understood that yes because as a new note is passed. Neither this is our result nor this, you have passed this atli, so we will add it in its neighbors, basically there it is being added to the list, here we have already made the diagram, this has been added, now this is the case. Now next we will come to three. Okay, now we come to three. Neighbor to th is not marked. Yes okay, so we put three in the new node. Okay, we put th in the new node. Then we will add th to its neighbor. Now the next call will be made to the next neighbor of the invited now. What is the neighbor? Okay, now the same process will happen with the second one. If he is invited then he will be added to the neighbor. After that, four will come for four. We will create a new node because it is not visited, okay and here we will create the first visited three, we have also marked this three as visited, here initially we have come to four, yes, we have come to four, now even four is not visited. If it was four, we will add it to the neighbors, made it a new node of four, added the copy node to the neighbor, added it to the neighbor of three, added it to the neighbor, and then called DD, DFS started, four on four, and added four. Okay, okay then we will come to the neighbors of four, what is the neighbor of four and one? Now look, one is also marked, so four has been added to the neighbor of one and one has been added to the neighbor of four and three. I am already connected, so in this way our clone has been created, so when it returns, the return means finally the process is white type, recording has been slowed down.
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
129
Welcome to my channel again today will discuss some problem to meet code 1298 sum to lip numbers for the problem statement saying from root will have to race to the list node from root dalit note hair 605 lips note means have no children beans left and right to Win All Software Which Can Find Three Lip Notes 675 Soft 262 Ko Din 3962 Cross Frustration Se Number Chord 06 Air Water With Number 394 7 And Exit Is 315 Se Toll Free Number Sadar Swift Editor For The Native Will Be See And 1615 Plus 315 4686 This Is the result you want from this problem now you have cost given one is the number notes in history train which is 120 and what will oo will meet 102 not least they single digit and can form number date of the tree will not exceed 100 three content Hui now this reminder is heard The question is that how I can solve this problem Sirf aloo cat hair the number three 96 Form notification The number it is 3210 Class ninth tenth plus 6 Replies check return 947 The breakdown Dutt * to 0.1 return 947 The breakdown Dutt * to 0.1 return 947 The breakdown Dutt * to 0.1 plus 780 tsp Yeswant That note's share was same tree leaves multiplied from same time to same time cities multiplied by thousand same time with tan white is Bigg Boss to maximum death for this loop notes are changing the billions 30 to level download way multiplying 3100 exit is three layer gold and Silver 3720 Just One Level Downloads Pay 210 SIM For No You Can Take Care No One Will Donate 0 But In This Case Not To Plu 1920 So Ifin Notice Here To Solve This Problem You To Things From Top Unmute To Go To The Button Free Ringtones Passed Buy Multiplying 10th that Sapoch for Hair Oil to Multiplicative 10.29 Absolutely Spent Plus 9 War 30 10.29 Absolutely Spent Plus 9 War 30 10.29 Absolutely Spent Plus 9 War 30 Time Pred World Play List 10 and Sind Side Interview 39392 Benefits Elephant Day This Gurjar Simply 892 This Aspect's 06 2394 10 Round View To Multiply Diesel 2010 Network's 087 2013 Entertain Any Thirty Plus 12331 Promise Solution Will Be From Top To Developer Now Will Go Through How We Will Do the Free Mode Traversal and Solve This Problem Solving This Problem Needs Someone You Will Want to Tell Someone Else Will Give the Sum of History Numbers What Formal Wear Is First Real Dob Total Workers Want to Tell Some Plus Numbers 30 Total Review Messages Variable Total Song Dushman Will Apply For Each Not Every Note Nandish Together Will Apply To Enrich To The Lip Note Sun First And Total 10 Days Indian Old Varna Movie 120000 Classroom Balaghat Is Three Layer Stree Ya Upvas To Both Side Free MP3 Stay in Accept This Name Is In Father Snowden Choli Member Third Quarter Se Input From Next Not For No Fear To Calculate The New Name Day 123 * 10:30 Calculate The New Name Day 123 * 10:30 Calculate The New Name Day 123 * 10:30 Classroom Spent Sexual To Part To Both Sides Of Its Children 100 3902 Pass Decide And Continue to pass this site that now has been quite reversal means left side to leave them to keep from nowhere to go to the left parties 66 vacancy too left and right is channel date means that is a lip note calculation of doom improved time both of this Will be satisfied with the first thing is the name will get 1000 b-39 or thing is the name will get 1000 b-39 or thing is the name will get 1000 b-39 or fruit pahal net is 8396 396 them bread answer total time so total edition answer total time so total edition answer total time so total edition hair soft 96 aaya 2nd year due to that nakul computing and go to right side And Health 28 Oil Facility Name Is Absolutely Near 12392 2398 Lad Follow Notice Forces Posts That And Obviously Right Side Nothing Is Late So Dainik Tourist 72 Laptop Distribution Odd And Exit Poll Apply Both The Islamic Katu Na Mintu Ten Plus Two Wealth Plus Total Semiconductor Mintu Name Swapn Dosh Nau Vid 394 * 10:30 3940 Plus Daru 12394 70 60 394 * 10:30 3940 Plus Daru 12394 70 60 394 * 10:30 3940 Plus Daru 12394 70 60 For Add Vid Total Sum Total Semi-solid 396 For Add Vid Total Sum Total Semi-solid 396 For Add Vid Total Sum Total Semi-solid 396 Shyam To End Dar Free Phone No 84 Ki End 7th 126 Party Find A Control Your Hair And Will Go To The Right Side After Free Service Three Layer Name Person * 10:30 Class Three Layer Name Person * 10:30 Class Three Layer Name Person * 10:30 Class Fruit Will Notice That Does One Is The Lymph Node Time This Bread Or Hotel 100% Whole Raw Node Time This Bread Or Hotel 100% Whole Raw Node Time This Bread Or Hotel 100% Whole Raw Discuss And You Will Be Our Total Saag Pushpi * Return Result Recording And Sample * Return Result Recording And Sample * Return Result Recording And Sample Accurately A Spray Bottle Function Newton Right Words When Will Pass Through Turn The Nam Officer But Think You Can Simply Eternship Route Left and Right Vatan Lal Mirch Speed Jali Apne Day Time Will Calculate Very Updating 19 Na Mintu Ten Plus Two Andher Nagari Total Semik Total Plus Nam It Is Not The Ke On This Day Hui Free Left And Remove Right And This Traversal Show Business Loot Novel Pass Notice Name * Ten Plus To Loot Novel Pass Notice Name * Ten Plus To Loot Novel Pass Notice Name * Ten Plus To Hell And Forward To All U Something Na Mintu 10th Class Room Where And When Will Complete All Records And Troubles Will Get The result century total Saumya can define outside a global variable and you can keep updating find time complexity they need to swim wear visiting below green node just once a come new-year coating brother milk according new-year coating brother milk according new-year coating brother milk according parts and total time now difference global variable outside pimple In third time calling is pre-order real family and calling is pre-order real family and calling is pre-order real family and friends and abiding total time third program which aims to submit a
Sum Root to Leaf Numbers
sum-root-to-leaf-numbers
You are given the `root` of a binary tree containing digits from `0` to `9` only. Each root-to-leaf path in the tree represents a number. * For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`. Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer. A **leaf** node is a node with no children. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 25 **Explanation:** The root-to-leaf path `1->2` represents the number `12`. The root-to-leaf path `1->3` represents the number `13`. Therefore, sum = 12 + 13 = `25`. **Example 2:** **Input:** root = \[4,9,0,5,1\] **Output:** 1026 **Explanation:** The root-to-leaf path `4->9->5` represents the number 495. The root-to-leaf path `4->9->1` represents the number 491. The root-to-leaf path `4->0` represents the number 40. Therefore, sum = 495 + 491 + 40 = `1026`. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 9` * The depth of the tree will not exceed `10`.
null
Tree,Depth-First Search,Binary Tree
Medium
112,124,1030
7
hey guys hope you are doing fine welcome back to another video in this video we will be looking at solution ah another lead coat problem which is reversed integer the problem definition is given a 32-bit signed definition is given a 32-bit signed definition is given a 32-bit signed integer reverse digits of an integer and few examples are given such that the reverse of 123 is 321 River so minus 123 is minus 321 whereas if the number is such that it contains preceding zeros like 120 then the reverse is only 21 before starting with the solution we must be familiar with two important operators namely division and modulus when we applied the division operator between two numbers a and B we get questioned whereas when we apply modulus operator between two numbers a and B we get the remainder for example when 10 is divided by 3 we get 3 as the question whereas when 10 is modular divided by 3 we get 1 as a remainder now we can start with the solution consider the input X is 17 29 and output la is 0 the output is initially initialized to 0 so the algorithm is as follows well X is greater than 0 multiplying them with 10 then add X mod 10 to num and finally divide X by 10 so this cycles goes on while X is greater than 0 initially value of x is 17 29 since X is greater than 0 multiply number with ten then add X mod 10 to num which gives 9 and finally divide X by 10 which gives once 172 so the new values of num is 10 and the new value of x is 172 so now X is 172 and num is 9 since X is still greater than 0 we can perform the similar operations which in the last iteration that is multiplying them by 10 add X mod 10 to num which gives 92 and finally divide X by 10 so a new values of num and X are 92 and 17 since X is still greater than zero we can move further and perform the similar operations by which we get new values of num as 927 and value of x is 1 so 1 is still greater than 0 therefore we can perform similar operations which gives final values of num as 9 2 7 1 and the value of x is 0 so here we can see that 9 to 7 1 is a reverse of 1 7 to 9 which was the original value of x so now let's begin with the code initially we need to initialize the output num to 0 and the next thing which we need to consider is whether the value of x is positive or negative if the value of x is positive then mean then we need to perform our algorithm which I mentioned earlier that is while X is greater than 0 multiplied num with 10 then add X mod 10 to num and finally divide X by 10 that's it we need to perform the similar operations if the value is negative but with a slight change that is before performing the algorithm we need to multiply X with minus 1 so that the negative value converts positive and finally we need to convert the positive value to negative so here we converted the negative x value to positive by multiplying it with minus 1 and again we made a positive number you too negative that's it now we can return num since the return value is int and enum is long and we can cast num to end so a code is not at finished we need to consider the node given in the question which states that integers must lie within the 32-bit signed integer range within the 32-bit signed integer range within the 32-bit signed integer range that is it must lie within -2 power 31 2 that is it must lie within -2 power 31 2 that is it must lie within -2 power 31 2 plus 2 power 31 minus 1 so we can check this case by adding a simple if condition at the beginning of the code as follows so this condition checks that a number is within the range of 32-bit signed is within the range of 32-bit signed is within the range of 32-bit signed integer we need to also contain check this condition for num that is we can add the same piece of code after we multiplied number ten so that's it a cold is over and we can check it by running yeah it's run successfully so we can submit it is submitted successfully so if you like the video do hit the like button and subscribe to my YouTube channel for more such upcoming videos thank you
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,669
A a beauty mausam jo washing machine thoda this question of list ko 12345 to jo question hai uske andar ko 2 released hum ko and one english march inside the other english, there has been a little light this question and there is no ko cheer I have tied you to this, so here in the case, the list on which was initially something like this 0 AFun 123 The Four Five and the playlist given to was sex like this 17th Height Now what do we have to do I have given you two injections, one copy, I assume the cost and also call to for, so inside this we have to delete the English in it from the flames to the court, then if we add English and this So I should write something like this in English and the one who is in the list two should be appointed to the one who is related to it, let's do it tomorrow in the middle, meaning now the one who is one will be appointed to 24 and the one who is one will be appointed to the Alumnus Peeth, so now who is my final, some of these It looks like this 0684 520 two three four courses were deleted and in their place the sacred lingus curved octroi. If we see how the people do this then it is very simple for us or not, this minus one of mine was bigger in the next one too but Aamir doesn't have just one need, so who will be whitelisted in his next list, and in the same way, whatever is the trail of the list, you will start joining it, B plus one rate, that too plus one will get points, so initially if you see. So this one, which is this area, its link has been broken, now my last one, it is something like this, then this - 110 whatever like this, then this - 110 whatever like this, then this - 110 whatever is the note, the world list tree, then 123 is on the astrology center, MS Word Artist. Death of and after that the list becomes mental and from where to where, I did not get to travel in the list, even from that point onwards, those who do the same work will see every vote, how will I find 219 first, the time which is I will help in tracing the initial whose list is absolutely there, I have knowledge about it, this note which is on the initial, I will not give the snake note which is national E B twisted notes which is on the tree real tap, I make its main lead one Which will help me in indexing travels and its default value is zero from Saturday. Okay, let's do this by going back to time is not equal to how many languages ​​​​do not come empty. Which one is the one in the list, languages ​​​​do not come empty. Which one is the one in the list, languages ​​​​do not come empty. Which one is the one in the list, then do not do the entire travels. Till then we will work, till then there will be no organic need. Now let's see why. If my ID app has ever become equal to 1 - one, that means I will get this note, if I 1 - one, that means I will get this note, if I 1 - one, that means I will get this note, if I get this 10 minutes then what will I do? I will say that the note request to take is a simple one that if ever there is a technical problem with my ID, then what is it that Vinod's sequence is 210 tight. Well, if none of these are there then what will I do, that is, I will spend time in the state. Sequence to daughters and side effects plus two Okay, now let's see if it is out of the missiles, that is, my hair oil is connected to Vinod Raina at the right place, so what should I put in the anode next. The one in next which is relax to is ducked meaning question list I should dance to see which is this - I should dance to see which is this - I should dance to see which is this - who should come next in this, the distic head is fine and the oil of Jurist is Manyata Marg, if your function was get a name then the oil of the list is It is playlist to retail in the list ok takey next means - list ok takey next means - list ok takey next means - in Vansh I will join it which is mine as well as requested things and as if I have done so much work then in that day if I return to the states of my list one then My work will be done, just in this corner there is a small function hall in a great deal named inside which we are in public list mode on an important valley and we pass a national whose name is note offering okay mobile no doubt next is not a There is a question of A, then what will we do? Nod request Oo know what next Hands free Arjun Notification is done He said in the morning that we are standing on oil, that day we will return Torch light and vitamin's spelling of course That planted for the zoo If there is then extracted answer and from our new people Mian and submit a tier 2 is accepted I think question will share and this love you finally subscribe The Channel and please like button too much
Merge In Between Linked Lists
minimum-cost-to-cut-a-stick
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Array,Dynamic Programming
Hard
2251
922
hello everyone welcome to day twenty eighth of stem bitcoin challenge and today's question is sort array by parity two in this question we are given an array of integers and we need to sort this array such that at every odd index we have an odd integer at every even index we have an even integer the result can be any such possible array and we need to write down that for example here the input r is given to us as four two five seven four is an even number at the even index zero so we are good second is an even number at an odd index we have to swap this 5 is an odd number at an even index we need to update this again so what we are going to do we will swap 2 with 5 so one possibility of our answer would be 4 5 2 7 how is it satisfying the condition this is a zeroth index this is an even number this is the second index this is an even number this is the at the first index this is an odd number this is at the third index this is an odd number so the condition is satisfied and we are good to return this array there are other possibilities that do exist these are also acceptable without much to do let's look at the presentation and there i'll be solving this by two approaches one using an extra space and one that is in place array by parity to lead code922 and let's reiterate the question here i have taken a slightly different example to what was specified in the question the input r is something like this 1 3 4 6 5 7 8 10 and what would be one of the possible result we should have an even number here so let's replace 4 here and we have 4 here now and this gets updated to 1 and then we have 3 is at odd index so we are good here let's forget this next we have is 1 at this particular index so we ideally should have an even number so let's swap this 2 so we get six comma one and the first four elements are sorted uh we have six at the second index one at the third index next we have is five so five happens to be at the fourth index uh we need to do something we need to swap this number and with what value will swap let's we'll see it later on next we have is seven is at appropriate place so let me just write 7 here and 8 is also added appropriate place which is an even index so let's skip this as well next we have 10 adds an odd index we need to perform the swap operation between these two so one possibility of answer would be we swap these up and the output arrays five four three six one ten seven eight five there can be many other possibilities as well uh but this is one of the possible answer now comes the question how are you gonna solve this question uh let me just uh take a different color pen and on the very first and the knife approach that comes to everybody's mind is to keep track of even elements in the array also simultaneously let's keep a track of all elements in the array so one happens to be an odd element so we'll add odd here 3 happens to be an odd element we'll add 3 here 4 happens to be an even element we add 4 here 6 here 5 here 7 here 8 and 10 here we have segregated even elements so these are even and these are odd now how do we build the answer we will take two pointers one here and one points to the first element of the odd data set and we will alternately place first even then odd so four gets placed here then we have one gets updated then this has already been placed next we have six so six get gets placed there next we have three gets placed here next we have eight gets placed here next we have 5 gets placed here next we have 10 gets placed here next we have 7 so the other possibility of answer is something like this 4 1 6 3 8 5 10 7. and this is another acceptable answer the time complexity of this approach is order of n while the space complexity is again order of n because you are bucketizing all the elements into even numbers versus odd numbers can we improvise on this the answer is yes let's try and look that approach the question itself gives a hint that we need to identify two elements if there is a number even number that exist an odd index we need to swap it with any other odd number at an even index and this is what we'll exactly follow so let's take two pointers the first one that we'll search for is an even number at an odd index and the second one that you'll search for is an odd number at an even index so the initialization of these two variables would be uh 0 this one would be would point to 0 and this one would point to 1 because we'll start the first odd index is one the first even index is zero so let's just point this up so we are searching for odd number at even index we find found out an odd number at even index so we'll stop the next one is even number at an odd index this is odd so this is not good what we're gonna do we'll move this pointer by two places so this points to three now what do we see a 6 that means it's a misfit since it's a misfit we are going to perform the swap operation between 1 and 6. so we'll replace this by 6 and we'll update this by one let's continue the process for the next iteration once we have updated uh this index will increment it by two for searching the next even index will point to here now 2 this is already an even number so we are good we are done with this let's move ahead next we have is five at four which is again a misfit so let me just change the color of pen this is another misfit in order to find the other number to be swat we look out for an even number at an odd index so where is that pointer pointing to right now this pointer points to three from the previous iteration of the for the odd indexes will this is an odd number one is an odd number so we are good we'll increment this by two again we witness seven which is an odd number what we should do we should increment it by two we witness them so we found out another misfit which is 7 at index 7 we have 10 and at index 4 we have 5 these 2 needs to be swapped so we'll perform the swap operation so this gets updated by 10 this gets updated by five and let's continue the process we were at for the fourth index for this particular pointer for the even index pointer so we'll increment it by 2 we get an 8 and at 6 we have 8 we are good so this is not a misfit we'll continue and this exceeds the length of the input array and we are done in single iteration in place we were able to update the complete array we are looking for the indexes that are misfit for even numbers and for odd numbers as per this logic i'll exactly do the same thing which i have just told and let's move on to the coding part here i have defined two variables odd number at even index and even number at odd index and i have taken another variable n for the length of the input array till the time both of them are within the limits of n i go and check recursively every time i'm incrementing by 2 till the time i don't i find an odd number at an even index if that is the case i uh continue this loop however this loop will break as soon as there is a different case there is an e odd number at an even index then this condition will not be true and this while loop will break so once we are out of the loop we are pretty sure that the index value that will be held here will have an odd number at an even index similarly this is again a recursive loop we will keep on incrementing the pointer even number at odd index till the time we have an odd number at odd index so once we are out of the loop we are pretty sure it will hold an even number at an odd index by virtue of this condition once we know both these indexes we will simply swap those up and this is a simple check for us to avoid unnecessary overflow conditions once i'm done with this loop i'll simply return the updated nums array and let's try this up accept it the time complexity of this approach is order of n and the space complexity is constant space 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
Sort Array By Parity II
possible-bipartition
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answer array that satisfies this condition_. **Example 1:** **Input:** nums = \[4,2,5,7\] **Output:** \[4,5,2,7\] **Explanation:** \[4,7,2,5\], \[2,5,4,7\], \[2,7,4,5\] would also have been accepted. **Example 2:** **Input:** nums = \[2,3\] **Output:** \[2,3\] **Constraints:** * `2 <= nums.length <= 2 * 104` * `nums.length` is even. * Half of the integers in `nums` are even. * `0 <= nums[i] <= 1000` **Follow Up:** Could you solve it in-place?
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
null
1,707
hey what's up guys this is chong so let's take a look at uh 1707 maximum xor with an element from array so you're given like an array nums consisting of none negative integers right and then and you are also given like a queries a list of queries which has like uh who has like two elements the first one is x the second one is the amp and the answer is it's the like the size of this queries each answer is the maximum bitwise actual value between the x and any elements of the nums that does not exceed mi so in other words right so you can basically you can do any of the xor you can use any numbers who is smaller not greater than mi and do x or with the current x i here and then you get you need to get the maximum of that and if there's no such number exist then just simply put -1 in that then just simply put -1 in that then just simply put -1 in that slot so some so here's the example right so for example we have no example one here and we have a lid that's the list of numbers and this we have five numbers and then we have three uh queries so the answer will be a three integers and so for the first one right so since the uh 0 and 1 are only two integers not greater than one right and then that's why no we just pick the uh the biggest one between the x or three uh zero x or three and one x or three that's why we have two that's why we have three so same thing for the uh for second query and the third query and here's an example so for example this one here since there's no numbers which is smaller than one right that's why we have minus one here and here's the constraints right so the length for the nums and the queries they're all 10 to the power of 5. and the numbers of x i and m i they are visiting like the integer right 10 to the power of 9. so that's that right i mean the uh obviously the brutal force way will be what so we just for each of the queries right we loop through all the numbers and for each of the numbers we do uh we do x or right for any each of the number who is not greater than the current than this of the m here we do xor with three and then we just get the maximum of that right i mean obviously that's going to be a of n square solutions right then with this constraints that will tle that's what and so which means we have we need to find a better way that's and that's what makes this problem a hard problem so for this kind of maximum beat wise a bit wise or right within a bunch of numbers so a common trick to reduce the time complexity is to use like a beat try basically we use a try you know we will build a prefix try here sorry a prefix tree yeah so the prefix 3 car also called a try so the pronunciation is a little bit weird so probably i'll just call it a prefix tree so because that's more uh it's more common so this prefix tree has like only has one node will only has up to two child nodes either we have zero or we have one and we just built uh this prefix tree with the numbers here so that in every time when we have like this numbers we will basically try to get the beat values from the highest uh from the highest position right from the left most uh locations and then we build it from left to right so and why this prefix tree can help us uh solve this problem right so the reason being is that you know the uh since the numbers right since the numbers are within the beat uh 10 to the power of 5 so which means that you know at most each number can have like up to 36 bits okay and since we have we only have 32 bits and commonly you know whenever we want to calculate the bitwise or we always consider the values bit by bit so let's say for example i have i'll give you a very simple example here let's say we have like one zero uh one right so let's see we have this number here let's see this is the x yeah let's see this is the x so what's this number that's the uh 8 plus 3 that's 11 right so to be able to get the maximum uh the maximum number uh is we do a xor right we do actually with some numbers here so in order to get the back the max values so what's going to be the uh the biggest value we can get we can ever get for this one so ideally what we can get is what is 1 right so to be able to get us this 1 so what's going to be the ideal candidates for this one so we're hoping this there's a number that have a bit value like 0 one zero all right so if we have a such numbers with this bit values then if we do a bit wise with the current x here we can get one which is our ideal answer okay and how can we find how can we know if there's a number that has this zero one zero that's one that's uh that's when we need to use this prefix tree with like this zero or one as a child node so here how here's how this prefix tree works let's say we have uh four numbers let's say we have a one zero one we have and then we have uh one zero one and maybe uh i don't know maybe zero one so let's say we have these four numbers and our x is what x is let's say uh we need x is zero one how about this one yeah i'm just giving like a random example here so let's say we have a zero one and that's the four numbers we have uh as a candidate and how can we use this uh tree to find our final answer so the way we're doing is we're basically we're trying to match the uh the bit greedily from the highest position which is the leftmost location so the reason we can do this we can do it in this way is because you know as long as we have like a bit we have a target we have a value on the left most position that's where we're gonna set the market as one because the earlier we can mark the higher bit load position as one the max the bigger value we can get so that's why we check the left most beat position we see if we can have like a number that can satisfy this bit value to be one after doing the bitwise or so we have zero here so what numbers we're looking for one right so for this one the tar the target basically the target uh bit will be the value will be one and then we'll see okay do we have a do we have numbers that has a starting uh has a one value at the current bit position yes we have two okay so we will have this two here that's why we have this bit value here right so we basically we have one and then here we have a one zero and one right and then from zero we have a one right and then from one we have a we have one so from here we have one and then we have zero and then we also have a zero so here's one right so that's why uh the way we're do using this prefix tree is that we start from the root node and then we see okay if the current one has like a child has a as a one value as one then okay we find one because one there's a child here and then we move to the second bit value here so now what do we have we're looking for zero right zero bit y x or 1 will become 1. do we have a 1 here because remember we're at this note here and then we're checking do we have like a 0 yes we have zero that's why we'll go here we'll go to this round right basically we're going this way right and then the next one we're looking for one right so do we have one of course yes we have one because the next one is one but for the last one we're looking for zero do we have a zero no we don't have a zero because the all we have is one so that's why you know the best number we can find is it's going to be a one zero uh one that's going to be our best answer and how about what's going to be the answer you know basically every time when we find a match with the target bit values we can accumulate basically we can add the answer because here we find like the match which means that you know we have at least we have 10 2 to the power of 3 okay and then for the second one we also find the match which means that we can add another 2 to the power of 2. right and then here we also find one right so and then we have a two to the power of one but in the end here we didn't find the match that's why we don't have anything to add here so in total the best answer we can get is like this eight plus 4 plus 2 which is uh 14 in this case because in the end what we can have is a 1 one and zero and this is 14. so and as you guys can see here with this prefix tree here you know as long as we can follow a path right greedily right by uh looking for the a match with the highest beat look positions we can just traverse down this prefix tree and then we can just use the current path to see if we can find the match for the net for the next bit value if we can and then we just accumulate the answers with the current beat position otherwise with skipped yeah so basically that's how we're going to use this beat this prefix tree to help us quickly calculate the uh a match uh between all the available numbers okay and then the last thing is that since we also have like these constraints with m right which means that we only we're only considering the numbers that's uh that's not greater than m so which means that we cannot just build the prefix tree with all the numbers we have to follow some sequence and then what's going to be the sequence where we're following here we can you know what we can do is we can sort these numbers from the smallest to the biggest okay and then we also sort this queries by the by m from also from the smallest m to the biggest m so after doing that you know we can just every time when we have like a queries here we can just uh we can just grab all the numbers who is smaller than the current am right and then we can just build the prefix three on top of that because next time we have like a another amp here which is greater than the current which is greater than the previous amp here all we need to do is just that we can just grab the a few numbers right after the uh after the last position so that we oh we can we um we can only uh add these numbers in the prefix tree once by following this sequence here right so otherwise you know otherwise if we don't sort this one so for each of this for each of the queries here we have to loop through all the numbers right we have to find all the numbers that's smaller than the current am and then we build the prefix tree that's going to be too slow so that's why we need to sort okay so enough talking let's start coding here and so first thing first right let me create a note for my uh pre for my prefix tree right so i'm going to have a node here and so init dots and then self and then here all i need is just a children here right so children is like the another dictionary right and here we at most will have two child two children but i'm still using like dictionary here and we have a root because the node right and then to build the uh the prefix tree we have we need an insert right and then we have uh we have a query right so we have a two cr and here i'm creating all the uh the signature of the methods first and then we can uh implement those two methods later and then here assuming we have those kind of in certain queries and then all we have is the length of nums right we have this n here and then like i said i sort the numbers right from smallest to the biggest and then i also need to store the queries but after sorting that we will lose the uh the original uh other but we also but which we still need to do to output right to do the output that's why i'm going to create a new course object right a list with the original index and the x m for i dot xm in enumerate chris okay and then i can sort key gonna be the lambda of the uh x two right so this one the m we're sorting on top by that and then uh i need the uh the answer right so the answer is minus one at the beginning i'm giving it all minus one so length of q and then for i x i'm in this sorted queries i also need a j right so to tell us what was the last position well we added we have added the numbers to the prefix tree right so while j is smaller than n and nums j is it's not greater than m then we just do an insert we insert this one into the prefix tree and the right we do this and then here we just do a nums uh populate answers i with the query of x yeah actually we so about the minus one case right so how about minus one and we only do this when the uh if the j is greater than zero so here it means that you know if j is one i'm sorry if j is zero it means that there's no numbers that's uh that's gonna be smaller than the m that's why then we can simply just uh leave this minus one and we only do the xor when there's something right there when there is any something that's that is smaller than m and in the end i just return the answer so that's the main structure of this problem and now let's try to implement this insert and the query so for current so to insert is like similar like the uh there are juno like prefix three implementations so the only difference is that you know for each of numbers we're going to loop through from the highest bit to the lowest which is the starting from 31 to zero okay and so we have a bit values so we're going to calculate the bit value of the current one it's going to be the what numbers now we just move shift to the right and then we do our n and one that's how we get the value of the current bit and if the bit not in the current dot children right and then we do a current dot children dot beat because the new note okay and then i just we just move the current node to the knight to the next one okay yeah so which means that you if there's like a multiple like numbers that has the same as the values at the same note we just simply ignore it and we keep moving forward right and for the queries right like i said so we also starting from the root and then at the beginning we have zero equals uh the answer is equal to zero and we also from loop through from the i in range of 31 minus one and minus one so the target right so remember the target i is actually the opposite value of the current bit right because again right we're trying to get the max numbers which means that fret since for x uh bitwise or if the current bit is zero we're looking for one if it's current value is one we're looking for zero that's why the so the current bit value is this one and to be able to get uh an opposite values basically we can just copy this one and then we can do a x or one that's how we get the target so if the target exists right in the current children so it means that okay we've we have a tar we have a match after our tar of our target values that's then we can just accumulate the current answer with the uh with the current beat value right with this one if this current bit is three then it means that uh we can accumulate eight to the answer and then we just move the uh children right we also move the current the node to the next one the target one else so else if there's no match obviously we there's no new uh values to be accumulated and then the next value will be what will be the current equals to the uh it's going to be the actually the original beat right so it's going to be the target we do a another one we basically we flip the b value one more time and then in the end we return the answer yeah so for this part i mean okay so i'll repeat this part one more time so first we're trying we're getting the target right which is the uh the opposite value of the current bit right and if we if there is one then we will go to the uh basically of course we'll go there and then we're accumulating the error the answers if the target is not there if target's not there and it means what so it means that since we're only having two nodes it's either zero and sorry it's if we don't have a zero it means that the child has to be one right because we're having at most two nodes but at least one nodes right so there's no way that you know the current one doesn't have a child because when we build the uh the prefix tree here so you see that we're starting from 31 and we go we build the tree all the way to the zero bit which means that at least a node will have like a node so it if the current one doesn't have the target node then it has to be the opposite value of the node okay that's why you know the if the target is there right and then we of course will go with the target node path if the target is not there we know that so the child has to be the opposite value that's why we can safely go to the other values path cool i think that's it or let me run the code okay accept it okay run yeah so accept it so for the time com time and time complexity right the insert and the queries for the prefix tree you know because things we have at most 30 to 32 operations so we can trade this insert and query to both o1 here and then actually the only thing left is just these two swords here that's gonna be the uh the sortings we have here because the sorting is it's like n log n right here we have also have an unlock n and here it's just an that's why the total time complexity for this one is going to be the n log n yep yeah i think that's it right so for this problem you know it's i think it's one of the things we uh we learned from this problem is that every the so next time when we are trying to get the maximum remember it has to be the maximum bit wise x or values between one number and a group of other numbers and we're trying to find the maximum this prefix tree is a good way to improve our performance since we can since we have given like the x here we know our target right so we just get our target value bit by bit here and then with this target values we'll basically will traverse this prefix tree from top down and then we'll try to find a match we'll find a node with this target value if there if it is then we can accumulate the values from for that bit position and then we'll go with that otherwise we just continue our traversing until we reach the last beat position i think i'll just stop here and thank you so much for watching this video guys stay tuned see you guys soon bye
Maximum XOR With an Element From Array
check-if-string-is-transformable-with-substring-sort-operations
You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`. The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`. Return _an integer array_ `answer` _where_ `answer.length == queries.length` _and_ `answer[i]` _is the answer to the_ `ith` _query._ **Example 1:** **Input:** nums = \[0,1,2,3,4\], queries = \[\[3,1\],\[1,3\],\[5,6\]\] **Output:** \[3,3,7\] **Explanation:** 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. 2) 1 XOR 2 = 3. 3) 5 XOR 2 = 7. **Example 2:** **Input:** nums = \[5,2,4,6,6,3\], queries = \[\[12,4\],\[8,1\],\[6,3\]\] **Output:** \[15,-1,5\] **Constraints:** * `1 <= nums.length, queries.length <= 105` * `queries[i].length == 2` * `0 <= nums[j], xi, mi <= 109`
Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering.
String,Greedy,Sorting
Hard
null
326
hello everyone welcome back here is van damson and today we are diving into a coding challenge that's often asked in interview determining if number is power or free so if you're new here make sure to hit the Subscribe button and ring notification Bell so you never miss on our coding Adventure okay so let's take a look at the problem statement we are given an integer n and the task is to return true if it's a power of 3 otherwise return false so this problem may look simple but there is more add than one a way to solve it so the first method use Loops while the second employs some mathematical in size so we will start with a first one so we have a class solution and method is power of three and the method takes an integer n as argument and yeah so now the first thing to check is whether the given number is less than uh one if it is we can immediately return false a power of 3 has to be a positive number so let's implement it so if n less than one return false and while and model of three zero and divided remainder and return and equal one so let's run it to verify its working so yeah it's working and for n given 27 it's true because 27 is 3 to the power of 3 and as you can see the function immediately return false if it's less than a one and the next step is to divide the number three uh our number by three so and repeatedly until it's no longer divisible by three so we check modulo 3 and also a division without remainder by F3 so and finally we check if we left with one if we are that means N is a power of three so let's submit it for unsynthesis cases so it should work okay so yeah it's working and we beat uh yeah 71 with respect to runtime and also 95 with respect to memory so now let's erase it and we can implement the second mathematical implementation it's really interesting so return n greater than zero and number model of n equal zero so all right let's move on the second method which doesn't use Loops or even recursion so did you know that the largest power of 3 that fits into a 32 a bit integer is a free to the power 19 is one six two six one four six seven so we can use this information to solve the problem in a very efficient way so it's just return n greater than zero and yeah this number model n and voila you can see that this method also worked like a term so let's run it and yeah so it's working for our test case and let's see if it's working for unsinterest cases as well so yes it's working and we beat 99 with respect to memory and yeah it's took 94 milliseconds so uh quite good and so there you have it two methods to solve the esport of free problem so I hope you found this information uh fun and for those interested in other programming languages I will include the link in the description below for implementation in C plus go Russ and much more and if you enjoyed this video make sure to hit the like button and if you have any question or suggestion for the future video leave the comment below and until next time keep practicing happy coding
Power of Three
power-of-three
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`. **Example 1:** **Input:** n = 27 **Output:** true **Explanation:** 27 = 33 **Example 2:** **Input:** n = 0 **Output:** false **Explanation:** There is no x where 3x = 0. **Example 3:** **Input:** n = -1 **Output:** false **Explanation:** There is no x where 3x = (-1). **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Recursion
Easy
231,342,1889
97
114 WhatsApp Guys Welcome to my channel, so today we will solve one of the least important heart problems, interweaving of strings, so first of all we will discuss the approach in the problem, withdrawal logic canteen. All right, so as I always say, the most important thing in dynamic programming is our approach. It happens then if the approach and bill is now logical field then it does not take much time to do the court. Ok then the problem is that it is saying that keep us from 30, Aishwarya students are three, so I have asked that I can become ST by using Ishwar S2. Can I do it, do I have to use it for the whole semester? Okay, so how is the problem of chromium falling down? Let's discuss it. Okay, so this is the example. Okay, so see, if I have to do something strange like this, then I have my wife right now. I have only one requirement, which of my Ashraf-ul-Haq is doing this, F1 is doing this, it is Ashraf-ul-Haq is doing this, F1 is doing this, it is Ashraf-ul-Haq is doing this, F1 is doing this, it is storing and analyzing, so I have taken the area from S1, this point is fine, now I come here. Went back then I have a requirement then do S2 If you have a pointer then coaxing is not possible then back I used school only Now I came here Edward Carpenter came here and I have a requirement Okay so team my S2 then where is it Okay, so I gave it to him, I took it, that is, I took his S2 Siskaari, now see what else is there that I can take it from being a requirement and also from MS Word and not from S2, okay, so here I have The choice is that I am in this dynasty or S2 treatment is okay so if you see here the choice is coming to you then you understand Chowk this is telling me problem to think extremely Gemini regular I am okay 24 This is done and constraints Yoga is that I have to do work full stringer chat using all the letters ok so I don't think it takes much effort for me to understand online top comments Shravan means Tribhag felt then she came back to Bigg Boss, neither will you take your choice and this If you clean it, then let's solve it, so soon after all what is doing this, if possible, first of all I will put on the rest, I am Rinku, I am Mohit, I am fine with the first record, then after that I will talk, okay, let's solve all that pilot. Lungi Springs A B &amp; C that pilot. Lungi Springs A B &amp; C that pilot. Lungi Springs A B &amp; C worry ok string to solve one will go mine will also go C ok zero will go 000 ok all these are their starting point also A N is ok from the alphabet that I have to return Babool return drink p bhool salt strengh This trick is also this trick C and what's in Tylent J&amp;K Okay see trick C and what's in Tylent J&amp;K Okay see trick C and what's in Tylent J&amp;K Okay see now look let's come to the choice First of all it's very easy to think crow also okay so 34 what is it I have that 24 that stroke okay all make a merit So the result is shrink to pause, forget the result is full pimple to pause, I will tell who made it, okay, if it comes to this, it is okay, that's why I will take this training, to remind me speed is dependent on science in tab is equal to dot size intense. Penance is equal to blot size intensify equal to zero size okay this is I took all the strings of okay this is left in the ants and what a guy is equal to this lesson learn personal so what does it mean that I this Priyanka is the character I can use that to make my interleaving lion, okay, so from here also, I will not get any result, record, dress and initial, this is my result for this, okay, so maybe I can call it from the record, please. If my exam comes then my net record will be broken, that's why I am writing like this, okay so Solve K B C D I Plus One because I have used this trick, Gel Reminder and K Plus One, okay so this is it, I have graduated. And Amit, I only vote among myself on the day of jail extent and chief and that DJ is equal to see, this means that I am also getting results from spring, otherwise I could never get angry in this form. It was told in the example, okay, 10th lets, then here also he will race with me and solve one now, machine earning from Avel, 20mg plus one, market plus one, okay, then back here and that is why this case of mine can be solved. My result for appreciation and that this one should be character but my two is coming as seen earlier in this case not that I also got the space okay so let me listen if you source the gift rate then take the dream also. Return to me further, Soul was sleeping ok but from here and to do two was coming so I took another from back ok and in the end what will I return then the race will end ok then if I don't get answer from both the places Meaning, it doesn't even come from this condition. More than this condition, I have kept it close after seeing the electronic test. Okay, so return file. Okay, now let's talk about West Indies. Okay, I know what happened to this condition. This is the condition. It will be quite simple. What did you say that I have to use all the springs, this one also, Singheshwar, I have to use the next one and add it, okay, so if I use all the strips, then this one of the pendant, if you see it, then my dad will be with me. This is that my intake quantum will also come here, the point of S2 will now come here and also the point A of ST, which is the index point, will come here, meaning so that Noida the way are looking so what. Gaya its is equal to ncd and that i request to a bj is equal to in thi than what return true that apps ki ss k ricardo nc ok my ketu has come to the end but yes this is the thread ok so it can be said I want that my key should be added and this support should go wherever it is, that means I can make this Singh strange only by using S2, but ST is not such a case for me, okay, so the sequence for this is E OK son second. Wait its sequence I can return for specific only NC why but meaning that enter has not reached Ujjain ok then that money problem day is quite simple and electronic after doing it you will know how well I have written something in English ok so this is what I have done 10 How to write, all these are going well, is there any difference, okay, so this is my record seat, its power will be expanded, see, I will submit it in the year, which will be done, isn't your upcoming one recorded, isn't it okay? So okay, now I have to memo it to remove it from Delhi, okay, sorry, what should I see, what are my parameters changing, so let's keep it simple, one thing is changing and there is one more thing. No, now you will say, dear baby, there is a change that the plus one class thing did not come and by doing this thing my answer is changing that we are always incrementing to compare, is it okay then Lakshmi did director vector in sorry. Vector vector ki in TDP ok now let's fold BJP bp dot assign a scientific doctor sir expensive what oo come we are fuel plus point I have to return the size initial here also Tulsi control book-1 control book-1 control book-1 ki and plus one work vector In N B plus one - I am okay, so this is my table, one - I am okay, so this is my table, one - I am okay, so this is my table, I have done minus one in this first school, okay and return and I have to toe the answers, okay so come in the DP in the answer, this is equal to dress okay. So this is where I am breaking the results of all my problems and if I see this note related to FD PI, equal to minus one means there is a problem, it has already been solved, so in that case I will return DPI. If dance on a person is a loser, let us sacrifice and discuss running status of matter cold, think 75 percent poster, then Dhan, if your problem is solved, then look, Samra is doing this, what did you do in the problem, first of all I thought. Man going to me the choice is ok what is the problem of my bike depends on then I came to know that it is delaying the index at the point of powder and S2 of one ok van I hate you just right So recall is just code ABC heart is forced hand juice milk and developed thick is my choice I have written here and this table condition is done okay all three of them have to do this blouse all three conch and only Karegi Singh is utilized which means Just give NC very soon, after Aaron Finch, I saw that my answer is correct, then what I did while washing it in Memo Ishqiya, I saw that my two parameters are varying, and from that I did a to-do. I have are varying, and from that I did a to-do. I have are varying, and from that I did a to-do. I have made a list and Shershah has given his results for the problems and I am not worried and if my problem is solved then I am giving the competition again. So, this problem was so simple unlike the birthday one, there was nothing much and I had to leave my mind. If not then you are sorry for this, you can also see its solution here, the memo is also for him and BJP is fine, it means he has a hydrated blackwater mood, he is so difficult to think, it is very easy for toppers to think at the bottom up, so like this. Answer: Do subscribe like this. Answer: Do subscribe like this. Answer: Do subscribe my channel thank you for watching my beloved.
Interleaving String
interleaving-string
Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an **interleaving** of `s1` and `s2`. An **interleaving** of two strings `s` and `t` is a configuration where `s` and `t` are divided into `n` and `m` substrings respectively, such that: * `s = s1 + s2 + ... + sn` * `t = t1 + t2 + ... + tm` * `|n - m| <= 1` * The **interleaving** is `s1 + t1 + s2 + t2 + s3 + t3 + ...` or `t1 + s1 + t2 + s2 + t3 + s3 + ...` **Note:** `a + b` is the concatenation of strings `a` and `b`. **Example 1:** **Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbcbcac " **Output:** true **Explanation:** One way to obtain s3 is: Split s1 into s1 = "aa " + "bc " + "c ", and s2 into s2 = "dbbc " + "a ". Interleaving the two splits, we get "aa " + "dbbc " + "bc " + "a " + "c " = "aadbbcbcac ". Since s3 can be obtained by interleaving s1 and s2, we return true. **Example 2:** **Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbbaccc " **Output:** false **Explanation:** Notice how it is impossible to interleave s2 with any other string to obtain s3. **Example 3:** **Input:** s1 = " ", s2 = " ", s3 = " " **Output:** true **Constraints:** * `0 <= s1.length, s2.length <= 100` * `0 <= s3.length <= 200` * `s1`, `s2`, and `s3` consist of lowercase English letters. **Follow up:** Could you solve it using only `O(s2.length)` additional memory space?
null
String,Dynamic Programming
Medium
null
1,091
hey everyone today we are going to throw the electrical questions shortest path in binary metrics so you are given n by n binary Matrix grid return the length of shortest career path in The Matrix if there is no clear path return -1 a clear there is no clear path return -1 a clear there is no clear path return -1 a clear path near binary Matrix is a pass from the top left cell 0 so here to the bottom right cell and minus 1 and then minus 1 so here so um such that all the visited cells of past are zero and all other adjacent series of paths are eight directionally connected so they are different and they share the edge or corner the length of a clear pass is a number of visited cells of this path so let's see the example so you are given zero one zero and the output is four because uh we can move like a restart from zero and then move right and then next so in this question we can move like a Direction so we move like a bottom right and then we move at the bottom side and then so we passed like a four zero so that's why I have to put these four in this case and uh so example three is a kind of edge case if um zero is one in the case we can't move so in this case output is -1 move so in this case output is -1 move so in this case output is -1 so for the most similar question I solved before so we moved like we can move like a full Direction but I in this question we move um eight Direction so that's the difference yeah so let me explain how to solve this question before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so let me explain with this example so actually I have three things just only three things I have to explain so one thing is that if a starting point is one so in that case we should return minus one so that is the one thing and next so we Traverse this Matrix with a breast first search so we use a q so the data we keep in the queue is at like a row column and the distance so this distance should be a return value so that is a second thing and the third thing is that um so every time we visit a new place so up to date new Place uh with one like this so that prevent us from regularly visiting the same phrase so we can calculate such so this path properly and so that is acting the breast for such but before press for such that means starting point so um once you start um algorithm update starting point with one so only this place is Omega before press or search so that is a different case so after that new place is a updated in the breast for such so I'll show you um how to write a code later yeah so that is a basic idea to solve this question so without being said let's get into the code okay so let's write the code um first of all check if the starting or sorry I forgot to say so ending cell also blocked that means uh one so we can't reach goal definitely right so in the case we should return -1 so if with the case we should return -1 so if with the case we should return -1 so if with zero so that is a starting point equal one or so gold should be minus one and a minus one equal one in the case we should return minus one if not the case so keep length of lead as a n and so we can move eight directions so directions equal so 1 0 and the minus one zero and uh zero one and zero minus one and one minus one and then one minus one yeah like this and then after that so use Q for press for such so Q equal so e is DQ and uh as I explained earlier so the data we keep in Q is like a um row from and the distance is one so yeah I'll say this one and then um after that Mark starting cell as a visited so click zero equal one so that we can uh prevents revisiting and then so now from now on WE implement the breasts as such so while Q so Q has data first of all um take the um lift data from Q so row column and these tons so equal to Q dot up left and uh if law equal n minus 1 and then column equal n minus one so in the case uh we read the uh so ending cell so return distance so reached the ending set if not the case um like I X pro or possible Neighbors so for let's say DX and DUI in directions so let's say new low and the new column equal so current low plus purus DX and the current column plus d y after that um okay so check if the May bar is in the grid and they're not um blocked so if zero greater than or equal new low and uh less than n and zero greater than or equal to new column and less than n and delete new row and the new column equal zero so in the case add a new row new column and a distance plus one to Q so put up end and uh new role and a new column and distance so this is a current length and the next portion should be plus one right so that's why plus one and then don't forget to update currency and not correct a new cell um to a wizard one so that we can prevent dbsd so grid and a new role and a new column equal one so if we reach the like a ending cell uh we can definitely return distance here so if this while loop finish that means we couldn't reach the goal so in this case just return minus one yeah that's it so let me submit it I got the error here so ah so we need a triple here so like this yeah so let me submit it looks good and I believe sent um algorithm so b294 so time complexity of this solution should be o n Square where N is a size of a grid so in the worst case best for such algorithm needs to visit each cell once and since there are any Square cells in the grid so time complexity is a proportional to n Square so space complexity of this code is also one square in the worst case so the main contribute to the space usage is the queue used for resource such traversal so at any point the queue can hold at most n Square elements in the worst case scenario where all cells needs to be visited so that's why space complexity is on Square yeah so that's all I have for you today if you like it please subscribe Channel hit the like button or leave a comment I'll see you in the next question
Shortest Path in Binary Matrix
maximum-average-subtree
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
Tree,Depth-First Search,Binary Tree
Medium
2126
93
all right let's talk about the result ip address so a valid fbi just consists of exactly four integers separated by a single dot so each integer is between 0 and 255 and cannot have leading zero so which means this is not valid and also this is not valid right so you are given the string s containing only digits and return all possible value ip address that can be formed by inserting dot into the s right so this is the given stream so you can possibly return this one or this one right so uh you just have to know the length of the string is actually um it's actually restrict between four and twelve right so you can have either zero point zero right or you can have 255 which is 12 right so you can actually have a base case for this to just making sure the dollar string is about right so it's if that is less than four or as the lens is actually greater than 12 i can actually know this is not a the stream right so i will have a list of string uh become a google variable to store my value at the address so i'm going to release i'm going to return this right over here so uh what i will do is i will actually uh split the string to four segment so for each segment i will just make sure this the number is actually between 0 and 255 if that is good i will move on the next index so at the end i will just making sure my uh four different segments and adding the dots so uh you might understand why i meant but this probably is easy way to okay so i have a inner risk statement right and i will have a helper function and it's going to be popular void and i'm going to pass in the string and passing the index of the string and from passing the segment and also passing the segment index so you would know like which uh which position you are at and i'm going to call this function s so starting from 0 and passing the in array and you also start from zero and at the end you just return this so let's talk about how i need to take care of the base case for this helper function so if i index if the string index is actually equal to s length i probably should know like i have to make sure my sigma index is also equal to 4 right if that is true then i can actually know i can add a string to my list right so and segment index is actually two to four i would just say list new string so i will convert the sigma number in the ring number to the string and add into the list so i'm gonna say segment zero plus dot plus segment one plus dot plus segment two plus dot plus sigma three right and later on you'll just return so this will be the return value if you find the segment is valid right and just want to make sure if there is a problem when the either sigma index is actually equal to four and you didn't finish the traversing the string then you have to return right or you either actually hit the end of the string but the sigma index is not equal to four so which means this is now the value string right so you have the lc else if case right so if index is actually equal to x or all the segment index is actually 24 you also have to return so this will be pretty much the base case so i'm going to traverse so for the length for each integer in the sigma is either between one and three right so this is one right this is three so you have like a one and three possible uh traversal right so length less than equal to three of course and i also want to making sure like my current position for the index in the string for the full string plus the length is actually less than equal to the extra length so i will not get out of bound right so and then plus index is actually let's simply and i'll just keep plus my name so uh in this situation i will actually just uh pause in my string to the integer so i will be able to know and i actually get about this energy or not right so parse in and what i will do is i will have to substring the uh the index with my length right so index so the current position is actually zero right zero plus the length so it could be one so zero one right but you don't actually include the uh the last one so substring is actually exclude the last character right so in this process so just want to make sure you know what is substring method and also if the valid the value if the value is actually what is actually greater than 255 so you don't want it and also uh the leading zero right the leading is the leading zero so if the length is actually greater than one and also the star chart at index so you always have you always use index this is because the first character is it is an index position not index plus then not index plus you know it's not all the situation it's always in this star.chart at index star.chart at index star.chart at index if that is equal to zero the first character then you will have to break out this is not valid okay so just want to make sure this is not valid and it's always happened on the first integer and you always have the integer i mean the index the current index for each segment for sure and if everything is pretty good right then you are just passing the uh the value into your segment and just call your uh just traversing for the rest of the character so i would say have s and the index cross right i'm using the length so just in this plus length and that would be the exact position where you add in the string and also i need to pass a segment and segment with sigma index will plus one no matter what right because i already store this current index already so if you backtrack right you have to restore the segment to negative one so you're actually reusing again and so uh this is actually pretty much the solution so let me just run the code and see what happens i might get some error for sure okay i don't and here we go so for time is base complexity so for every obvious for the uh full time i actually don't know but for the space is actually what uh it's actually the height of the tree so if you actually think about the back tracking this is actually the tree so i would say like all of probably the land of the ass so it's going to be all of logan for sure and for this time i have no idea so if you have any solution please let me know and i will see you next time bye
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 `"192.168@1.1 "` 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
312
okay cool 312 burst balloons givin em balloons indexed from 0 to n minus 1 well that's not a complete sentence that's why I read Tyler will anyway huge balloon is painted with number are they represent by away gnomes you are asked to first order the balloons after you what if I guess what after you burst balloon I if you purse balloon I you will get numb left numb sup left times numb sub I times numbs up right coins here left and white other adjacent in taxi safai after the burst the left and right then becomes a Jason find the maximal number of coins you can collect by bursting the balloons wisely okay and some stuff about boundary conditions and you have pen is you go to 500 okay uh-oh you have pen is you go to 500 okay uh-oh you have pen is you go to 500 okay uh-oh it was kind of fun okay please um no spoilers then but you could watch me struggle but please no spoilers a little bit okay hmm so my first inclination is just try to think is this greedy and usually it's not I mean I explained this a couple of times but I feel like greedy is always like a trap and if that's the case and maybe it's dynamic programming but what is the dynamic mode when we write hmm because this is only adjacent right so it's not like you're not splitting things in half necessarily but and how do you keep track of those things now become adjacent hmm okay I'm still so right now I'm still thinking about data and programming I'm just trying to think if it is dynamic programming how do i you know what is the DP on also please don't give me hints for this one for a little bit I mean one thing that I am a little weak on despite one out of yours I just I am a lubricant anemic programming's so I think I'm cheese No so Valley ignore the comment it's not me try to be mean I'm just trying to be trying to figure out this one a little bit on these things yeah I would say dimensional analysis and it's go to 500 so I could find do stuff that's n square maybe n Square log and if I want to do it that but what does it mean to burst a balloon how can you do so as a DP poem I would think about how to describe let's say I burst one balloon how do I at least I guess n khabees zero so that kind of force swings in the loop a little bit oh yeah how do I describe the subproblems in that case right and if I have n square away how to describe that tiny like how do you solve it right what are the supports well if I burst this if I first have random number in the middle can I solve left and right I don't know it might be that it is greedy to be honest it's just that I'm just trying to think about in the DP way am i talking on and try to not look at the comments or spoilers but actually I mean well that's tough zero right it always makes sense to pop to zero first wait because you get no coin for me but it prevents future maybe it is time thank you yeah then you kind of figure out relaxing it's like a weird and I say relax I meant like graph theory a relaxing like you know it's almost like a weird ice tray type problem maybe where you're like is it clear hmm well because well you definitely wanna get rid of all the zeros so we could that we filled out the zeros because obviously the coins are zero but also so dad like future because you know like given zero and an adjacent number which is any number you want to pop to zero for us so that when you popped a real number later like you know you get coins from it I think that's fair mm-hmm this doesn't look that's fair mm-hmm this doesn't look that's fair mm-hmm this doesn't look like greedy though I feel like this is a big number now that's 15 but this is 40 so that would be more your choice of its greeting mmm-hmm I mean I think there is like a mmm-hmm I mean I think there is like a mmm-hmm I mean I think there is like a weird maybe enter the fourth dynamic or something like that DP but that clearly too slow so I Oh hmm what could I maybe missed is that I mean I looked at their zero point but me but this is a hundred hmm does that mean anything well it means you it's hard you can go over four I guess maybe that means one thing maybe there's also some kind of state that you can keep track oh I think that's like a fun thing where me I mean it may be greedy is the right word wrong word sorry but it's like almost like a comparison I mean like okay first thing one like there's a function that's like second order or something like that like the cost function of the greedy isn't necessary just bursting it but it's like there's some or like some weird function on first thing dis before word cursing the neighbor or something like that and there's some function on that maybe and then once you do that you can do a sort of a greedy maybe let's first think this means you got fifteen but it wasn't means you're five your cost function what does it mean suppose this way first thing the one means you have in the future in somewhere three times five more I do like that's kind of I'm not gonna I like this problem per se but not as an interview probably not but well maybe when I see the solution but uh so I would like to you know smallest means well uh hmm why would you not pop five instead well but like in this case right now pop two three then why how do we choose the five I'm listening we'll try to work out this example just to kind of see if I could work on an intuition nothing like this you know you popped it three you get the team answers well you know that's just a problem what we ate but then you have me down to minus 15 times 8 is 120 and then you can oh you can pop to 8 so you pop the edge you get 40 and you get 305 now why do we make that decision but what does it mean to parka cologne because I think well you had some coin but so if you pop five the cost function is so then you put the three and eight together whether eight instead of so it's somewhat cut the 5/8 then it went from so again cut the 5/8 then it went from so again cut the 5/8 then it went from so again eight times five minus three just prop that and then you have minus 5 plus 3 times 5 20 three months what's that this is negative 16 9 to the stake of that theory that cost function is 113 maybe it's not good enough only to do greedy in this case are you parked 3 so 5 goes from 3 to 100 that's it negative 10 this is just I guess it's like a weird sorting issue ami thing but thanks back to staying up posting wet hope I see y'all next week guy today trying to a mini marathon so that's why I've been longer than usual usually it's already 120 here - so a.m. so it's not like you 120 here - so a.m. so it's not like you 120 here - so a.m. so it's not like you know good yeah and I seen y'all thanks for their support okay so bye pop - eight if five goes okay so bye pop - eight if five goes okay so bye pop - eight if five goes from 8 to 1 so that's you go to negative 5 so this is 5 okay I mean I guess this kind of fits for this but like that does not it's not convincing enough for me boy Eric okay actually bite down coach I don't have to do it manually okay that's popping and changing - okay that's popping and changing - okay that's popping and changing - doubter yeah it's for testing just for intuition so okay so we pop this better and we get gonna be righteous yeah I don't know how long just bought my ticket because this is one of those phones I get oops and let's figure out the Delta of this which is some like weird cost function so get left I'm trying to hear when I pop five it's calculated while your left has a delta from your number two okay which I couldn't times make I even need to go too deep this is just confusing you mister smelling like let's just look at the shape of dysfunction Wow people overwhelmingly like this one so maybe I'm missing something obvious so in this case copying to one gives us negative seven don't think that convinces me of anything no ifs no buts this is the longest bit but in this case this is the highest so doesn't make this is like delete coercion of one boy well and then your last round you always know like wait waiting game with something like one more turn and then next thing you know your last turn takes like two hours this is what it feels like hmm how do I choose what's going to pop one of this like a heuristic to kind of do it is some sort of so I'm not talking about I'm talking for many hours straight I guess okay I don't know if there's an easy way to you to dynamic programming only because once you merge something it's over that and your problems or your like your cell phones you need to know where it began hmmm I think there's a dynamic programming solution but I don't think it's fast enough it sends you can enter the fifth or something you know it was smaller maybe when I do have a code a number one solution but seems like maybe not maybe it's a query with a odd course function there's no idea of left and right you pop a balloon I'm still thinking about in terms of subproblems maybe that's the wrong way to think about it maybe this is kind of a figure out the cost function well like a true course of popping a balloon which is not just a number of coins but it means a lot of implications that I'm not doing a good job of thinking about which is what I was kind of trying to see by you know the shape of these things all right let's go a little bit please case okay just one balloon you pop okay that's there's two balloons I guess this actually doesn't matter what order is up the two balloons like what the answer still let me just say yeah that's no that's not true two balloons you have to wonder lower one first yeah why did you five year you cheated of it thank you - it's my 120 plus 24 plus a thank you - it's my 120 plus 24 plus a thank you - it's my 120 plus 24 plus a 132 my not 20 my happen to be 2/3 for us maybe the greedy this way the greedy is popping the smallest balloon until got three balloons and then maybe after two three balloons you just proof force the race because as long as you two really biggest number maybe everything in between doesn't really know like but you choose the lowest well you have three numbers you pop the middle number some weird thing like that maybe it is just greedy because this earliest you pop the smallest number then your numbers get bigger together I think I was just over generalizing to and he goes three case and over thank you free case let me try dad and then we tried and able to say okay and with dad you could actually do which record I sleep but yeah I'm not going to I'm just going to do it we love it I'm just going to fold up to calculate them and just Chris I think it's like easy to call and I think for now I'm just in my testing by hypothesis mode so yeah I mean yeah nicely on the edge case I think it's around the edge maybe do you pop a long one that I wanna edge yeah maybe you do yeah maybe well so if that's the case I mean I'll explain why you're about this far maybe that's the case but maybe I could moduli such a function okay maybe right this is a little late but maybe my thinking make sure hot water is cold right here yeah well are you wasted I really need to down I need this - yeah I really need to down I need this - yeah I really need to down I need this - yeah I need this for calculating the coins final actually just now that's tough love it I don't know what I'm thinking it's just Glade in him then maybe this is my task alarm then okay so we what we said was we would take the smallest number I started implementing stuff that is what now I was a so that's not great mmm that's less than 100 so that smallest number has to say there should always be something okay and then now we wash that number cause I guess this is if it's queer don't we what we said earlier No like it says coins not cost okay now that we got it down to boy we get them well actually we want to get rid of them we still want to get uh we still want to get rid of all the zeros even before word we okay no it's a quaint way to filter yeah okay now we should get numbers now let me just compounder gonna see recompiles okay it compiles wish it did something that uh unit I was you into leaving because let me just any stupid so I guess in one elevation of the loop by the way you add a bunch more answers okay doing this way it gets interesting maybe but we already wasted a zero so this wouldn't happen if okay so there should be no zeros and the remaining answers then okay so we just maybe do a case yeah so you want a meadow and in a smallest number and bigger sample it's okay I don't know this is too greedy maybe I'm going some places and that's one the numbers are zero now we only we moved on a server so they shouldn't be there was it a smaller number first okay well you need to hope the numbers will give you the same some the same whatever and then smaller of the two numbers not the bigger of the two numbers that's the point of popping the small one but there are other cases because I've been moving a zero so if you have two numbers well a scimitar here which is we yeah okay if you have two numbers and you practice water one and mr. Adams take a number twice yeah and just one they just pop it three honest not convinced at all about the solution is very happy but yeah well I guess it has to be less than 100 but yeah also it's not the right answer I don't know what I'm gonna do I'm just gonna go find your stuff oh man so greediest doesn't seem like it's right then alright so this is kind of what we talked about with no never bad idea then what do I do well don't break it down to easier components to understood and then see where it goes wrong okay would you pop the - let me print even text pads I'm the - let me print even text pads I'm the - let me print even text pads I'm gonna like keep track so I mean here my strategy is to pop the - maybe that's strategy is to pop the - maybe that's strategy is to pop the - maybe that's not what no that's not right well how should I know well that's even like it keep going yeah and then after 15 sir it's this way at least okay so three case maybe it's like just add one but numbers back again and Zaheer is not to pop it Wow hmm well one dirtiness should be an endpoint i-best I don't actually but it shouldn't i-best I don't actually but it shouldn't i-best I don't actually but it shouldn't matter so what maybe I think I was some other strategy which is to take the biggest number I mean I think what I'm thinking of is take the biggest number or maybe went blue for us because every what I notice here is that you kind of actually want to pick its number in the middle right maybe he says best as you can and then 500 keep climbing to keep his huge and then all the other numbers are just in between and kind of other subproblems okay given two numbers how do I merge older intermediate stuff with time as the border may be tightest the dynamic programming just greedy work I said I wrote a lot of code but I do think I am getting a little bit of insight of Mabel to whitewash no query maybe not maybe making some progress anyway we definitely test to get rid of the zeros I think it does nothing for us except will give us negative score I'm not naked ever but you've got to be negative I think this point is what we have to do I think there this part is also should be mostly right because you know the only number of cases but at least maybe smaller about this greedy person a we just never want to get maybe I'd even the biggest number yet what is the biggest middle number or the best number for the middle can you do it that way well it's a path dependent I guess not because you always punch stuff around it but it like it's still a case where you want to pop like a couple of 99 in the middle now because then you cuz that would be one of your other conditions and then you have to figure out how to adjust it huh thanks for the tip let me think man uh think about this a lot already oh yeah I mean I've yeah I was I think I was like yeah getting to thinking about it thanks again for the tips I'm squirrel pox I mean that's why I was kind of thinking about like what does it mean for you a hundred I'm like well like you were saying what if that's already attached to last bubble like I said it's never greedy but untested ice bubble what does that mean well how do I restructure the prom to like what I want to intermediate perhaps in between like you know the left and the right okay I think I see what you mean actually and I think that's how you structured a time programming and it I still end cute girl maybe yeah okay I have blue cop in place it's go just in case just for my friends but yeah I think I'm gonna blame it on the sleep because that because yeah I think the key insight and I was kind of if I'd like I don't know you might miss the point where I said what if it's good but and I try to flooring it but because I was trying to figure out how to man I chef Cantus fast in it about rigor how to kind of separate the subproblems and but I was thinking too much about solving the problem first or like first to pop where you're popping the balloon mass then is a clear separation because by definition you're popping up on a mass then all your left will have to you know yeah okay if that's n cube I mean I'm waving a little bit but I think I have the idea you might had some ear I'll explain it after if I get it right but now that you're sort of snide and cuz I shall find out faster that's the case but uh what's the max 500 okay that's just negative one is a place on up now that's why they will practice never handed records about I'm still 2 n minus 1 you now we have two palpable doing so it isn't okay oh my toilets right I mean this is too white or you have two hours to write wearing that okay so let's say you picked iPhone into pop and I left anyway how do you get the number for the course it's something like cocktail of nine minus one times but that's the main cost not to matter why you I guess I could just store another thing I just didn't store another thing yeah okay maybe dollars to it missing key down yes that would you because to stop the best optimal things might not be so if we take this as your last number - uh - put into pop then you last number - uh - put into pop then you last number - uh - put into pop then you means you pop all your left balloon except of one aluminum trying to figure out what does that mean maybe laughs white is not the right formulation you know a start on this a little bit earlier mr. place yeah of course mr. go-to well mr. place yeah of course mr. go-to well mr. place yeah of course mr. go-to well this is the best name of coins you get is the left to right Plus what you get for getting this one which how do you get to test you maybe need to take a look right depending on your second I don't like your pass on the left and your pass on it away can and cute anything in here that would take way too long so you can reduce it to a hundred maybe I could abuse the fact that it's just a hundred your intent is like 10,000 times fifty your intent is like 10,000 times fifty your intent is like 10,000 times fifty hundred times 5/1 or 510 five hundred times 5/1 or 510 five hundred times 5/1 or 510 five hundred thousand times down that way too much today it's not like that's like if I'm a game I gotta find this well maybe this is one case where I actually learned something and I know the formation that goes at this but then it requires you to add a dimension which I don't think we could afford and also just a dimension here but which also we can't afford man is to a Oh mmm think that so that's why I was kind of thinking about it toward greedy but like I'm close no well if deeply is that the DP is the reason then you know that's how I would think about it great well at least memoization maybe there's a queen would think about it like this is also standard it yeah I'm just trying to figure out how to calculate the score right I mean I think I have century this is the laughs applause this is the right support and then I'm just trying to figure out the cause of or the score of you well of this one how do you get to left in there right like how do you choose - I like there's smallest index choose - I like there's smallest index choose - I like there's smallest index to get to score am I doing this weird and it's time for me to do some learning hmm I'm a guy oh I guess have to first love one you Fran chilly so that means Oh sometime I guess leftist implicitly to last one you ghosting so I guess the score is I think I made this ago well so normally everything in between and you do two thing last on the border we don't have to maybe read about this a little bit let me point around this and in the car thing right now which is my hunt explains how mixed up maybe I'd formated my deep here and over here I rap too you have to two pounds on the other side that's fine but thanks what the hell yeah let's - later today I'm just good I call let's - later today I'm just good I call let's - later today I'm just good I call it now mmm took this left twice one fine my intuition is an open off on this one well I just yeah that was very close but maybe not I don't think this function was kind of anti trouble with I think if I don't have to collect basic I have no base case so of course is not work but still no hmm well is it because well I see disappoint well I guess I don't eSport no there's only one number how its pain what am i doing uh sorry fights I'm sure it's just later good night there we go my thing is just we're all together thanks for the destroyer oh nice little Dino soaked wet ground made a comment okay cool okay well is that right it is something I need a awesome one more case maybe sorry I'm a little slow that's all it's a I'm on my seventh hour of decoding John and twitch so that's my excuse for being a little slow in time but it's the longest I've done but yeah I'm an integrator you need to do stuff for like five straight hours so five six straight hours so I don't think that's no reason to excuse well hopefully maybe there's slightly easier time based case I probably have an off by one somewhere I just don't like this is woefully right maybe I mean except for maybe one of the cases I bought that could wait - Mike cases I bought that could wait - Mike cases I bought that could wait - Mike the one yeah they feed you and stuff - the one yeah they feed you and stuff - the one yeah they feed you and stuff - yeah thanks for eating disappoint just let me just think I couldn't register them well one number is too far okay maybe I double karna this actually because I just already factors that in so maybe this is just soon maybe no that's not true you know this is flowing there's two numbers so I don't know okay this is not much just a lot so maybe that's a business right I must have double counted something I mean where did this all right now I cite the left size one because that's just a war yeah I agree that's why I've been trying to do a lot of them but uh today it's just been exhausting I'll just say mix right let's get some of these man I guess everyone needs well I get that off so yes that's good it means that somebody just when you walk it's off by 90 there's my two number ones all right why is my green check that assumption oh man I forgot that I changed sorry it's very late I've got that's what happens when you are like you're hacking face then take one price and you know they'd have to change another crisis okay it's still one thing but it's more right which is good enough for me well not good enough for me yet but good enough for now yeah i mean what you don't well you don't know is I'm just actually delirious what I had too much caffeine so I'm really into you need to use the restroom at a time blah it's only like six possibilities I just have a type of plan here Steve Tool Works maybe I don't know I want to start this way right that know that I think I try to wash it and that left me to do things in a way that I'm not usually deeply described which kind of sitting mistakes I'm the only screen up just called a little bit no I think you should still be the same thing but at least it's easier to read this is true only for two places maybe okay I am struggling with this bond right now in my face case as well what does it mean well we're not able to avoid them is your number is going to hurt me jump I think maybe you have to do maybe I don't pop the last balloon well no why because we tried to do it to see when didn't change the answer sir sure did change yeah we didn't know so I mean I don't know justice white but it did not change the answer so we pop you guys should manually mantissa and figure out what but uh you pop this one so well what does it mean to pop your left yeah you type this and if no dish mm-hmm yeah you type this and if no dish mm-hmm yeah you type this and if no dish mm-hmm I'm quite I think that's right oh my god but that means you parties you if we close on 32 almost not to like take care of zeros at some point I think I mentioned that earlier and I think it's still useful bit now let them off by one yeah maybe dish it's not like that except forgot to hand out education again yeah okay let me do something okay let's get back up on the servos for this and then maybe we just created porn trees maybe that simplifies our so much cases it did something I think I didn't do this for yeah so this one than you okay we're on the right track again maybe no aah and that coin I think this one has to so you pop this you get the court cost just because I'm used to optimization but this is actually just going to something that I like the subproblems okay well we don't need dry stone it is now that I have not opening the ones maybe not in this simplified apartment every move it took place where I can do what I don't know oh Jesus how does that give me I don't know what I mean it works but if you ask me if I believe in it I don't think I do that's my list of answers I thought question why not whatever fun people okay well if I don't terminate early uh yes like oh yeah I still don't know if I won somewhere that's fine oh no am i doing something funky because I can definitely be less than that I think this is just wow that's why I know you want that so maybe it's right but do I use end anyway what's hoping I mean I got one little closer but also maybe no closer to death what is this negative thing I mean definitely shouldn't have any many girls I mean this is a how do I even get negatives in here amazing processing random Wembley I mean it's probably just that is passing random memory so like it wasn't our bounce I didn't get check somewhere but more likely okay this actually seems more likely but it's that's more likely than an overflow because all these should be integers or like and they're just less than 100 even and I said that I mean to use the restroom again soon I don't get it because this should be at most one or at least one and at most n minus 1 then UN so of course oh wait England's - to make so of course oh wait England's - to make so of course oh wait England's - to make my restaurant ok let's try that you know cuz minus one is the last pound so and mine is just one with two one at the border ok yes I did fix something still wrong that's mighty practice with dynamic programming clubs all right definitely need this because I forgot to tell too soon so you can't just take gnomes nothing I have enough to look at us upon days I was so close I felt like I got that one other enzyme right okay see whatever should not be your thing so let's see why that is the case yep two numbers love more than to what I do in that case oh because I just never meant order things I did too okay I guess other stuff I did too just keep it Queen long time ago and I've been have been struggling my turn off by once maybe dynamic poor grandpa just not the way to cap off a seven and a half hour stream okay once again thanks for the hint yeah - once again thanks for the hint yeah - once again thanks for the hint yeah - callbacks I don't know I want to say I would have gone there eventually but knowing today oh maybe that's not true Ivan oh yeah okay yeah just y'all know you're too tired to play em even more test cases okay cool well I'm really slow - but you've an Ncube tickle only slow - but you've an Ncube tickle only slow - but you've an Ncube tickle only 16 millisecond which was actually surprising maybe I don't know why maybe the test cases are no Lex I think yeah first of all yeah I mean post-mortem a first of all yeah I mean post-mortem a first of all yeah I mean post-mortem a retro on how I saw the farm I definitely they try to I'm having a general you I don't I could have obviously skipped agreed yeah but I couldn't come up very quick each case for greedy so I was tryna and he's implemented to kind of get intuition about it I think for whatever reason I just didn't racialized a dynamic program fast enough I also I don't know I think I struck a little bit with I took and Cuba below too slow for n is equal to 500 maybe I got it to my math a little better two cubed is 125 million maybe that's fast enough yeah maybe my internal clock has to be a little tuned for it yeah exactly and I was doing it forward I think at some point I did cut when after I did the greedy thing I'm like maybe the greedy thing taught me to look up things to think about it in terms of what happens if I kept this balloon until the last balloon and that kept me and then that in a weird may be unnecessary but a long roundabout way allow me to kind of think about dynamic programming again where that was the last balloon to pop and that helped me have a separation of bound left and right but I think so one thing that I did want to point now a little bit is in my obviously I was ahead help them and once callbacks for which I'm thankful which you know unfortunately you know I'm on the tracks it's not gonna be at my interview side ever needed to be able to do this by myself like you know a little you know maybe was it go air pod cheating is Rises a friend no but uh so I didn't well I think I didn't formally I mean I think something that I definitely did a little bit bad on is well one is I didn't float out to things and we set up the problems and okay I chef created these wars a little bit earlier just to kind of so that I feel each cases because I was doing weird things that we sell but also yeah I mean I forgot to get a better sense of I mean and yeah if you watch me kid I don't know how carefully because I kind of did this phone and there for a bit but if you catch me on the stream I set up most of this immediately and some guys fight you know just one experience but that also kind of worked against me a little bit on this problem because I thought I was very close to the end when I didn't have a clear formation in my head which led to me having weird like a weird ish off by once under to subproblems and also the cost because I was using left and right because I was just like in my head I was like fudging I was like yeah I maybe I'll get it if I just kind of get it and sometimes it works but in this case I kind of paid a price for it but if I had kind of really step back and really formally but what this function means what does it mean to calculate left and right and excuse me and I think once I did that which was to which is the best cost that you can given that you populate one of them or you popped one of the balloons between left and right that's the and even now I'm sure going a little bit to be frank but that's just the best order the maximum number of coins that you can collect popping left and right laughs yeah III think I struggle a little bit with kind of you know and I guess to that point and I kind of played around it with a little bit well you said well what am i singing I'm singing oh it's still so I think sorry let me get it together in my head so I could kind of formulate this sub problem a little better I mean this up for me or you know which is the part of just recursion yes yeah the Mexico or the max number of coins between yeah the Mexico is that of from within that range where the Mexico is popping a balloon right well in that range glass to be honest I'm not convincing myself either a little bit maybe I'd to think about it but like you pop a balloon under well and in this case if we pop the leftmost button first then again you know you pop I'm sorry I do lass so if you pop the leftmost button last then that means that everything from I'm saying is really wrong that's for example is equal to left meaning you pop the leftmost but doing glass it means that you can only have two borders which is y plus one and that was one which you know is really default case it's just edges and the same in the right and in the middle of any of those buttons last that means yeah I'm struggling a little bit yeah I think the struggle for me like and you know this is like the setup of this poem and they're not many different type different types of setups with dynamic programming so like I have all this set up correctly I think it's just a deformation which determines the cost function changed a little bit you saw me struggling a little bit on thinking that from left to right this you also need to know the maximum balloon death within that range but that's not true because all the balloons already pops or your add so you're assuming that the last balloon that popped over there you don't need to return the balloon that was last part because you are popped for the cost function which is here because everything in between is already popped and out that was the part that I was struggling with a little bit but uh I think as a result I think one thing that I am trying to figure out how to do better about is yeah I mean I guess I solved this problem a little bit and I guess I know how to solve this particular problem if I see it again but what I need to do better is figure out well what am i or how am i learning from this and formally this problem in a way that if I see you know yeah a similar problem I could solve it way much better yeah maybe I chopped it up to a bad night Oh late night but it's still I wish I could figure out a sound a little bit better cuz Joey popped all the balloons from left to right and all your left and that's cut why this one doesn't have any you know cause of one of them the kicker is because you were popped or decrements inside you're left with left of that range and right of whatever that range is and that's what this thing is I mean we have one balloon enough along with your ranges one then Yugi you just pop that and you get to immediate borders I think I kind of understand this form but I think one thing I'm also just try to figure out in terms of learning is yeah how do kind of clearly formulators and I think thinking back I kind of was one step away from thinking it correctly initially where I was like okay because I think what I was thinking about sausage-like iterating thinking about sausage-like iterating thinking about sausage-like iterating pivots or their sub pivots on the left and on your way but I wasn't thinking well enough and which is why I talked about like the cost Bing and not enough but I think my sub problems were a little off in that I still worried about the numbers to pop but in that case or the last button to pop in that case my sub problems were wrong anyway but I was just kind of doing it all happened I think that's what I would say that's what the pattern-matching buys you what the pattern-matching buys you what the pattern-matching buys you it is that or like from being familiar with GT coupe arms is that you get so good at kind of writing these templates but you still have to you know understand the problem to really solve it and of course again thanks and blacks on you know walking me through it a little bit
Burst Balloons
burst-balloons
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it. Return _the maximum coins you can collect by bursting the balloons wisely_. **Example 1:** **Input:** nums = \[3,1,5,8\] **Output:** 167 **Explanation:** nums = \[3,1,5,8\] --> \[3,5,8\] --> \[3,8\] --> \[8\] --> \[\] coins = 3\*1\*5 + 3\*5\*8 + 1\*3\*8 + 1\*8\*1 = 167 **Example 2:** **Input:** nums = \[1,5\] **Output:** 10 **Constraints:** * `n == nums.length` * `1 <= n <= 300` * `0 <= nums[i] <= 100`
null
Array,Dynamic Programming
Hard
1042
447
hello everyone so in this video let us talk about a problem from lead code the problem name is number of boomerangs so you are given n points in the plane that are all distinct where the point is denoted by x of x and y of y a boomerang is a tuple of points i j and k that you have to find out such that a distance between i and j equals the distance between i and k you have to find out different type of tuples that can be formed the order of the tuples also matter so let's say that you have three point zero comma zero one comma zero two comma zero so let us draw it out let's say you have this as the number plane and this is zero comma zero okay the next one is one comma zero so one comma zero and the next one is two comma this is two comma zero number of boomerangs so boomerangs is that you can form any like you can find out any i j and k in this plane such that this line is equal to this line so what you can directly see is that if i just find out this as one of the possible answers so this because it is zero so this length is one so this is one of the possible tuples also but you can see that this is also one of the tuples so going from left right or right to left so because the order matters so what they are trying to say is that one comma zero comma one and two comma zero as well as one comma zero two comma zero and zero comma zero so if you just find out a decimal i and j and i and k so i and j so this distance is one and this is one this now i can find out like all of the possible boba ranks or electropulse in this because what you can actually see is that the total length is up till 500. you can do like you can do of n square approach but not of n cube because that will be like time limit x here but you can do easily now what you can actually do is that for a boomerang like for a boomerang to form the best case scenario is like you just have to ensure that for a given point what is this length and what is this line so let's say we just take out three points let's say i k and k so for a fixed i if i just do a for loop for every ith element inside the area that we have for every i okay we just have to find out what are the total number of lengths that are equal okay and from all of those equal lengths you can form out the possible number of what you can say boomerangs so what you can actually do is let's say for every given eye for so i just find out from every point i will find out this distance between every other point okay so let's say this point so for respect to this point there is one point here so i just find out all the distance between every this point let's say this length is one this length is two this then this two then this three and let's see one point that is three now with respect to this point how many boomerangs i can form with this as a center let's say if i take this is the boomerang this is the like a center point then i can form number of boomerangs with equal lengths only so this is one of the boomerang second form or this and this okay so what if let's say i have n lengths that are equal then for every ix length i can choose the other n minus one length okay so total number of boomerangs i can form is n into n minus one for a given point okay so what eventually i have to do is that for every point you have to make a separate map of how many total lens that are equal with respect to this point and then finally when you have all the map you just iterate over all this map and find out how many total lines that are equal so let's say there are two lengths of length one that are equal so for this one i can form this is the boomerang and from this one i can form this at a boomerang because order matter now let's see if i have three lengths so if i have three lengths that are connected to this singular point how many total moving second form i can form this boomerang with the rest of this boomerang which is probably this boomerang and this moving so for every ith point i have other n minus one point so for every n point i have other n minus one points which i can pair with total number of points i can form is this and then we just have to add all of those points for every ith point that we did over in this for loop and that's who runs so let us show and move down to the code part now so what we have done is that we have taken the total point of this whole array is n total number of boomerang second form is total and iterating over every ith point i will make a separate map and for that particular map what i'll do is that i will find out the distance between the is point and all the other points that we're treating over and stored inside this map okay what is whatever the distance now because the distance between two points is if you just want to find out distributing two points i know that you directly know the formula if this is x one y one this is x two y two distance between them is under root of let's say x1 minus x2 whole square plus y1 minus y2 whole square now because it's under root then and we are storing it in map how my total tuning occurrences are there then this will cause a problem because it is untrue but what we can actually do is because if we directly remove this under root also then also these will be unique values only because the distance will be unique so what instead of writing on this value when i just calculate out x 1 minus x 2 whole square plus minus y 1 minus 5 2 whole square because eventually we do not read the need actual distances we just need how many total distances are same okay so that so we are eventually in this distance are only calculating out this like difference into like difference whole square okay for x and y not the undo part and then add those distances inside the map now we have the total number of distances that are same now for we again hit it over the map and then for any distance that is like if i have any acres greater than one okay then what i'll do is i will increment the total i into i minus one so if i have total occurring so let's say n so n into n minus one so total occurrences i dot second for every given point that is inside this map so i dot second into i to second minus one so it is n into n minus and into n minus 1 okay that is how we can get the total occurrences for a given point how many total number of pairs i can form that will be boomerangs and then situation so going to our diamond city what we have done is that we have done two for loops and for f like for this outer follower we also make a map also okay so it so we are already creating a new map so this whole operation like inserting so it is n square login okay so n square and there's a login operation to insert inside the map also and that's so and then this is again in for you but the overall maximum which it is n square login and you can also like optimize the same mobility by making an ordered map also here but it i don't think so it does matter too much but yeah that's overall diversity for this problem as well thank you for watching till the end i will see you in the next one thank you for watching
Number of Boomerangs
number-of-boomerangs
You are given `n` `points` in the plane that are all **distinct**, where `points[i] = [xi, yi]`. A **boomerang** is a tuple of points `(i, j, k)` such that the distance between `i` and `j` equals the distance between `i` and `k` **(the order of the tuple matters)**. Return _the number of boomerangs_. **Example 1:** **Input:** points = \[\[0,0\],\[1,0\],\[2,0\]\] **Output:** 2 **Explanation:** The two boomerangs are \[\[1,0\],\[0,0\],\[2,0\]\] and \[\[1,0\],\[2,0\],\[0,0\]\]. **Example 2:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 2 **Example 3:** **Input:** points = \[\[1,1\]\] **Output:** 0 **Constraints:** * `n == points.length` * `1 <= n <= 500` * `points[i].length == 2` * `-104 <= xi, yi <= 104` * All the points are **unique**.
null
Array,Hash Table,Math
Medium
356
255
okay so back again the next problem we're gonna go with um yet another elite code medium so welcome and basically i'll just give you one moment and we'll check something yeah basically the last problem that we solved took us like half an hour didn't really need to take that much time but i got a little bit uncertain at some points so we'll try i'll try again uh the next question should i do as many problems as i can before 10 o'clock my time or just russians at 10 o'clock my time i should just say try to as many problems as i can for the night um if i want to go late i might go later who knows you know or earlier whatever what have you let me uh let's get the next problem let's take a look at the next problem so it's uh maybe a minute or yeah okay so the next problem verified pre-order so the next problem verified pre-order so the next problem verified pre-order sequence in a binary search tree let's see give an array of numbers verify whether it is the correct pre-order traversal it is the correct pre-order traversal it is the correct pre-order traversal sequence of a binary search tree you may assume each number in the sequence is unique consider the following binary search tree one two three five six five two six one three false five two one three six true five two one three six oh pre-order traversal oh no kidding oh only using only a constant space complexity probably not i don't want to do it recursively which would not be constant space but i actually could you could i think you could um so in through you could i think you can um actually i don't know if you can so basically let's see pre-order so basically let's see pre-order so basically let's see pre-order pre-order traversal you pre-order traversal you pre-order traversal you actually don't know i don't know about this we'll just say leave that for now so free or traverse i mean you could you would check you check the first value in order to be a binder in order to be a pre-order traversal of a binary search tree they have certain properties i guess i actually don't know i would do this even you know if we forget about this part um you have a left subtree or right subtree but you don't necessarily know where the right subtree starts so you want to verify the left subject but you don't even know where the right subtree is yet you only know where the right subtree is when the left subtree i guess ends so you would say all these numbers need to be smaller down the left sub left side so you keep going and then finally you have the end i guess since i finally have a number that's larger that's going to complete this first level here and the next number that's larger has got to be larger than this value i'd want to keep like a stack or something um so five two one and then three it's gotta be larger than the previous so this group of three you find and then the next value it's got to be larger than this one so six is greater than five three is greater than 2 i mean i guess you could do that kind of go from the outside in trying to figure out how we can do this with constant space complexity let's just try to solve it in general right in the first place if we could solve it at all and then figure out how to do the constant space complexity so i would probably use a stack it's real simple um keep pushing values from left to right onto the stack that are smaller and then eventually uh you'll get to a value that's larger excuse me you gotta compare that to the previous value on the stack um and pop the stack and then you see another value if it's now this next value could be smaller or larger right so if it's a basically the pre-order traversal you basically the pre-order traversal you basically the pre-order traversal you have a head node and then you have the tree split into two other pieces the left subtree in the right subtree and in order for it to be a binary search tree the left subtree has to be binary search tree and the right subtree has to be binary search tree and the left subtree needs to be everything in the left sub tree needs to be less than the head and everything the right subtree has to be greater than the head greater than or equal to or just greater than say um what's tricky about this is um basically as soon as you find a value from left to right that isn't smaller base pretty much what you want to do is you want to find the split between the two subtrees the left subtree in the right subtree the head of the left subtree in the head of the right subtree clearly you can just look from left to right until you find the first value that's larger than the head right that's got to be the right subtree excuse me because then you have this left subtree and then this right subtree and you can just do it recursively right the first value should be the head of the tree and then really the first value on the right side you know first value to the right that you find that's larger than this value it's got to be the head of the next tree so here five would say the left subtree is two and the right subtree is six however there's one and three being to the right of five is not a possibility another way to verify this is uh the property is that for each value everything to the right there is a certain number of values that are smaller and then a certain number of values that are larger and all the values are larger from us from one point yes the values that are smaller to the values that are smaller block of values that are smaller and then a distinct block of values that are larger and all the values are smaller or smaller and all the values that are larger or larger and if you have any kind of discrepancy in those two blocks then for any value then no that's not true i don't know it is true no yeah that's true it's like for one and three everything to the right is just larger for two you have one thing though that's smaller to the right and then everything else is larger now can you check that property directly without using any extra space because ideally what i would do is i would just do a recursive solution let me see if i can solve that or just resolve it recursively first so i'll explain what that would look like okay yeah we can just do this we could even do pointers um i mean yeah we'll just we're just doing a hp uh okay do unsigned ins all right um so we want to return f of we want to say okay all right um sure so what we want to do is interval equals pre-order is interval equals pre-order is interval equals pre-order of a now we're going to say 4 and x equals this one x is less than pre-order dot this one x is less than pre-order dot this one x is less than pre-order dot size increment x if pre-order of x pre-order of x pre-order of x is greater than val then um let's do it this way uh okay if pre-order of x uh okay if pre-order of x uh okay if pre-order of x is greater than the value then we break and you return a x and x b um let me just see here uh first value that's greater than and so you're actually going to recurse on a plus one um up to x minus one and then x to b it's inclusive these ranges and i don't know what this is going to do uh i don't know about this one i don't know this doesn't seem so let's see right here um all right what happens oh yeah i keep forgetting i'm throwing f here too this is basically recursive left side recurse on the right side oh whoops let's throw just a bunch of random numbers in here i don't think you have duplicates in a binary search tree by the way it's also taking me a lot longer than i was expecting it to uh yeah 18 minutes it's been a pretty good amount of time it's okay i guess you know um all right how are we doing here wrong answer sweet false true everything else false true false one of these are true all right yeah i didn't think the logic i don't really even understand the logic that i have here so this one is true okay so at one point yeah so how do we how is this supposed to work is the question um if a yeah if a is equal to b obviously that's just true by default uh if b is less than a then it doesn't make sense and if a is greater than equal to it was off the edge now that actually may not be a problem um this might be wrong yeah that might be wrong um that never really should happen though i think so we set val the pre-order of a we set xc with a plus one to the next index and now we say okay um as long as x is less than the pre-order as long as x is less than the pre-order as long as x is less than the pre-order size we want to find if pre-order of x is we want to find if pre-order of x is we want to find if pre-order of x is greater than value that's going to break so we found the next um i guess spot to split our array of x value pre-order x equals a plus one uh yeah found this next value of x to split the array it's pre-order of a value uh x equals a plus one just thinking all right when i find the first time where this is where x occurs where this is greater right now it could be that never occurs um which is not necessarily a problem because the right subtree could just be empty so actually you probably would return true here so wait so now here's the question if we do true then we're going to have truths when things are false and things are true oh no kidding hmm why does this give us false on the bottom one like if we did we just did this case five four three two one right that should be true but our algorithm won't come up true yeah and why hmm i actually want to say something like this still is false though uh that's interesting okay this third one causes problems why is that so the algorithm is five find the first value that's larger so recurse here and then it would say six first of all it's larger is eight and so you would record oh that's why you would recurse on oh it's actually the other one that's causing problems um the other case um i guess my question is do you have a return ever returned false why do you return when do you return false um right so here a plus one x minus one is you would say what do you recurse on if the next value is larger there is no left subtree basically if there is a left subtree if there is a right subtree you would recur so you just have to check if there is or isn't a left or right subtree that's kind of all i guess um yeah i don't think this is correct this algorithm i don't think it doesn't make sense to me but you would say left subtree which is to say that this is um the left tree subtree exists when the difference between x and this a plus one square that equal to zero right uh i don't know create another one so yeah x is the new right subtree's head and if that's right next to the previous subtree's head which is val or a um then there's no left subtree maybe let's put another way if x minus a plus one is greater than equal to one i think yeah that's what it's supposed to be a is an index x minus a um this is you actually this is a little confusing um yeah this is very confusing there's a and then a plus one those are two numbers two indices it could be zero and one minus zero plus one the number of numbers between three and seven minus three plus one is five three four five six seven that's if it's inclusive exclusive you subtract two that's why okay that's why i'm so confused yeah uh there's gonna be three really you'd say this is great that equal to three that's really the way i think about it there we go that's what we want to do okay yeah that's what we want alternatively we can yeah that's me better do it this way that's why it's confusing or just the difference between these two numbers is greater than equal to one or greater than equal to two really yeah it's so i don't know i'm trying to think of a way that's like easy to understand what this means um let's do it this way should be at least three numbers between the between these two all right subtree exists that's if um x is less than or equal to the index is less than or equal to pre-order.size pre-order.size pre-order.size or it's less than yeah it's going to be less than this index um and then we finally say little red let's say it's true if left subtree exists rhett and equals if right subtree exists and then return red there you go there's no left subtree and there's no right subtree that's just true um yeah i think that's fine it'll return true anyway uh okay all right what does this do now still wrong always true um say false okay let's do it this way ah hmm i don't know i was gonna say it's just always true why is this doesn't really make sense does it um no this doesn't the algorithm itself is like i don't even know what the algorithm is supposed to be i just want to just know that if the left subtree is correct and the right subtree is correct then the whole tree's got to be correct but there is a caveat here um we'll call it a key uh that got stuck well the tricky thing is the left every value in the left sub tree needs to be less than the key and everybody in the right subtree needs to be larger than the key so you just need to take that previous value and it's got to be less than the key so you say if pre-order of x or i don't know just call it k-a-x or i don't know just call it k-a-x or i don't know just call it k-a-x i can't call it k okay is less than the key first greater than the key so this is greater than the value that's fine you're done but if it's not creating the value and it's greater than the key they would turn false i think that's the only time you return false super confusing um i don't know what these sanity checks are supposed to do i don't know i really have no idea um call us in max i guess initially i don't know now we're gonna call these the new keys so these keys gonna be the previous uh values don't know it doesn't seem right mostly true it says um so greater or less than the key i don't know defense is the left or right subtree right i don't know yeah it's totally it's bunk it's not doesn't make any sense whole algorithm doesn't make any sense i want to use some kind of recursion but i really don't know all right so we got beat up by this question we weren't super speedy with our problem solving with this one we have to really think about it for a while how do you verify that the uh array you're looking at satisfies the pre-order traversal of a binary the pre-order traversal of a binary the pre-order traversal of a binary search tree that's a good question i don't actually know that off offhand i have to think about that for a while sometime like what's the case where it doesn't work well pre-order traversal the first element is pre-order traversal the first element is pre-order traversal the first element is the head of the tree some number of elements is the left subtree and then some number of elements to the right subtree could be zero or more all the values to the left need to be smaller than the head all the values to the right on the right have to be larger so you can group it that way you could say all right it'll take all the smaller values put down the left side all the larger values put that on the right side and certainly if we recurse on the left side and recurse on the right side and it's true on both sides now that's actually not enough that's where i'm getting into some trouble it's actually not true to just recurse to the left or curse on the right because not only does everything on the left side need to be smaller than that head node and everything on the right side be larger than the head node we're simply recursing on the left side and the right side does not guarantee if we just split on the first node on the right side that's larger than the head node that's not enough to guarantee that everything in the right side is larger that's actually i think the problem it's not enough to guarantee that everything the right need to guarantee that everything past that point is also larger than the head node okay interesting in other words just being a pre-order in other words just being a pre-order in other words just being a pre-order traversal is not sufficient the left side could be a pre-order verse on the right so i a pre-order verse on the right so i a pre-order verse on the right so i could be pre-order traversal however could be pre-order traversal however could be pre-order traversal however all the values on the right side may not necessarily be larger than the head node that you provided so you need an extra condition beyond just being a pre-order traversal and just being a pre-order traversal and just being a pre-order traversal and that's you just have to verify that everything to the right is what you can do um yeah you just you could say uh you could do it this way um just larger it's true and we'll say um we don't need this key anymore it's not really necessary so yeah dude this we could do this way um i think we'll just return false in these cases and this edge case will just return true and we'll say and really this isn't this is actually less than or equal to b i'm not supposed to go that far let's say i don't know v we'll call it v of g equals x so let's circle the v plus v larger and equals v greater than val and really we have yeah something like this i don't really need this anymore excuse me wrong maybe it's wrong but still giving me false huh oh could you how could you which one is the one giving me problems one two three this one ouch the third one huh oh why is that let's focus on that one false true five two one three six so we have two and three okay so we say val is pre-order of a is five val is pre-order of a is five val is pre-order of a is five x say plus one is two less than or equal to b increment x the order of x greater than val break so x is here which is zero one two three four right larger is true x is four less than or equal to b uh oh ah okay or we'll say i don't know um jay it could just be i and we'll say um that's probably why there we go okay i made a mistake i miss misprogrammed that there was no there we go okay right correct it should be correct now um see if they have any test cases where it's wrong let's go for it no probably wrong in a bunch of test cases why empty test case should be true um oh interesting huh um i feel like this should be true by default oh it wait what i'm so confused that's interesting all these cases just return true hmm oh okay oh pass all the test cases okay interesting it's too slow though i thought that might be the case um brother i'm getting my butt whooped by this problem no kidding it's a saturday right yeah wow um okay yeah okay you can use a key so there's a better way to do this right so obviously um this is an expensive way to solve this problem the reason why this is so expensive is that this takes um quadratic time if you just take the list and you put it i think you make it ascending what's gonna happen is at every point you're gonna guarantee you're gonna have to run a loop to guarantee that everything to the right is uh is larger than the head which if you sort the list from left to right that's very expensive it's true but it's very expensive ideally what you want to do is just when you recurse you have a key and you just check against that key that uh all the values are larger than that key yeah the left subtree doesn't need to be larger actually left substrate needs to be smaller but the left subtree is guaranteed to be smaller anyway so i don't really care so we could do it this way there's a clever way to do this or somewhat clever so actually it's in min is what you want and you say key so if okay all these values need to be larger than this key and left subtree is key the right subtree is actually going to give you the new and updated key here we go all right try again that's it's dying i am struggling with this problem man i'm struggling yeah this is sorted in descending order looks like this shouldn't be such a problem now we're almost descending 8 000 elements this shouldn't take that much time can i copy this um why don't you try one of the contest questions happening right now just for fun how's it going very single day how are we just going well welcome um yeah that's not a bad idea i could do that yeah sure let me see if i can finish this one first though yeah good call um okay 340 milliseconds well what's in tle on this one how come why not i got the timeout here uh why what am i doing wrong well this is certainly faster but it's not fast enough apparently it's kind of weird though because this breaks pretty quickly pretty soon checks left subtrees checks the right subtree i mean really in theory this shouldn't be too expensive because um hmm i it's correct right it's too slow though why is it too slow i mean maybe there's things i can do to speed it up i'm wondering uh if it's still correct if we just i wonder why it's taking so much time excuse me okay still correct still tealing it does why interesting that's sufficient as it is but um at least to solve the problem but how do you do this faster how do i do this faster it's not fast enough i'll be blunt i really don't know how i can make this faster i mean there might be a way to not use the um not use as much space but in terms of time complexity this is pretty fast it's pretty fast so um actually maybe it's not that fast i take it back maybe it's not that fast if that's a very large portion oh no right it was sort of decreasing order yeah i'm sorry yeah sort of in decreasing order no this is quadratic time i'm sorry i made a mistake right because if there's not much to remove on the right side each time for the right sub-tree for the right sub-tree for the right sub-tree and we've traversed from left to right until we find sort of the difference between the left subtree and the right subtree each time right then we have quadratic time for each okay i'm sorry i understand now yeah that actually makes sense i don't know why i didn't see that before i really like uh i did practice more i really thought i should have thought about this some more um okay i think i understand now the algorithm as written is not great i'll just say oh um it's correct but time limit exceeds the time limit that's quadratic time algorithm in some cases but how do i do this in a way that's not quadratic time if you want to do this recursively you know divide and conquer you cannot guarantee that the divisions are going to be of um equal size or even remotely equal that's really the problem yeah it takes a linear roughly a minute linear low of end time linear amount of time each time you execute to split to divide and the divisions are not necessarily uh equal in size so that's it really um that's the problem that's why it's quadratic time now in theory oh that's clever how about this you can treat the first leg of the pre-order the first leg of the pre-order the first leg of the pre-order traversal first you know sort of from left to right that section should be sorted in descending order so you can actually if you know that's true you should be able to use a binary search on that um i want to say in logarithmic time you can find the first value that's not decreasing i guess not if that works i don't know if that makes sense so i want to say if you can find this in logarithmic time instead of linear time then you're fine then you're in good shape it's going to be the first number so there's a left half in the left half and a right half and if the number is smaller well actually you're doing something really interesting you're trying to split the remaining um values into two pieces but specifically you're trying to find to the left side all the numbers are less than a certain value and to the right side all the numbers are greater than a certain value so you really want to find really from right to left of oh that's really interesting yeah you can use a binary search you should be able to not even think of that's very clever okay um hmm what's interesting though is that basically there needs to be a value in that range they need to be both larger than the vowel than the head and also larger than the key you'll certainly run into a point where that's not true if yeah you can do this and then you can do um this is kind of interesting so first element in the range is greater than value ah could be greater than both yeah that's it and the value which i think you probably want let's see happily i don't have premium so i don't know what that question is but it looks like a good solution except it's slow happy decoding keep up thanks yeah thanks i appreciate that oh yeah you can't see the question yet i'm sorry it's premium um thank you yeah it's a slow solution i'll see if i can get the right solution though see if i can get there i don't think we need this part anymore this larger shenanigans we would say um so i don't actually know how this is going to work um they're looking for the first value no this is wrong the first value that's larger than this pre-order from left to right it also has to be larger than the key larger than the head right because that value must define the right sub ahead of the right subtree because if it's not at the head of the right subtree that means it's got to be the left subtree which it cannot be so all right and we would say so right exists p is not equal to end it would really be n plus one left subject exists um we could just do x the end if we and we say um yeah that's fine so we can say i don't know about this let's just think about this for a minute um i don't know man dude i'm like getting really hung up on this question right subtree exists when x is less than or equal to b and the left subtree exists one x minus a minus one squared equal to one or x minus a minus plus one is greater than equal to three and you would say there's this rhett cursing the right subtree oh um yeah so the right subtree exists you say this has got to be and p has got to be greater than the key and then f l x b f yeah left subtree exists because the right subtree doesn't necessarily exist in which case p may not be defined if the left sub tree exists and you just and equals with uh xbf left side a plus one x minus one something like this i don't know man i don't even know if this will compile i don't know what's gonna happen here always false great i don't know man i gotta really think about this um all right first things first uh let's focus on one at a time let's do five two one three six all right let's do that okay what happens here okay so our key is very small say five let's f5 to the head now we want to say okay somewhere here from left to right there is a number that's greater than five so find this upper bound again now a is zero this shouldn't be plus one that's just a and the end is b plus one so we would find a pointer would point here right six okay six where's what we got so this is fine let's begin and end for whatever reason that seems okay um i was actually thinking that these you wouldn't want to add and subtract these iterators this way but these are random iterators so it's fine it actually works out if you're dealing with other kinds of iterators it'd be harder you'd have to use a different syntax so that's something to remember for myself um but anyway so this index so okay so now we get this right subtracts this left subtree exists x when we're looking at zero one two three four uh minus zero so x is four right that index and we say if this is less than or equal to b and the right subtree exists it's left subtree x minus four plus one square negative three um x minus zero that's one right there's one two three four that's the number i should get which is what i get yeah which is greater than another three um that's actually five we got should we get one two three four five rather yeah okay so the left subtree is the right sub trees we say okay let's take a look at the right subtree and right p is greater than the key that's good um i have our new value which is going to be six and we say okay val of x b and f x is four v is four l is six okay um interesting i don't think this is necessary i think this is gonna always be true well i don't know let's see um a equals b so this part returns true i believe so one is true yes this word is true which is what i expect um okay it's false though in the next iteration six so yeah so that actually goes off true and then let's look at the left subtree iterated on the left subtree you have this value which is five uh no that's wrong that should be the key left subtree oh it's true okay it's really confusing i think what i wrote was confusing as heck also i don't think that's all right well all this is wrong anyway um all right which part was wrong the third one from the bottom is the only one no there's a few okay which one is that one two three okay five two six one three four true false so our algorithm would uh find the first value it's larger than five which is um six i guess and we could print to see what this finds what this gives us so first get three which is strange because i really get six um what happened here two why is two what is going on what am i looking at here one why is a one ah my freaking brains on delay here what's going on i am definitely missing something here what is going on um uh what did you go to bed okay it's a zero and somehow oh let's see i see the problem that's why no kidding so what happened is there was no value found that was larger now here's the tricky thing this upper bound assumes that you're dealing with a sort of a set of numbers that has a certain property excuse me so i think it assumes that they're sorted right no that doesn't work properly so the thing that i guess i'm trying to check is i'm gonna lay down for a minute i'm getting really tired um i think i found the problem um the i guess the problem with the algorithm that i'm trying to use is that um false i guess false negatives so false positives i guess is the issue so if it were true that this was uh the pre-order traversal of binary uh the pre-order traversal of binary uh the pre-order traversal of binary search tree then this algorithm is always going to return true on those cases however if it's not true that this is a um in other words it's false that this is a binary the pre-order traversal binary the pre-order traversal binary the pre-order traversal binary search tree the algorithm that i have will not always return false sometimes return false positives that is the problem that we're looking at right now the issue that we're seeing which is pretty interesting excuse me no what i was hoping yeah so that's the problem um basically we need to figure out a way ah well um this is a tricky thing what i want to do excuse me i would like to do yeah so okay so i'm really not approaching this problem correctly right like i need a solid solution before i start coding kind of just wildly coding things and there doesn't make sense you need to actually have like a solution before you start programming it right like this it's not correct or not reasonable to just start programming so the issue seems to be that we want to find excuse me um we want to find the partition element such that all the elements to the right are larger than the value you're looking for and all the elements to the left in this particular range split the range into two pieces partition the range in two pieces now obviously this works nicely if we assume that the range is already the range can be split in that way however there is a problem um if there could be two things it could be that all the values then i guess this value you're searching for so there's no there is no right subtree that could be true that would actually give you know sort of the element would sort of just fly off the side of the but yeah basically you would show up you wouldn't find the element that you're looking for right if there's no right subtree to be found that could be one case but another case could be that you can't actually partition you know your numbers are not partitioned in such a way where there's two distinct you know one side on the left side is less than your value and the other side on the right side is larger than your value that could just be false in which case you may also run all the way off the edge or you might grab one of these numbers now if you do end up off the edge basically you want to verify that indeed there is no right subtree if you go off the edge though and you don't find that there's no right subtree so let's say you could do a linear search an exhaustive search and just check left to right to see if there are any values that you should be finding if indeed there is no right subtree then you would just recurse on the left side substrate right you just wouldn't rehearse on the right subtree now the problem with that though is you can't tell whether or not there's no sub tree no right subtree at all or if there's if there is a uh or if the partition won't work properly now if the partition doesn't work properly uh you return false right that's it you just you can't partition um you sort of terminate early you'd be able to check that in uh in linear time because everything on the everything's in the yeah you must have that partition must exist but the problem then is that if you let's say you just sort in decreasing order from left to right um the first time you would show that okay you don't have a right subtree logarithmic time but then you'd say okay um it's for curse but let's verify that we're not in a faulty state i guess so let's suppose that p goes right out right off the edge now we don't know without the left subtree well yeah we're going to process now this lad this sub range as a that's just the whole range of the left subtree um okay now what ought to happen is our key gets updated and basically if any value in that left subtree is larger than that key um then we returned false i think that might be the problem we just need to specify um and then you're looking at left subtree or right subtree i mean that may have been the problem all along sort of um just thinking now um so actually i think i know what i'm doing wrong um there's a range these numbers need to be in that's what i'm doing wrong duh oh i feel so silly now i've seen you know okay these binary search tree verification questions really what you want to do is you just need to pass in a range of values and update those range values accordingly it's really what it comes down to um yeah that's all you have to do okay and you just have to compare that all the numbers match the range and specify and update the range accordingly if it's a left subject right subtree just update those numbers and i mean a minimum and a maximum range you know in values minimum maximum values yeah i don't know man i like i think i just need more experience with these questions because i've seen binary search verification type questions in the past and i know that you need to do some kind of like min max um verification but i don't do it like i don't always think to do that which i think if i thought to do that in this case i'd been i would have been done already but yeah it seems that you do a logarithmic search to find the upper bound and i guess you assume that it's correct until it's not um and excuse me there is a verification excuse me during the verification of the sub trees it'll come out that the range wasn't actually um partitioned that's pretty much what should happen and that's about it but you do need a left subtree check and a right subject i can eat both and that should give you n log in time recursive check now the tricky thing here though is how do you do this with a constant memory oh i have no idea not a clue i guess you'd have to use some kind of a while loop i don't know some i don't know oh excuse me uh constant memory huh i have no idea i don't even have the regular solution yet let me try that let me try the regular solution first see if we can do that the recursive one very similar to what we were doing oh okay awesome man i'm falling asleep here i need to go to bed all right um okay excuse me okay let's do this um lower upper ah say yeah lower greater than the lower bound of the small lower than the upper bound um and um so the lower and upper and the lower value so the right subtree the lower bound is going to be updated to this value on the upper bound is the upper bound doesn't change so the right subtree everything has to be greater than or equal to it's gonna be greater than or equal to whatever the previous lower bound was and uh whatever this value this new value is it's gonna be greater than equal to both the upper bound doesn't change and the lower amount of the left subtree lower bound doesn't change but the upper bound changes everything's got to be lower and smaller than the left subtree everything needs to be smaller than everything yeah everything to the left side is still got to be larger than whatever the range is lower bound but the upper bound now everything has to be smaller than the head and it also has to be smaller than whatever the previous upper bound was so let's get updated on the left subject right subtree um now this pointer being greater than the key um i don't know if we need to do that anymore i don't know if that even matters let's just check to see what happens here if i do this wrong answer true false nice um okay we can just do uh oh okay sweet oh nice i see it works now okay that's all i had to do here's another question um do we even need these does that even matter oh it doesn't seem to matter got the feeling like it wouldn't i got that feeling like it wouldn't see a non-existent um yeah basically it's vacuous vacuously true for non-existent true for non-existent true for non-existent intervals and then for the other interval intervals you just need to make sure that your values are in the upper and lower bound ranges uh if the interval is just one and then i don't think you even need to check this quite frankly this is sort of a base case you don't need to do any more recursion after that um all right that's good are there any test cases we fell on nope oh okay wow brother this is uh okay yeah i really need to get better at uh oh i don't need this anymore either anyway yeah i really need to uh need to practice some more you know um no kidding can i do this um just looking to see which parts i can remove huh pretty interesting so okay now the question is how do you do this with less memory so this should have been like a really easy question i don't know man i'm like not that great at this but in simple terms um yeah whenever you're dealing with verifying binary search trees you want to basically have a lower bound and upper bound that you're checking against and uh yeah if it is indeed a binary search tree then you can use this binary ser yeah if it is indeed a binary search tree in this case you can actually use this routine to do a logarithmic search um obviously if it's not a binary search tree and the logarithmic search gives you something funky then at some point you're going to violate your bounds on the lower and upper bounds just have to update them correctly between each excuse me for each of the other excuse me iterations now right now the question is um can you do it using only constant space complexity i could i was barely able to do it using extra space the constant space complexity basically you would need to do these without a recursion um the problem that i have with doing it without recursion is it feels like i would need a stack um yeah i don't really know how to do this without recursion you could view this like a depth first search in a breadth first search um like i can definitely do this iteratively using a cue in sort of a breath first search type of way but that's not constant space complexity all right definitely not the way i would do this using constant space complexity i think is i would need to this is property from left to right that for each number there's a certain pocket of values to the right where there's a certain point where to the right all those values are larger but up to that point all the values are smaller so as you move to the right all these values are smaller and then boom now the values are larger and i guess there's this check that you want to do basically i want to do a kind of like dynamic programming sort of thing like a very clever way to do this that doesn't involve recursion or searching i don't want to say you say okay um i guess if you start with five then all of your numbers the right of five have to be less than five up to a point where they're no longer less than five so i guess you have a lower bound and an upper bound where your upper bound is infinite and your lower bound your upper bound is five and your lower bound is infinite and you get to two and you say okay now two is less than five that's greater than our lower bound now harper bound goes from 5 to 2 and the next value has to be less than 2 and it's not the question is it greater than it's going to be greater than 2 but is it greater than 5 also if it's greater than two that could be okay no see that's not that algorithm doesn't make sense that's not necessarily a correct algorithm right like i don't actually know five two one three six and then one is less than two and then three is greater than one it's gotta be greater than two also i mean maybe uh maybe you're supposed to maybe it is still sort of end login time and you say okay um once you find you know six is greater than you know it's greater than the last value it's greater than your you know it's out of a certain bound you want to find out which value is it greater than i guess then you can figure out what value is supposed to come after six i don't know because if this is greater than five everything to the right of that is all supposed to be also supposed to be greater than five interesting huh let me lay down for a minute think about it i'm wondering if there's a way to do this that involves maybe a binary search or uh or just something some constant time so i think i'm thinking excuse me basically the first value you look at is the head the next value is either on the left subtree or the right subtree if it's in the left subtree that means it's smaller than that the previous value if it's in the right subtree that means it's greater let's suppose we're in the left subtree for a moment that means we have to be less than the head and then now this value is the new head of the left subtree and so our sort of our state is kind of the same as it just was where we have a new head and now this next value we look at we compare it to that head we say okay are we smaller or larger now if you're larger then you can't be larger than that means there is no left subtree and you're in the right subtree and again it's another ahead of another subtree um but i guess like if you just kept going smaller on the left subtree all the way down sort of nothing changes i guess in the state of things something like that if you but once you switch to the right subtree that's when things get interesting so as soon as you switch to the right subtree your you're larger than the previous value um now the question is which sub which subject are you a part of then like which head are you now that the subtree of and i think you could use a logarithmic search there right because um from left to right after that point you could do a logarithmic search to figure out which head your which head you're larger than um which part of the tree is that node belong to basically how many um of these sub trees that you looked at this left subtrees how many of them are empty right um so let's say you're right something because you perform your logarithmic search and you find that your i don't know somewhere in the middle so like 500 400 300 200 100 and then you know your value is like 350. so there's 500 400 300 200 100 um and you're 350. so you're right on off of 400 you're that right subtree there okay now you're 350. now you basically repeat your uh your algorithm i mean no what's the significance of that though um i don't really know exactly i think you use that to update what the um what the i guess the minimum and maximum value should be uh because if you now find a right subtree there that's no if you now find uh actually i don't know i want to say if you find a value that's smaller to the right it could be a left now you can see the left subtree right subtree of the node you're looking at if you find a value that's smaller oh yeah the reason why that's significant is that any number left or right has to be at least as large as that number they just found which was when we say was uh 350 and 300 and 400 right so your 350 is it's gotta be hanging off of 300 so you can't have any number less than 300 now i think that's why so if you find the left if you're on a left sub tree and you go below 300 that's um that's your new minimum that's your new lower bound oh and that means you're not looking at a uh a binary search tree anymore but let's say you keep going you do a similar thing you get another right subtree um and then now here's the thing um you could find that makes that works for the first right subtree but let's say you have another right subtree right and if you are above if the next value you find is larger than it's the sort of two nodes there right there we said there's 300 and 400 and so that actually tells us that all the nodes that we're going to look at now on this right subtree must be between 300 and 400. it actually gives us our bounds because if we find anything above 400 that means that it's a new node on that previous branch previous tree and that's actually where i think we need the stack because that's because that gets confusing right because you have multiple you know you have multiple layers and these branches that's kind of where you need the stack i just gotta figure out you know where the heck is this new node supposed to go because you can't have a node that's smaller than 300 uh all right that's sort of already done i guess um but you can have a node that's larger than 350 then 400 or yeah because that would just get placed on a different tree um right now what's interesting is when you move to a left sub-tree all those values have to be less than the head and now you just saw right and when you move to a right subtree all the values have to be larger than the head however when you move to a right subtree you don't necessarily know which head that node belongs to which is a little confusing um now in theory the easiest thing to do is just find the first number that's larger than your head value and then you say everything then that splits the array into two pieces right the left subtree and the right subtree that's all well and good however that's the basis for the recursive algorithm we're trying to figure out a way me should not only do it iteratively but also do it without using a stack which is super challenging it's extremely challenging hmm excuse me now i'm wondering if maybe there's a way to use the vector itself like a stack in that you could somehow save the position you need to jump back to i don't think you can i don't think it's that easy i don't think so i think it's no i don't think so i don't know i mean as i said certainly navigating you know down the left side of the tree through the different head nodes i think it's smaller and then boom you see a node that's larger and then you want to figure out okay which head does that belong to and then you put it there and you say okay let's see the next value is another if i it's larger i guess again so you have these ranges of left subtree nodes that you want to iterate over um interesting excuse me here keeping track of all the nodes to i don't know man it's hard seems like there's a lot of information to keep track of well as soon i mean as soon as you see no see a value that's larger you don't necessarily know where that node goes um the thing is if any if it's larger than any of the nodes you've already seen then that implies that all the nodes that are smaller than that you're not going to see if that makes sense um you're not going to see any more of those because i mean not just that one i mean it's gonna be the i guess the head node that it's attached to and you're not gonna see anything smaller than that head node because you can't right i mean certainly anything larger is either on the on that right subtree or is on some other head node that's larger off of some other head nodes larger possibly but something that's smaller than that current node's head node um basically if you see that it should have already been processed if that makes sense because everything to the right of the head of a right sub-tree of the head of a right sub-tree of the head of a right sub-tree needs to be larger is that right i don't know i'm kind of just babbling on here because i'm just thinking it through like what are some of the properties that we can use of these trees that could be useful everything to the right of a head node there's the root and the head of the right sub tree well the thing is yeah you've got this left subtree it could be sort of any shape um what once you see a node that's larger than a particular head node then all the nodes for that head node you've already seen that's good yeah it's going to be true the reason for that is that for a particular head note everything to the left of its subtree is less than and everything to the right of its subtree is larger but also everything in that right subtree follows everything in the left subtree so there's a certain partition point where you will no longer see that left subtree and if this node is encapsulated by another you know let's say this is like a sub you know that's a subtree of some other tree whether it's on the left side of the right side that property still holds um that's actually that's the question i'm wondering like i guess what i mean to say is that because everything on the left subtree so it's always going to be preceding the stuff in the right subtree this is a certain like cascading effect i guess i'm not really sure how to express it an inductive property where you can make some guarantees um i just think the left subtree the right subtree uh like i want to say that you know you if you have you see a note you know you're moving from left to right you see a whole bunch of left sub trees see a right sub tree you say okay this is the finally i found the head for that right subtree you know the appropriate position to put it in um you can guarantee after that point that the head of that node you won't see anything to the right of your current position that is less than that headnote true because for that head node there's a left subtree and a right subtree and everything in the left subtrees or you've already seen it right correct and further that means that every node from there on out to the right has got to be larger than that particular head that you found so you have an absolute minimum like it just got updated true now do you have an absolute maximum is that possible um not really i don't think you ever really have an absolute maximum or not necessarily because the deal with the maximum is that uh the maximum will just tell you don't really have a maximum actually like well i don't know actually i don't know now i'm not sure i don't know what to think of the max we definitely have an absolute minimum there taking up that i got it got updated but now here's the thing like you could have multiple layers of you know from that right subtree you have a bunch of other left sub trees and then another right subtree you know the left sub trees and on you kind of have this like i don't know you have this like nesting that goes on and the problem is that let's say out of the blue you do get this very large node that goes all the way to the top level and that's supposed to be your new right subtree sure you get a new minimum um but like how do you know which left subtree you're supposed to jump to because in earlier when there was only one sort of branch to pay attention to uh it was pretty simple but now you need to somehow keep track of the quote-unquote holes the quote-unquote holes the quote-unquote holes to figure out which head node to jump back to see that's the thing i'm not sure about um well you're not gonna jump to the previous ones ever again uh the smaller ones so that's kind of good i guess however when you do your searching you need to somehow i don't know jump to the correct ones i'm not really sure because we're trying to do this with all this without any extra space um so we're not really keeping track of the sort of holes uh quote this stack would be useful there what you can do you can actually uh i have an idea you could okay this is kind of uh tricky but if you're okay with destroying the array right at the end of it what you can do is basically you have your logarithmic search that you're going to do now that you know you're not going to revisit a certain node you can write in that node the index um that you're going to jump to perform another binary search if that makes sense um so if your binary search fails that sort of gives you your stack you kind of jump to the next index to search maybe you could do something like that and then you would in that way you would actually be able to chain your binary searches to figure out which node to jump to and ultimately the i want to say something like there really can't be that many of these indices to jump through something like that i want to say something like that some kind of algorithm that you can come up with sneaky kind of algorithm where you uh you don't use more memory you don't need a stack but the stack is sort of implicit in the array you kind of write it in as you walk through it something like that i don't know i mean it's pretty uh i don't know if you can even do that if that even makes sense i don't know man i don't know i'll have to come back to this i think about it some more i don't know if i'm gonna live stream that part i'm really tired uh probably just gonna end the stream go to sleep but this has been a really interesting question i got stuck on it you know i don't know what the uh how to do this without extra time complex extra space complexity let's really ponder it some more let me uh oh what oh okay let me go ahead and get going let me get going so thank you all for watching hanging out saying hello i do appreciate it um wow oh it's two and a half hours i spent on this no kidding dying all right i'm getting out of here so take care have a good uh have a good rest of your day rest of your night
Verify Preorder Sequence in Binary Search Tree
verify-preorder-sequence-in-binary-search-tree
Given an array of **unique** integers `preorder`, return `true` _if it is the correct preorder traversal sequence of a binary search tree_. **Example 1:** **Input:** preorder = \[5,2,1,3,6\] **Output:** true **Example 2:** **Input:** preorder = \[5,2,6,1,3\] **Output:** false **Constraints:** * `1 <= preorder.length <= 104` * `1 <= preorder[i] <= 104` * All the elements of `preorder` are **unique**. **Follow up:** Could you do it using only constant space complexity?
null
Stack,Tree,Binary Search Tree,Recursion,Monotonic Stack,Binary Tree
Medium
144
242
question 242 of leak code valid anagram so given two strings s and t return true if t is a nanogram of s and falls otherwise an anagram is a word or phrase formed by rearranging the letters of a different word or phrase typically using all the original letters exactly once so in the first example we have anagram and nagaram which returns true because if you see all the values of an s are within t and there is no remaining values rating carbon the second example is false because we have two letters in each which don't add up right the only thing that's similar between the two examples here is the a so we could use some kind of sorting algorithm and sort them and then see if they're the same that would work just fine but what we're going to use instead is a hash table also called a frequency map and we're going to store the frequency so we're going to loop through s and we're going to update our frequency map so this is what the frequency map is going to look like so we're going to have a which is going to be pointing to 3 right because we've got 1 2 3 n which is pointing to 1 g which is pointing to 1 r which is pointing to 1 and m which is pointing to 1. so we've created our frequency map now what we can do is we can loop through t and we can see if the letter at this position is found within the frequency map and if it is then we can subtract it from the frequency map and then we move along we can subtract it we can move along subtract it and then once this is complete if we pass all the tests that we have in our full loop checking the frequency map then we can return troop right but say we have an a here we get to the a this is going to go to -1 so we need this is going to go to -1 so we need this is going to go to -1 so we need some conditional logic which is going to say if so if map or letter is less than one just return false or if it's undefined return false so the way this algorithm is set out time complexity would be o n where we create the hash table so we have to loop through each value within string in order to create the hash table so that's going to be of n times so it's going to loop through the entire string plus m where m is looping through the entire t string and then space complexity is of n because we're storing all the values of string s within our hash table which we've created so firstly before we add any code we can take care of an edge case right so if s dot length doesn't equal t dot length then it's not going to be a valid diagram because they're not the same length then we need to initialize a map so our hash table which is going to be an object we need to loop through string s and we need to populate that map so let's just declare letter as si so we're grabbing each letter here if the map at letter doesn't exist we're going to create it and set it equal to one else map of the letter gets incremented so if there's already a value within map that letter then we just increment it by one and this will give us the frequency map we're looking for okay so the second part of this algorithm we just need to loop through the second string create a variable called letter we'll equal it to t at position i so the second string at position i to make this code a bit more readable then we need to carry out a few if clauses so if map at letter is undefined we can return false right because it's not found within the map so they aren't valid anagrams if map letter is less than one we can return false because there's more of the same letter in one string than there is in the other so return false and then map letter decrement so if we pass the first two if statements then we need to decrement from map at that letter's position and if we pass all that throughout the entire for loop we can return true because that will essentially be a valid anagram let's run this to see if it's worked okay let's submit it okay and there you have it
Valid Anagram
valid-anagram
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** s = "anagram", t = "nagaram" **Output:** true **Example 2:** **Input:** s = "rat", t = "car" **Output:** false **Constraints:** * `1 <= s.length, t.length <= 5 * 104` * `s` and `t` consist of lowercase English letters. **Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
null
Hash Table,String,Sorting
Easy
49,266,438
1,604
Hello hello friends so this is the problem from the list difficult contest 3638 omelette using quantity three or more times in one and ₹ 100 from the station I want you to check on one side light sweet crude oil price in a 10 name the The person who is the list of the people and not the example of who behaves the two is research in a manner type and name is the name of the portion so let's have a pun cheese litterateur dad tank and Sudhir Vaikunth comes in his white skirt 100 gram channel Subscribe to 1110 More Read That System Map The Time Win The Opposition Fighter Card Okay So This Pregnancy Difficult Time From 2211 Research Alien Impatient That Always Notice The Video then subscribe to How To Editor In To The System Valid For Android System But Milk 100 Is Not Considered to be seen it is due to solve this problem solution President Number of People More Than One Should at Least in Alphabetical Order Subscribe to Channel Subscribe to Swarna Time and OK 100 Grams Defining Dictionary for the Times and Doing Simply Midning Dip Ki Calculation of and Eliminate setting the full value point one ok so the solution from left is that time thirteen cases minute tawe and 3000 minutes and subscribe this Channel and subscribe the Channel press The Seervi media agency list and adjacency maximum lagna approach should not contain information and can have reduced Should Not Going Strong Entries and Outgoing APN Subscribe to the Video then subscribe to the Torch Light Bill Complex Finally E Will travel through period hole's set of the agency list all of the map ok chirva flight real mathematical operations to check also bounce of the time should share and performing wash population du Plessis like it ifik sundar karenge is loose the person for the 3031 more subscribe The Channel and subscribe the Light a lamp o Pregnancy It is not done with the change of wave effects Entry 800 to 1000 Cities to Take Off Pollution in English for Kids for the Efin More List Play List Subscribe Time is the Tree of Life in Everyone Time They Do Subscribe To Who Is The Inside The Range Of Merit List Side Table Of Saintly Figures List Start Doob 600 First Time Because There Are Candidates Author Last Time 100 subscribe The Channel and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Difference Last Time Machine Time Travel Give Me The Volume With Range Just Like It Is In The Range Of Dresses In Can See The Question Is The Range Of Channel Subscribe Button To The Journey To The World Will Be Subscribe My Channel Like This is what we call the return typing is slow to-do list sudhir va basic operation to convert president to the list final reduced to select from its ncc the like share and subscribe 602
Alert Using Same Key-Card Three or More Times in a One Hour Period
least-number-of-unique-integers-after-k-removals
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `keyName` and `keyTime` where `[keyName[i], keyTime[i]]` corresponds to a person's name and the time when their key-card was used **in a** **single day**. Access times are given in the **24-hour time format "HH:MM "**, such as `"23:51 "` and `"09:49 "`. Return a _list of unique worker names who received an alert for frequent keycard use_. Sort the names in **ascending order alphabetically**. Notice that `"10:00 "` - `"11:00 "` is considered to be within a one-hour period, while `"22:51 "` - `"23:52 "` is not considered to be within a one-hour period. **Example 1:** **Input:** keyName = \[ "daniel ", "daniel ", "daniel ", "luis ", "luis ", "luis ", "luis "\], keyTime = \[ "10:00 ", "10:40 ", "11:00 ", "09:00 ", "11:00 ", "13:00 ", "15:00 "\] **Output:** \[ "daniel "\] **Explanation:** "daniel " used the keycard 3 times in a one-hour period ( "10:00 ", "10:40 ", "11:00 "). **Example 2:** **Input:** keyName = \[ "alice ", "alice ", "alice ", "bob ", "bob ", "bob ", "bob "\], keyTime = \[ "12:01 ", "12:00 ", "18:00 ", "21:00 ", "21:20 ", "21:30 ", "23:00 "\] **Output:** \[ "bob "\] **Explanation:** "bob " used the keycard 3 times in a one-hour period ( "21:00 ", "21:20 ", "21:30 "). **Constraints:** * `1 <= keyName.length, keyTime.length <= 105` * `keyName.length == keyTime.length` * `keyTime[i]` is in the format **"HH:MM "**. * `[keyName[i], keyTime[i]]` is **unique**. * `1 <= keyName[i].length <= 10` * `keyName[i] contains only lowercase English letters.`
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
Array,Hash Table,Greedy,Sorting,Counting
Medium
null
943
welcome to mazelico challenge this problem is called find the shortest super string given an array of strings words return the smallest string that contains each string in words as a substring if there are multiple valid strings in of the smallest length return any of them okay so you may assume that no string in words is a substring of another string in words so say that we're given these words here this superstring contains every single word in our words list basically what we're trying to figure out is how many of these words can we overlap and save as much space as possible so the order is going to matter and yeah so this problem's pretty simple to understand but the solution is very difficult in fact i think it's the hardest question this year so i'll do my best to try to explain the solution but i still don't quite understand it well so just keep that in mind alright so the first thing we need to figure out or understand is that this can be solved as a graph problem um one thing we could kind of see is every time we want to add another string we want to check to see is how much overlap is there between the source word and the target word that we're trying to add so say that where this is our source word and we are trying to add uh this word here how much like space can we save well if we were just uh looking at the entire word see if there's an overlap say that we looked at our target word or source word and said okay from this end from the very whole string this is the same as this word here and obviously it's not so we can't say four but if we look at this cta we can save three character strings here because all we need to do is just add this end and that's going to contain that first string of six characters in here right so this would be the minimizing path so what we'll do is create some sort of data structure that's going to record the cost from a source index to a target index because that's all that really matters and once we have that then we can make this into a graph problem to solve it out so let's start by creating a lookup we're going to call it cost and i'll start by initializing n to be the length of words so this cost here is going to be representing to us from the index number is going to represent the word that we're at and each one of these is going to have a list of the character that we're the index word that we're trying to add here and we want to calculate how much space can we save so we'll just start with zero because we don't know what they are yet and we'll times this by nine so each one of these are going to be a word that we can add and we'll say four blank and range of n okay so now we have our data structure we want to calculate this out so four i in range of n we want to calculate for every other one for j and range of n as well we're going to calculate to see depending on what the minimum length is we call our example that we just mentioned with these two we're going to take the minimum length between the two and check to see from the starting point of this can is the same as the ending strings of whatever is in here and if it's not we'll just continue on to see okay what is these three equal to these three and so on and so forth and see if we can add it up so what we'll do is have another nested for loop we'll say 4k in range of the minimum between length of words i and length of words j and we're going to move backwards because we want to see what the largest one is okay so if words of i uh let's see minus k onward is equal to words of j uh up to k j here okay if this is true then we want to update our cost to be equal to k so cost of i k our j is going to be equal to k and that will immediately break otherwise if like we can't find one that's true then it's just gonna stay at zero so let's first look at this and see if it makes sense um here with this example there's no overlap at all so you can see like the only times that we can save spaces if we add the same letter to itself because obviously if we add alex to alex we can save four characters because we don't need to add anything at all and later on when we build up this string we could just subtract the however many letters that we're able to save from the beginning and just add whatever's left to that string okay so now we have that cost now this is where it gets difficult um how can we calculate what our minimum string could be um now if we were to do this brute force we could create like a permutations list of all the different paths that we can take to add all the words like you can have uh i don't know like all sorts of different paths that we can take to add every single word and then we can just like um build up the string and calculate the minimum cost and whatever is the minimum cost we can return that string right but that is going to be an exponential time and it's going to reach the time limit so that's not going to work but surely if there's a recursive solution then there's probably a dynamic programming solution right so here's what we're going to do there's two insights here the first thing is using a bit mask and recall that there's only 12 words so what we can do is use a bit mask to represent the state at which we're in right now so see how we had like sort of a mess like this uh each one of these ones represents that fact that we've added this word to the string okay but that's not enough because the order matters right and specifically for this question here it's really more about what character or what word have we just added so have we added just added this one have we just added this one uh and so on and so forth so what we're going to have to do then is create some sort of dynamic programming array dp array and what this will contain is um like the key will be the bitmask representation of our state and we're going to have a list here of every single index um inside of our words so it'll be 12 maximum and this will be contained two things it's going to contain first the length of the string that we've calculated so far okay as well as the string so far that we've that we created and that way at the very end we could just take our bit mask that represents everything added like this and we'll just take whatever the minimum length is for this bit mask here and return the string that represents the minimum length because we'll be calculating it all the way through so um that's definitely hard to understand but i'll do my best here and we'll try to figure out everything okay so first thing we want to do is create our dp array right so the dp array is just going to be a nested list and it's going to contain a list here and we have to have what a tuple right and the first thing length will start with an infinite value so that we could decrease it immediately every time and we'll have what an empty string at first so tuple empty string and we'll multiply this by however many indexes we have now we want to have this oops see here so we have this and then we want to do this inside of a for loop so four blank and range of what uh well we want to have every single state possible right so it's from zer from zero all the way on to all ones so we'll just have to use a uh bitwise here and say one with n being all the representations right there okay so now we have our dp array okay so now the first thing we want to fill our base condition uh so for let's see i in range of n we're going to calculate um everything with like one state here because this we know if we're just adding this first word initially then the minimum cost is just going to be the word that we're adding the length of the word and it's going to be the word itself because we've gone from 0 to adding a word right so we know what that is so we'll just take dp and we'll say i of what i like this and this will equal let's see it will be words i or length of words i and words i okay so let me make sure this also looks good here okay so you can see like when we're adding here four alex five loves and there should be eight lead code right here and it's kind of hard to um know what all these index numbers are right now because these are all like states but that's so be it like let's assume that's correct for now okay so now we need to figure out like update our dp array in order for every single state as well as every single different index number that we're adding at from the state before okay so uh we'll call this four it's called bitmask in a range of i to n okay so what we got here okay so the first thing we want to figure out is from which source to which target are we coming from okay so to do that i'm going to first calculate the different possibilities from which index to which index we're coming from right now so to do this let's see i'm gonna call this bits and we're gonna say for j in range of uh let's see and if we find that in this state this index number exists then we'll add it to this bits so if bitmask will use the and one j if that's true then we'll add it to this bits and now we can calculate what the word that we're adding or the index number anyway and as well as our source i will say forefront and we'll use this air tools permutation to get every single different permutation from the source target and this actually matters because depending on what word we're adding and which word we're coming from uh it could be different the answer could be different so permutations in bits and we'll have two okay so now let's first calculate the candidate like what's the word um that we will end with right now because if it's not smaller than uh some previous value we've calculated then we should just leave it so a candidate is going to be let's see we're going to look at their dp and we'll say um now this one gets really tricky but oh that's right um we're going to use a or symbol here because we want to calculate like when the state didn't have this added character right so what we'll do is say or and we'll take one to add like this and we're going to take the ad here oh no that's not the ad it's the source as well as take the second character which is going to be a string and we're going to add the second element so this will be whatever path string that we calculate so far without having added this word and we'll take see we're going to add this so say words add and we are going to take from our cost function however many words we can save onward right so cost and we'll take uh from target to source onwards so whatever we can save onwards we'll add that to our candidates and now we're going to try to update our dp so dp is going to be let's see the bit mask the index number we're trying to add we'll take the minimum between mask and add and our tuple of candidates length of the candidates as well as the candidate itself okay finally uh at the very end we should have the very last number here dp will contain like um a bunch of candidates with the different index numbers added last and we want to take the minimum between these right so we'll take the minimum of this and we'll just take the second element inside of that so okay so let's see if this works i'm sure i missed something up here so yep target there's no targets should we add okay so i don't know if this worked but whatever yolo let's see if this works uh okay so i messed something up here a little length of these look the same of course i'm adding the cost maybe yeah i might have to switch that around should be the source to add let's see all right yeah so i think that's what the problem was let's go ahead and try that again yep there we go accepted oh so are you confused i mean me too like what the hell this is not a reasonable interview question um and even after looking at the solution i'm still confused i'm still very confused about this but hopefully this kind of helps you kind of get there i may have made some mistakes in what i was explaining um but yeah time complexity wise it's going to be exponential for sure because of this permutations it's going to be 2 to the nth power as well as n squared because of all these nested for loops so it's still better than doing the brute force method but you know if i was just trying to solve this on the spot maybe the brute force method like would be acceptable i don't know um but yeah all right so i definitely recommend looking more into this uh specifically this traveling salesman problem could help but these bit mask situations are really confusing and something that i don't fully understand myself so sorry i can't be more help i hope this helps there are definitely more places that you can look for uh resources so thanks for watching my channel remember do not trust me i know nothing
Find the Shortest Superstring
sum-of-subarray-minimums
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Array,Dynamic Programming,Stack,Monotonic Stack
Medium
2227
149
good evening everyone today we are going to do the problem of the day for 8 January 2023 that is question number 149 maximum points on a line they are saying that we are given an array of points we have a array of some points where points indicates the x coordinate and y coordinate on a x y plane and we have to return the maximum number of points that lie on the same straight line so here they are asking you to find the number of points that live on a same straight line means that they are having a same slope so let me draw it for you if I draw it for you this is a straight line okay and if I see that this point what will it be X1 y1 see and here it will be X2 Y2 so these two points are on the same line okay that means their slope is same and CM goes for a third Point here that will be X3 Y3 so they are all having the same slope so if I write the formula for you let us consider X1 y1 as the first point x 2 Y 2 as the second one and X3 Y3 as the third point so for that slope formula is y d y by D X you can say that is tan Theta uh tan Theta and it is equal to Y2 minus y 1 divided by x 2 minus X1 okay so now for here if I have to find the slope of between these two points and these two points I can write it as Y2 minus y1 divided by x 2 minus X1 is equal to y 3 minus y1 divided by x 3 minus X1 that will be our slope and if these two points are equal the slopes are equal then we can say the points lie on the same line so that is the case here but there is also another case that the parallel lines also have same slopes if there is a parallel line it would also have the same slope yes or no the angle is same but the point here what we will do in the approach first approach will be the very basic diet we will find a that will be of O and Cube complexity that we will check with every point the slope between these two points and we will check whether they are same or not and we will have a counter but that would be a very Nave approach and the interview will ask you to optimize it so there will be a n Square approach what we can do um uh let me tell you the first thing that there always exists a one point passing through the line and if there are two points they will also be passing through the same line and the case is changing after the third Point okay so that is our situation here so what we are going to use unorder maps so in the map what we are going to do let me show you the code and explain you the exact points what is happening here now so what we can do the constraints given are the maximum limits is 10 to the power 4. so slope can be all slope can also come out to be 1 by 0 in some cases that is infinity and we cannot Define Infinity to our compiler ion code so we are using the out of limit bound or you can use intermax as well so here our index is one zero one maximum number countries are just count variable which will count uh how many points are there on a straight line the maximum one okay and now what we are going to use for enter is equal to zero we are creating a loop that will uh we are creating a loop till the last point and then we are creating a map for every slope we have to create a map so what we are doing here is we are storing on a map that here will be our slope and it's going to be like this slope and count we are storing it and hence the for as the formula is in divide the slope can also be in double okay it can also be in point so we are using the double data type so now we are iterating from first Loop till the last and the second point is coming out to be I plus 1 yes or no and we are iterating that and the what is the worst condition we are having that is when denominator is zero that is your X2 minus X1 or X3 minus x 1 is 0. so we are dealing with that condition here that if the points are seen that is X2 and x 1 are same or X3 or X1 are same then it comes it goes to Infinity slope will be Infinity so we are uh create uh we are initializing it in the map as outer bound and if it is not the case then we can have the slope we are getting the slope we are storing the slope in our map and we are having a counter for it as well and now when finally we are done with that we are checking what's the maximum value count is maximum or X second Plus One X second one plus mean that the second point in the map we showed you now discount and Y plus when you ask because the counting starts from 0 but we have to and if you are counting the points we will start from one two three four not zero one two three so that's a second X plus one so that is our overall approach so if I have to summarize it I will say if I have to find this points on the line I will say that if the slopes are equal then the points lie on the same line and I have to calculate the number of points that is our approach and we calculate that by using unordered Maps okay and for the parallel line question what is happening if you found the flow between these point the angle is changing so that will be a different slope value and it hence it is not interfering with or the counter value okay so that is how we are getting the number of points lying on the same line let me just run the code for you and check whether it is working or not uh case one is passed case 2 is fast let me submit it again and yes it is working so the time complexity for this question will be o n Square which I have shown you the solution and the space complexity you can comment down in the comment section if you want me to solve another question you can drop a comment on it and please like and share the video And subscribe to get more updates on lead code questions thank you for watching bye
Max Points on a Line
max-points-on-a-line
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\] **Output:** 4 **Constraints:** * `1 <= points.length <= 300` * `points[i].length == 2` * `-104 <= xi, yi <= 104` * All the `points` are **unique**.
null
Array,Hash Table,Math,Geometry
Hard
356,2287
237
hello everyone welcome back to lead coding the question which we are going to solve today is delete node in a linked list the problem description is write a function to delete a node in a singly linked list you will not be given access to the head of the list instead you will be given access to the node which is to be deleted it is guaranteed that the node to be deleted is not the tail node in the list so first of all before jumping into the solution let us look at the structure of the node there are two data members the first one is an integer which contains the value of the node the other one is a pointer of the type list node it contains the address of the node which is just next to it and then there is a constructor which is going to initialize the value with the given x and the pointer as null this is the initialization list so the structure of a particular node is something like this there's an integer value and there is a pointer so this is the format in which we have our linked list this denotes a particular node in the linked list and this pointer points to the address of the node which is next to it and similarly this is going to point to another node so this is how the structure of the linked list is now let us denote these nodes using circles so let us say this is our head and we are not given access to the head node and let us say we want to delete this node from the given linked list we are given access directly to this one now okay let us say that for more clearity we have one more node over here and this is pointing to null all right so if you want to delete this node then what we can do is we can directly connect the node which is previous to this node and change the pointer of this to next of the node which you want to delete so this way the node you want to delete gets eliminated from the linked list and we can store it inside a temporary variable and simply use the delete function to clear the memory but in this case we are not given access to the node which is previous to the node which you want to delete so this is not going to work but what instead we can do is let us say they have the value 1 2 3 four and five and we are asked to delete the node which contains the value three now what we can do is as we have access to this particular node we can swap the value of this to the next of this as we have access to the node number three we will be having access to node number four and five as well and uh whatever is previous to three we will not be having access to those nodes so we are on three and the next of three is four so we have access to four as well we can swap the values so four will come here three will go there and now as we have access to 4 and we want to delete 3 we can do the attachment as this and we can store this inside a temporary variable before attaching 4 with 5 and we can simply clear off the memory so let us try to see the same using the code this node denotes the address of the node which you want to delete so let us first swap the values i'm using the swap function nodes value with the value of next node and now we want to store into temp nodes next now we can change the connections how we are going to do this so to do that we just have to do nodes next is equal to nodes next and then delete temp to clear the memory let us try to run this notes next is equal to nodes next and the spelling is wrong it is giving us correct answer let us try to submit this and it works so in terms of space complexity as we have just used uh two variables to uh one in the swap function and another one the temporary variable which you want to delete so this is basically a constant space solution in terms of time we are just doing a swap which is a constant time operation and then we are just changing the connections and then delete so these are all constant time operations and the time complexity will be big often as well so this is it for the solution if you like the video please subscribe to the channel thank you
Delete Node in a Linked List
delete-node-in-a-linked-list
There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: * The value of the given node should not exist in the linked list. * The number of nodes in the linked list should decrease by one. * All the values before `node` should be in the same order. * All the values after `node` should be in the same order. **Custom testing:** * For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. * We will build the linked list and pass the node to your function. * The output will be the entire list after calling your function. **Example 1:** **Input:** head = \[4,5,1,9\], node = 5 **Output:** \[4,1,9\] **Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. **Example 2:** **Input:** head = \[4,5,1,9\], node = 1 **Output:** \[4,5,9\] **Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. **Constraints:** * The number of the nodes in the given list is in the range `[2, 1000]`. * `-1000 <= Node.val <= 1000` * The value of each node in the list is **unique**. * The `node` to be deleted is **in the list** and is **not a tail** node.
null
Linked List
Easy
203
875
hey everybody this is larry this is day 20 of the lego daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom actually that's funny because i was just looking at this problem because i've been working on a on um on a binary search uh video um so this one i think maybe to be honest i might keep it a little bit short just because i might um end up using this problem anyway um so i actually do know how to solve this as a result um because it wasn't it's really commercial dental but um but yeah uh i do have one minor big news which is that i have a new keyboard so if it's a little bit cracky crack let me know how loud it is if it's or whatever but yeah but for this problem um yeah i mean i'm not gonna go over it too much to be honest um because i'm gonna have a video coming hopefully soon to kind of just go over how i sell binary search forms because i solve every binary search form more or less the same um and i feel like there are some details that like you know i'm recording these live and these are kind of like almost like a daily relog type thing of me solving these problems um and one thing that i always find a little bit hard to do to be honest as part of these videos is to kind of figure out like you know the balance between going really deeply into a problem or you know um or not as much right but because at this point i probably have like literally a hundred videos on binary search and it is like i ask myself what is the um what is the returns on me explaining the same binary search for example as an example um every video like as in depth as possible right like i'm okay with being in depth but at a certain point i'm just doing the same thing and you know maybe i could do a special video on this instead and these are kind of things that i've been thinking about so this one um this video may be a little bit shorter and maybe not as detailed but the ideas that will still be here and we'll figure it out um let me know what you think in the comments about my keyboard my binary search way concern dental uh problem uh and stuff like that so yeah um cool let's get started so yeah um actually i don't i remember looking this up or looking this problem but i actually don't remember the details so it'll still be live a little bit um but yeah and maybe this is actually a good um warming or not warming up a preparation for that video but yeah so coco loves bananas as we all like bananas uh the end piles the i power has powers you guys have gone and come back can decide you challenge somebody else and you came if that one doesn't use all of that instead without you anymore this hour okay um so yeah so one thing the first thing to notice for this problem is that um maybe i won't use this one for the video just because it's a little awkward to kind of be so close about it but the first observation about this problem is that it doesn't matter which order um the order you need to pause in right so you have something like this and then um let's say you can you oh you have to find k okay but let's just say you have given uh you're trying to find well you're trying to say four at a time right um it doesn't matter whether you get to three and uh from it doesn't matter where you eat from the three first and then to six twice and then the seven twice and then eleven three times right um because the order doesn't matter it only matters is that in total it sorry still adjusting to the keyboard locations of stuff i'm so used to my old keyboard you've stood for like let's say almost 10 years so yeah so now you have one day two days and three days right and this of course sums to eight days um and it doesn't matter whether you know you interlock or what or whatever um and you could kind of prove to yourself that this is the case um this will take eight days right so here um one thing that i would like to do is to write a function of okay let's say we have the answer can we figure out a way to see how um whether um we can finish in h days right and you know there's given different ways naming it but uh yeah so then the first thing i would say is let's say we have some target um i probably will explain this better in the binary search video not to spoil that a little bit but yeah um but let's say we have some target that we're trying to target and i do use this okay i don't want to be too sloppy on this one i do want to do a technique called binary search on the answer um and basically the answer can be any number from from let's see right let's think figure that out the answer in this case can be this 10 to the fourth of each power can be 10 to the ninth um so that means that uh the number of total piles um yeah the number of total piles will be 10 to the 13th right so that means that okay so that means that the answer can be from that is it zero or one of those two say for now it doesn't matter as much 0 to 10 to the 13. um so then here we know that our sketch of an algorithm this is going let's say we have this magic function which we will implement and it's going to take a loop through that away every time then this is going to be o of n times log of the universe is what i call it which is the size of this thing right which is of course roughly speaking um i don't know like oh well it's a log of you in this case even for 2 to the 64 is just 64. right so let's just say i'm lazy right now in the math um and so then this is just going to be roughly speaking o of n times 64 and of course n is 10 to the four so this is the math for me to kind of figure out 10 times uh 10 to the six ten to the fourth times 64. so this is roughly an estimate for me to figure out whether i need to uh um whether this is going to run in time right okay so now that we have that um you know we do a feasibility study and then we go okay let's say we are given a target what is the um you know how you know and you can implement this in any way but the way that i would implement this function um and i always label it good maybe it's not a good name for it per se but uh maybe you could count or like you know is getting speed enough right let's say this is let's say we're given this target speed and is this speed enough and so then now we just count the number of days where days is zero for x in piles uh days we added which is of course equal to well x divided by the speed that we're eating it and then we want to round up and of course in rounding up in um in discrete is this is how i would do it for rounding up in the screen and then oops and i'm still not using this new keyboard they're like page up buttons and a weird price maybe i need a different keyboard but yeah um and then now this is enough if the number of days that it takes to eat this is smaller grade or less than h right so okay so now we have this and this is the function that we have right um i think maybe i want to give this a try where i explain this backwards right where okay now we implement this function now instead of kind of asking um the first true the first or the last true or whatever i have this function that i know i want to binary search on so then the question is what am i looking for right am i looking for and i actually don't use these terms because i don't think of it this way per se but i think that's what a lot of people do right so then i go okay um let me take a look at this property of this function which is that okay let's say speed is equal to one what does that mean well if speed is equal to one then this will be a lot of days so it's not gonna it's probably gonna start off force and then as you kind of increase the speed days goes down right so that means that uh analyzing this function um as days goes from a big number to smaller this is going to be we eventually it's just going to be first resolution first and then it becomes small enough to be true right so this is the function that we're given um and this is just analyzing this function that we wrote um and of course there are a lot of ways to kind of represent this in um in the negative way which we'll talk about in a sec but let's say that we went this function like this because that's the for me the most intuitive way to write it for you may write it differently right maybe you're right is this is the using speed too slow for example it may look the same and then you would maybe have a different um operator here or something like that right but here so now we're given this function right and what do we want from this ends uh the question so we read it again maybe or maybe you already know it without reading it again run the minimum case such that can eat all the bananas in h hours that means that we want the minimum thing where this is true because the speed and now this if the speed is good enough then we do eat all the bananas so that means that we want the first true say right so we're trying to find oops so we're trying to find this position right so um yeah maybe that's good enough for now uh for you know find this right so that's basically our goal and of course like i said you can use the vocabulary of this is first truth i don't really think of it this way per se and you'll see why in a second um so then now we declare our ranges um one thing that i sometimes is a little bit sloppy about is about the ranges um about the lower bound and upper bound uh it's very intuitive to oops uh do something like you know let's just say this but depending on the way you write it is critical to have um and maybe the way that i would like to write it anyway is to at least have one force in the range and one true in the range so that things can be um resolved a little bit easier right um and what i mean by this is that let's say you have a equivalent function where you know running it for all your range if you get ch to choo um in a weird way you don't know that this is the first truth because in theory maybe if you started too late um there were more choosing to the left right um so that's why i don't like doing it this way or that's why i want to make sure that there is a force so that you know and sometimes that will take us out of balance maybe it will take us to negative one or something i don't know if that's the k well in this case i don't think that makes sense because um if you have a heating speed of zero this would go outbound so actually we won at least one um and then maybe we have to take care of it a little bit but ideally this is what i would like to do and of course the other case is true as well right if we have all fours how do we know that you know this value is going to be true we don't right so that's why i want to make sure at least one force and one true is in the bound so that we can guarantee ourselves that's where i make the most mistakes to be honest um and here um yeah so left is equal to one means that we're almost guaranteed to have a force except for if h is like really big i guess um so in this case actually we're really um yeah in this case i guess we're actually um a little bit sketchy on this part you can maybe have a edge case of okay let's start at zero uh if our speeding z speed is zero then you could say maybe if theta is equal to zero we have some infinity value which will just have like i don't know something really big right um so that oh uh and this is less than h of course um which means that uh i'm actually pretty okay with the home keys on this new keyboard but they're like arrow keys and stuff like that i still have to get used to because it's a little bit different layout um but yeah uh and of course this ideally should be four so we just return force so that basically saves us time here to kind of figure it out so we always have a force in the beginning and given a fast enough speed this is always going to be true so i think maybe this should be good enough but maybe we can add like a small number or something right um because that's the most number of things here or something like that um okay so then now we um this is a thing where you know you see some people as you know this or some or something like this um the difference is that one of them is in exclusive brown and the others inclusive bound um i'm not going to go over the rice and house because i'm going to save that for that video um it's going to be a longer video and it will have a lot of details hopefully but um but yeah but uh but this is an inclusive bound which leads to a couple of meaning right um because this is an inclusive bound that means that this is our range which means that every number inclusive of the left number and the right numbers out range that means that this becomes false when left is it goes to right we terminate right terminate when this happens so we terminate when this happens so that means that the answer is going to be left right um because when we terminate when it happens um we terminate when this happens which is another way of saying now left right me implies left is equal to left which means that there is only one number in the range our correct answer so that's why i write it this way right um and then here we just have mid as you go to left plus right over two um at least that's why how i write it to begin with um we'll go over some nuances you know in the future but this is just the midpoint of these two um we in this case we round down because it is discrete and yeah um and to facilitate so that now we go oops if good of mid um and then now we this is the part where we kind of figure out how to answer this right so let's say we have this thingy and the only two scenarios right one is okay let's say if this is mid is here right let's say this is mid if mid is here if this is okay actually i wrote it like this first so it doesn't really matter but let's say mid is here then because this is you know this is true what happens if this is true then mid is a possible answer right if true mid is a okay actually let me write it here instead right uh mid is a possible answer um to our solution so we don't want to eliminate it so we want to keep this in the range um and also the other thing is that okay if mid is good what does that mean that means that everything to the right of the mid is also going to be good as we kind of have this diagram um everything to the right of the mid uh or higher than mid bigger than mid is also good so but in this case of course we want to get the first true in this case right we're looking for this so that means that everything to the right of this thing cannot be first true by definition because the current value is already the first true or it's not the first truth but it is already by definition this is a possible first true that means that everything to the right of it is not for is true so that means that we want to move the range um you know from here and here to here so here all we have to do is do right is equal to mid right um and then else what happens um yeah that means that right is inclusive still it write is still a possible answer that's right is equal to mid and then now we move to left in that case in theory um okay because we basically chop off everything to the right of mid um okay and then now the other thing is okay what if mid is false right if mid is force then one thing right well two things mid is not a possible answer and also um everything to the um well just a little bit awkwardly the page up key is too close to my backspace key yeah and then now every so now every eye smaller than mid is also uh not good right so now mid is no good and everything smaller than mid is no good so we want to move left which of course used to be here say um we'll move left okay let's actually maybe i'll draw it here instead oops so let's say this is left right now we want to move it to here because we know that everything to the left is not a good answer and of course mid is also not a good answer so then that left is equal to mid plus one so that's basically the idea behind this and that's pretty much it we run the code oh did i not define oh i change i usually use the function name good but i forgot that changes for this case uh cool so this looks good that's one of the different cases um and that's pretty much it i mean we did the complexity at the beginning so i'm not gonna go over it again um but yeah but this is a good warm up to my binary search video i suppose i actually haven't solved this before huh i it feels very familiar to another problem that i solved or many other ones so i don't know but yeah but it turns out i haven't solved this before so it's a good idea but yeah um that's pretty much it for this one um so yeah that's basically all i have um let me know what you think you could hit the like button hit the subscribe button join me on discord leave me a comment in the comments if you really want to see a binary search video i think i'm going to end up doing it but you know you never know so you know put some likes if you really want that to happen uh yeah that's all i have with this one stay good stay healthy to good mental health i'll see you later bye
Koko Eating Bananas
longest-mountain-in-array
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_. **Example 1:** **Input:** piles = \[3,6,7,11\], h = 8 **Output:** 4 **Example 2:** **Input:** piles = \[30,11,23,4,20\], h = 5 **Output:** 30 **Example 3:** **Input:** piles = \[30,11,23,4,20\], h = 6 **Output:** 23 **Constraints:** * `1 <= piles.length <= 104` * `piles.length <= h <= 109` * `1 <= piles[i] <= 109`
null
Array,Two Pointers,Dynamic Programming,Enumeration
Medium
1766,2205
121
okay it's the best time to buy and sell stock elite code question one two one so you're given an array of prices where price i is the price of a given stock on life day you want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock return the maximum profit you can achieve from this transaction if you cannot achieve any profit return zero what we need to do is we need to return max profit when anything concerns max profit or an optimal what we usually go for is dynamic programming so in this example what we need to do is we need to find the smallest value so in this case it's one and then just determine where the next largest value is in this case we can easily see that it's six and then we just return that profit which is five the difficulty comes in when trying to program that out so the best way to look at it is if you draw it out okay so here's the graph and what i've done is i've plotted each point so we have seven one five three six and four and the points that we really need to take into consideration is this point and this point so we need to assign a variable to this point let's just call it current min and then with this let's just call it current max right so with this problem what we can do is we can kind of set current men to this value here so to the first price in the array so that will equal seven and then current max we can set to zero because what we're going to end up doing is we're going to end up returning this and remember as it said in the question if you cannot achieve any profit you need to return zero so starting off at zero is great because it covers that and then what we'll do is we'll loop through the prices right so we'll look through the prices and we'll update the current min and the current max so at this point the current min is seven current max at initial position is going to stay zero right so then we move on to the next one current min is currently seven what we'll do is we'll change that to one because one is definitely smaller than seven and with current max what we can do leave that at zero because we haven't got anything to compare it to yet because this is the new current min so we move along to five now current minimum is still one so this is where the interesting part is in order to get the current max here is we take this point take the price at this point and we minus the current min so it's going to be five minus one and then we do this consecutively throughout so three is going to give us two so what we need to do is we need to work out the maximum current max is going to be equal to math dot max current max and the current value we're on minus the minimum so it would be prices at i minus min or current min sorry and that'll be the comparison there so this is the dynamic approach here so we're always using previous values in order to computate the current max so then we'll move along we'll go to six and we'll subtract one from that and that becomes the new max because the current max is four six minus one is five is greater than four so five goes there move along four minus one is three so that doesn't matter and then we just return this value and that is the answer we're looking for so let's jump into the code and see how it's implemented okay so we need to set the variables for the current min and current max so current min is equal to prices at zero so the first value of prices so we can start the comparison and then the current max is set to zero and the reason for this is because the question asks us that if we don't find a maximum profit return zero and at the end we're going to be returning current max so that covers us there with the for loop we go to the last value and then within the for loop we are just going to be updating current in and current max so current min is the minimum between prices at i and current min and then current max is going to be the maximum between current max and prices are i minus current minimum now in terms of time and space complexity we've only got one loop or one pass over this entire array so that's going to be o of n and space complexity is going to be one constant space because we aren't allocating any extra space and that should hopefully run okay so let's pass let's submit it and there you go
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock. Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 5 **Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. **Example 2:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transactions are done and the max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming
Easy
53,122,123,188,309,2138,2144
486
Hello gas, how are you all and today we are going to solve 486, so while discussing this question, it has been said in this question, who will have higher number in the last, we have to find out, if there are chances, then if the number of player one is either It's time to happen, so we have to return true, or Jal, once it is written in the question, either that name is Length - 1, this is right, most Erickson, light, Length - 1, this is right, most Erickson, light, Length - 1, this is right, most Erickson, light, most element, like most. Whoever is going to choose, he will give his score. Me jod laga last mein di game aur when dewar is no more element in dewar hai jab sare element player one Yadav player tu le liya hoga That usam tha playing optimumlay meaning apna it means ultra in the game and we can speak That both are playing correctly means both are right and that no one is taking a wrong step, that both of them are at the same level as both of them and whether he can win in that or not, it remains to be seen whether player one can win. No, if player one can win then we have to return true otherwise we have to burn it so with this example the player here who is player one is going to take the first turn if it is a game then it will be player one's turn first so player one will either This one can choose what am I doing here 3 you and one player one is going to have first turn so if it is left right left what will happen and in the last 1002 will be left then what will player one do with 1002 take 100 and player one You thought, you have to do a hundred. Well, we could have said that we will win all the time only by taking more numbers. Left is happening. For this, we have to see the whole game. So let's see this one. What is the left most here? You can also take the right most. If we can, then two will come in it, how can two, then this will happen here, if we say that its value will be one, the value of player one will be in this, what else will be left is five and you, and if player one is taking the plate from here too, then the player is still the child. What is happening, how do we solve it, what is the approach going to be, this is also such a question of game type in which there is less meaning of whether someone can win in the game or not, then this type of question is It is called game stratification. This is a game strategy question. To solve it, we have to keep two things in mind: solve it, we have to keep two things in mind: solve it, we have to keep two things in mind: when it is player one's turn, it means that we have to take max when player two's option is required, like above, if we are here. But how can I get the second one, here it is 52, what did we do, maximum good one, cash was taken, fiber, you are a player, you are five, why is it so much, what does it mean, what does flair Gan have, you came, minimum is right, when the player You will have less turn, when it is your turn, the player will come to us. Hey kid, what will he do from i plus one to s minus one and if he is taking i, then if he is taking i then he is going to save here so here We have to consider the minimum that will be left from I, what did we do in this and what happened here I + 1, so here player one was getting profit in this way. There should be a loss, yes, which option can be correct, whether we will take player one's left or right and make plus, if we are with him, then there were so many approaches and this game is a strategy question, in every question, the same thing is asked in every question. Simply now, if we say no then what will we do in general, we will take I and jet, we will take I, we will take its yes and we will plus the rectangle with it, which means that if we are taking I, then how will we make it? How will we make it and after that we will check the minimum that yes, this is the minimum, how are we doing this, how will we make this different minimum, how will we make the minimum in this one, we will plus it with the rectangle, the minimum which is A, it will be added to the jet. We will do plus and this will be the max of what happened between these two, this will be the max here we will find that here, so what we have to do now is that I is the minimum, which is the minimum which will go from I + 2 to K minimum, which is the minimum which will go from I + 2 to K minimum, which is the minimum which will go from I + 2 to K and I + 1. From J - 1, and I + 1. From J - 1, and I + 1. From J - 1, we will plus the value of the lake in which the minimum will come with I and the maximum value that will come from it will be the score of p1, so this will be p1. How to get the score of p2? What will you do with the score of p1? To return the advice, I urge you all to watch the code from the beginning, if you understand it then try the code once yourself, if even after that it is not working, then I have put a video for the code for you further and can play it on this page. So I hope that all of you have tried to code once and if it is not possible then it does not matter, we who code here do it, so as we saw in Across, What do we have to do? The first index will be taken, the last index will be taken once, what can happen to the minimum count p1, we have to find out the possible answer of p1, what will we do by adding it and adding it once. We will see what is the value of A and whatever will be the maximum between them, we will store it in it, that will be the score of p1, if we know then what will we do, we will find the score of p2, yes, PON will be bigger, minus one, okay do. So this is the code, but what do we have now, what do we do now, if we create a function for p1 score, then for this we create these p one and we will take I here and see once Jai, we will plus it, so that's why mean here. Off p one's score is tax score will be name will be Jai and after this here there will be mean something what is going on here is to return i take score and will be which will be aids its will be got will be stored after that What will we do with p2, we will make it equal to p1 and we will check whether p one is greater than A or equal to A, if it is A then well and good return true, will it be true or not, okay what? If there is a mistake, then this was this question and it was said that yes, this is a joke question like the player given and who among these is going to win, in this question, put this question with a blindfold and this approach, okay so for today. If everyone has understood then see you in the next list code question, till then bye.
Predict the Winner
predict-the-winner
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` or `nums[nums.length - 1]`) which reduces the size of the array by `1`. The player adds the chosen number to their score. The game ends when there are no more elements in the array. Return `true` if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return `true`. You may assume that both players are playing optimally. **Example 1:** **Input:** nums = \[1,5,2\] **Output:** false **Explanation:** Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return false. **Example 2:** **Input:** nums = \[1,5,233,7\] **Output:** true **Explanation:** Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win. **Constraints:** * `1 <= nums.length <= 20` * `0 <= nums[i] <= 107`
null
Array,Math,Dynamic Programming,Recursion,Game Theory
Medium
464
228
welcome back for another video we are going to do another vehicle question the question is 22a summary ranges you are given a salty unique integer array nonce a range ap is set of own integers from a to b inclusive we don't smell this sorted list of ranges that cover all numbers in array exactly that is each element of nouns is covered by exactly one of ranges and there is no integer x such that x is in one of ranges but not in nouns each range a b in this should be output as a to b if a is not equal to b a if a equal to b for example one nouns is 2 1 2 4 5 7 the output is g two four two five seven the ranges are g two becomes zero to 2 4 5 becomes 4 to 5 7 becomes 7 for example 2 nouns is 0 2 3 4 6 8 9 the output is 0 2 4 6 8 2 9 the ranges are 2 0 becomes 0 2 4 becomes 2 4 6 becomes 6 a nine because a two nine four constraints all the values of nouns are unique nouns is sorted in ascending order now let's work through the code arrange covers consecutive elements if two adjacent elements have difference larger than one they do not belong to sand range the array is sorted out without duplicates therefore two adjacent elements have difference either one or larger than one if the difference is one they are in the same range else they are separate range we use two indices for each element we check if it extends the column range if not we put a wrench into the list we also need to put less branch into the list time capacity is o n space capacity is 0 1. and the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching
Summary Ranges
summary-ranges
You are given a **sorted unique** integer array `nums`. A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive). Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`. Each range `[a,b]` in the list should be output as: * `"a->b "` if `a != b` * `"a "` if `a == b` **Example 1:** **Input:** nums = \[0,1,2,4,5,7\] **Output:** \[ "0->2 ", "4->5 ", "7 "\] **Explanation:** The ranges are: \[0,2\] --> "0->2 " \[4,5\] --> "4->5 " \[7,7\] --> "7 " **Example 2:** **Input:** nums = \[0,2,3,4,6,8,9\] **Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\] **Explanation:** The ranges are: \[0,0\] --> "0 " \[2,4\] --> "2->4 " \[6,6\] --> "6 " \[8,9\] --> "8->9 " **Constraints:** * `0 <= nums.length <= 20` * `-231 <= nums[i] <= 231 - 1` * All the values of `nums` are **unique**. * `nums` is sorted in ascending order.
null
Array
Easy
163,352
141
Hello everyone welcome tu my channel it is very popular solution bhi patna hota slogan fast point based question hai linked list cycle tu theek hai liquid mein 142 medium level questions and everyone knows slow internet fast point wala This is the approach that was taught in college too, to detect cycles, so it is not me but the company, it is okay, I have not written all of them, you will get all the companies in the description, either go to my getup profile and click on this question. You will get the names of all the companies. Okay, so let's see the input output of the question and understand what the question is. It is a very simple question that we have given you a link. We have to detect whether there is a bicycle in Linkluf or not. If there is no bicycle then tap. Return it. If there is a bicycle then you have to tell where it is. Neither did the bicycle come here nor the bicycle. Look, you are on the starting point of the bicycle. You have to find out from here if there is a bicycle then where it is. Okay, you also know. No, I will try to tell you how it happens, but what is more important than that, why does brother do it less, why is it the method, which I will tell you now, it is more important then you will understand the process, okay then let's start, if it is slow then also. Understand the Good Force, it will be very simple that you stand here at this point, take it as 'Mother', 'It's okay', name it 'P', take it as 'Mother', 'It's okay', name it 'P', take it as 'Mother', 'It's okay', name it 'P', okay, so first you check whether I have ever seen 'Three' nearby. whether I have ever seen 'Three' nearby. whether I have ever seen 'Three' nearby. I will make a map. Okay, if there is a map then I will make a set. I have made a set in which I am not putting a note or link. Okay, so here I have never seen three nearby, meaning it has not been repeated, so let's three. You put 'O' and then so let's three. You put 'O' and then so let's three. You put 'O' and then moved the pointer forward. 'Have I moved the pointer forward. 'Have I moved the pointer forward. 'Have I ever seen you before, no? Look, you are not in the set, otherwise you are there. Then you moved 'P'. Have I ever seen 'Zero'? Have I ever moved 'P'. Have I ever seen 'Zero'? Have I ever moved 'P'. Have I ever seen 'Zero'? Have I ever seen 'Zero'? So also zero. seen 'Zero'? So also zero. seen 'Zero'? So also zero. Okay, after that, A went here, Okay, so have I ever seen -4, I have went here, Okay, so have I ever seen -4, I have went here, Okay, so have I ever seen -4, I have n't seen, so let's put it here, Okay, after P, the next step will go, so back here A, Have I ever seen you? Look, yes, I have already seen you, that is, I have got the cycle, it is okay, there is a cycle, so on whom is the cycle, this is the cycle above, the cycle is starting from here, so I will simply note the return of this one, that's it. And if there was no cycle, then it is obvious that our linked list would have looked like this - you would have linked list would have looked like this - you would have linked list would have looked like this - you would have been zero-4, after that there would have been a tap, otherwise he would have been zero-4, after that there would have been a tap, otherwise he would have been zero-4, after that there would have been a tap, otherwise he would have said that brother, cycle is enough but barf force, you write it, do n't miss it friend, practice it. Practice never goes waste. Practice as much as you can. Write the route four by yourself and check it on the approach. Then you will remember what happens in the technique of slow and fast points. The slow one is also the head. It is there in the starting point and the fast pointer is also in the head, okay, this is called toys on hair, in which what is slow, it will move one point once, the fast one will move it twice, okay, so see. Let's start it, here it is slow, here it is fast, now both are pointing to the head, slow has moved once, okay, fast will move it twice, it came here once, then it will come here, okay, so let me remove it here, then let's start it. If slow will move only once then slow came here and what will happen fast will come here then come here ok why came here because why is there on you near mines four because there was a cycle here and here the pointer is pointing next. Okay, again slow will come here and will move ahead but the fast one will move twice, so see where will fast come to zero and then come here, okay and pay attention to one thing, what happened here is that fast and slow are at one place. After coming and meeting, it is okay, both of them came and met at one place, it means it is a cycle, okay it is a cycle, then it is okay, we have come to know that it is a cycle, the cycle has been detected and when the cycle has been detected, as long as when slow is equal to fast. It has become equal to fast, so it is known that means it is known that brother, it is a bicycle, that is why what happened is that the password has been changed to one place, it goes round and round, but sometimes There is a reason behind why we will never meet, if there is a bicycle then why will we always meet, okay but I will make that in a separate video in which I will explain to you that if there is a bicycle in the link list and we are slow. And if we do fast points, then why will fast and slow always meet at one place, okay, so that is a different concept, okay, I will make it in a separate video, if you want to know, then okay, slower, fast, met at one place. It means that the bicycle must have been there somewhere. Okay, this thing is clear. Now we have to find out where the bicycle must have been. Mother, the question is the same. If the bicycle is found then it is good. But where is the bicycle? So you have to find it, are you okay and if mother takes fast which is while walking and if it comes to the tap then it means it is not a bicycle, I will simply check that if my fast which is equal to the tap, then brother I will return the tap but this has not happened here if fast is equal to slow, then I will break my for loop and now what will I do to find out where the bicycle is, so tell me what for this. I will do it, I will take one more point for this, okay, I will take one more read for this, I name it, if you name the entry point, then keep it anything, I will give P, I have collected P, after this I don't know what to do, after this P Increase A. From here to here, slow from here to here, A will go. Okay, now see where P and S will be found. Wherever P and S will be found, that will be my starting point of the cycle, so quietly I will return P. Return P. I will give it to P or I am opening both of them. I will return it to P. Okay, so let me tell you again what I did. As soon as I made the match, I came to know that brother, the bicycle has been found. Okay. Now what will I do, I will leave the S here and take a new point which I will start from the head. This is the head, right? I will start from the head and will increase each of them by one. Remember, I will increase one each but it is equal here, that is. Cycle is the starting point of the cycle. Okay, so what happens is that this will be my starting point where P and S meet. Okay, so this is the code. So, write it quickly. I have understood the dog story. But. The idea behind the story should be that why P and S are matching, I am saying that brother, that is the starting point, okay, proof is needed for that too, so brother, this is the most important question which will be asked from you in the interview. Don't go at night. There are slow and fast points. Go keeping the Intion in mind. So let's see what is the intuition behind it. Why P and S. Where I matched will be my starting point. Okay, so let's understand this. To understand the Intion, I have seen this. If you have taken this example, then first of all do what I taught you, slow starts from here, fast starts from here, slow one will go, it will go here, fast two will go, one will go here, okay then slow one will do. A will go here, it's okay, if two fast ones will do, A will go here, okay then A will go here, then the slow one will go here, let me do a race and if two fast ones will do, then fast will also come here, so what have I done if I match? Told that if both of them come to one place then it means that the cycle will definitely happen. Now we know that we have to find out from where both the cycles started. Before that what I had said was that the pointer named P will start from here from the head and slow down. And we will move P one by one. Okay, so if P is moved one, then P is here. If Slow is moved one, then Slow is here. If P is moved here, then Slope is here. If one is moved, then this is here. I went to the same place where I have met, that is my starting point, this is correct, this is the starting point, so my answer will be three, till now it is clear, but I have to explain why this thing is reducing me, okay, then you like this. So remember, this one was my meeting point, this red one, this was my meeting point, this is where the slow and fast font is, I meet the mother, this distance is the album, it is okay and this cycle is this cycle's. Which is the starting point, from here, both of them meet at L2 distance, if both of them meet, then the slow one, which is slow, at what distance is the mobile van plus L2 and this speed is running, is it slow or fast from here, can be a very pointer. The sphere must have rotated many times in it must have rotated many times, okay, after that it must have covered L2 here and came near it here, okay, so I believe that it must have done 11 + L2, it must have believe that it must have done 11 + L2, it must have believe that it must have done 11 + L2, it must have also done fast plus it has covered this sphere. You must have done the complete round, right, and how many times will it go round, mother, let's check the end time and cycle this circle, mother, let's say that this many times, this distance is fast, the slow one is the distance, because what I said is fast. Whatever it is running at D speed, slow is fine, so the distance covered in slow, if I put it in the throttle, the same amount of fast will come out, but I have already put out the fast here, see, this one is fine, so what does it mean? Both of these will become equal i.e. 2 * 11 + L2 i.e. 2 * 11 + L2 i.e. 2 * 11 + L2 must be equal, you are 11 plus N, so you can do it like this, then L1 + L2 will become equal, after mincing it will become then L1 + L2 will become equal, after mincing it will become then L1 + L2 will become equal, after mincing it will become K, so now look at the most important one After that, if you go again then leave it, you are marking it, so what is left, you are looking at this portion, child, I am making this portion clear by erasing it again, I am making it clear again by erasing, what am I saying? Which means N means complete cycle completed, multiple times and times, it is ok in that L2 - I am doing it, ok L2 - I am doing it, L2 - I am doing it, ok L2 - I am doing it, L2 - I am doing it, ok L2 - I am doing it, so see will this part be left, will this text be saved and what does this text appear to be equal to? I am seeing it equal to the album, so you see this L1 is equal to this distance and this too which came here while walking, so this is my starting point of my cycle, so this is the proof that if I take the mother here. But P and S will be found here. If P and S are found then this will be my starting point. We have proved the cycle mathematically. It is okay. You must have seen this in college too. We were told this is right. The story that was told is the same which has just been converted in the court. If we do then let's code this, okay then let's code like this, look, we will do exactly what the story tells, we will not do anything extra, okay, so what I said that we have to take 2 pointers, let's take two pointers, list a little stress one. Slope Underrow which I write as S or slow which will be pointing to the head and there will be a fast finder which will also be pointing to the head and simply write for loop until fast is not equal to. Nal ho end and fast is connected only then what have I derived from fast ka next. It is okay to pay attention to the person who is running fast. If you write about his bad condition then you will be safe. If it is then you will have to check the next also, it is not equal to tap, it is okay and first of all, write one more thing, there can be two reasons for coming out, either slope must be equal to fast, okay then brother, it is not equal. We would have stopped only then and would have gone out of the way i.e. we would not have found the bicycle, i.e. we would not have found the bicycle, i.e. we would not have found the bicycle, right? If it would not have been equal to slow-fast, right? If it would not have been equal to slow-fast, right? If it would not have been equal to slow-fast, and if it would have been equal to slow-fast, it would and if it would have been equal to slow-fast, it would and if it would have been equal to slow-fast, it would mean that it is a bicycle and if it is a bicycle, then it would be less of us to search for it. Where is the cycle started from? So what did I say, if P is taken from Ram, then it will start from starting, it will start from head, slow will not be equal, both will keep moving forward, P = P's next because P = P's next because P = P's next because till now I know. That is, now we have got the bicycle, here we fast and brake, so it means that we have got the bicycle, here we have put the check, okay, so we are definitely going to get the bicycle, right, let's do the next move of slow as soon as we stop and slow down. If it comes equal then it will break the vicious loop. At the end if we make return P then we will slow it down. Look at the thing because if both are equal then only the break will happen. Volume is ok, the story told is exactly what is written, nothing extra is ok, it was more important than that. You understand why the engine is reducing, then mathematically I have explained to you why this brother is reducing the look, why P = when it is slowing down, why P = when it is slowing down, why P = when it is slowing down, then only that is the starting point, mathematically I have explained it, okay, it has also been submitted. Any Doubt Hota Hai Residence Pe Out See You Can Next Video Thank You
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
5
hey everybody this is larry this is day 16 or 17. why is my computer so slow okay day 16 of the leco day challenge hit the like button hit the subscribe button join me on discord let me know what you think about taste farming as you can see i'm back in new york yay um i got in really late after about 12 hours of uh flying and stuff like this no that's actually not 12 hours of fine but just 12 hours of being in the airport and all this other stuff so i'll make it up with another video uh with a better aruba video intro tomorrow but also follow me on instagram if you want to check out how that went but um anyway yeah let's do today's problem longest paradromic substring okay um let's see the first thing that i look for to be honest is uh the length so that means that there's gonna be n square um there is there uh what's it called manager's algorithm well i don't know i still kind of refuse to use so yeah i am gonna you know put it here i think that's how you spell right uh yeah uh so google this if you like for cancer linear uh yeah so that's basically the idea but that's not i don't think that is necessary here so we can just do it in a naive way i'm not sure why it's a medium but i guess it's from way back when but and also if it required a manager's album i don't think it's a medium per se though i don't know it's just like you know like a very uh very specific algorithm that i find is not very practical uh to or like it's not worth my time to learn and i still don't know it uh if i am doing competitive and i'm seeing this i'm saying that i need this i would just google it and you can maybe say cheat a little bit you know but that said you know knowing the name of it is good enough for me because i don't know i just don't find it that useful per se but i guess you can say that about a lot of things that's just me and i know what you're going to ask uh for some of you anyway maybe not all of you so maybe i don't know why i say it like that but so yeah so the question is should i learn this from my interviews right my answer is going to be no i actually uh i'm thinking about doing a video about these kind of weird not weird just like you know maybe advanced algorithms if you want to call it that but just these algorithms that are not fundamental per se right um and the answer i would say for you if you're still working it out if you're still learning how to do dfs better bfs better dynamic programming better binary search better just regular sorting better and all these other algorithms right uh there's probably a list somewhere um if you're still learning how to do them better i would rather work on pushing those things better as well right because look the truth is you know no one cares that you know i mean what you know you could even do like a conditional probability thing right like what is the chance that you know you're going to get this on an interview and then you nail it out and that you're able to know it enough to explain to the interviewer how and why and all this other stuff right um i don't know i have probably less than one percent in terms of just even getting this specific problem and then the other question is well you know like let's say you get um let's even like just say you have 50 percent chance of getting a bfs problem or a manager's algorithm problem right well the key thing there then is not to be average in both because being average probably isn't good enough or maybe not average but like an average interviewer maybe or interview esi not an average like engineer um with a job or something but you know you're being average in two things you know like that doesn't that's not impressive right yeah you know i'm just saying that's not you know my thing but if you're like really good at bfs then you have 50 chance of really impressing someone right anyway that's my spiel that's why i still haven't used or i think i've used it before like once literally um but otherwise i just and that time i googled because i knew the name and i knew what to google for so i don't know take it as you will uh anyway i will do this tonight way we're just for i feel like i've done something like that maybe not this particular one i feel like i've done something like this in uh recently but i think maybe there was one that was just like binary but yeah so basically there are two types of pattern drums right sorry i if you were not thinking about manager's algorithm and you're here just for the basics um then i will go over that right now there's two type of uh pattern drums right there's either an odd one right like this is five characters is odd so then the middle is the center and then there's an even one which is i guess like something like this where the middle is in between characters right so that's basically the idea and you could just prove first per both uh let's do it for odd ones first uh then now you know left is to go to center right as you go to center uh while left uh while well let's make sure this is greater this is within bounds and this is then and s of left is equal to s of right then we move left to the left and we move right to the y right and then at the very end we have a best um here i just noticed that we have to return the string but that's okay uh are there multiple solutions huh it doesn't say i mean it could have multiple solutions if it's like even literally like a b right without multiple solutions it doesn't really say so hopefully it doesn't come into play but uh but yeah so then now the length is equal to right minus left plus one right you could kind of do the math and then if l is greater than best then s is equal to l start is you go to left right and then even ones so for center in range of n uh left is equal to center right oops did it the british by accident center plus one and then you could hear see that this is you know because it goes out otherwise um and then basically the same thing here uh maybe we could do a little bit better with you know uh code duplication but for now i'm going to do this and then at the way end we just return s from left to left press best i think that's right-ish i'm really bad i think that's right-ish i'm really bad i think that's right-ish i'm really bad at string thingies so maybe that's off by one i don't know okay that's not good did i miss oh this is a d not a b i got confused okay but that's okay uh maybe i did it off by one oh well i'm silly this is stored that she said i don't know if that fixes it but hopefully that does okay that does not in fact hmm oh this is awkward because we don't check to begin with so this may not be right okay right i just have to be a little bit lazy or it's a little bit more checking but i think this is fine also this is wrong because now this is even i copy and paste without thinking about it i mean and the sad thing was i was thinking about this while doing it but then after i copied and pasted i forgot about it was then right oh no this is let's see am i doing this one i think this one is the one with the plus one and this one is where am i right let's think about this right so these should be inclusive bound so if you add number you have say zero to two then that's three numbers so that's plus one uh here this should be more right actually right because if you have now zero and one it should have two no i guess they both should have this i'm just being silly um yeah because i was thinking about doing off the center but that said i'm still really wrong for some reason hmm i need to do this after the check that's one man very sloppy today sorry friends i just got off a very long trip so that's my excuse uh i have excuses for everything but you know oh there you go that was the funny thing is i made the same mistake on the by wiggly q4 uh like yeah i just had things in the wrong order and not paying attention just going really fast because it is easy and you know as you and as i said you know it's the easy things that will get you uh that's how i lost my drone so anyway uh oh let's give it a submit wow i have i hope i don't get a wrong answer again i'd have wrong answers before okay 807 day streak yeah yay uh this is going to be quadratic time and square uh and o of one space i mean the space part doesn't we don't really use much space uh oh i guess technically o n for here depending how you want to say it but other than the output uh what did i do well here wow oh i was trying to be cute before i said the same thing last time too uh cool uh yeah i mean i guess just easy off by once uh cool let me know what you think hit the like button hit the subscribe button join me on discord i'll see you later stay good stay healthy to good mental health goodbye and take care
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
730
cool 7:30 count different palindromic cool 7:30 count different palindromic cool 7:30 count different palindromic pollute public subsequences chemistry gas find a number of different non-empty gas find a number of different non-empty gas find a number of different non-empty powder omics of sequences in s and we turned that number module 10 to the nine plus seven which I guess is a prime a subsequence of a string s is obtained by deleting zero or more characters from s sequences palindromic if it's equal to the sequence we were okay two sequences are different if there's someone which a sub I see that you got a piece of I guess that means that mmm that they could return the same string but they used a different cup or two me and I guess something like that okay yeah I mean I think so the first thing that leaps at me is that if you have to return a number module 10 times 9 or 7 that means as a comet or a problem I mean I guess that's also to define a number for it so it's coming to a farm and usually these are dynamic programming without even reading anything else but obviously that's not the whole point I mean like just saying someone who's done having four gramming doesn't mean you solve it and your interviewer would be impressed for half a second we were like okay now and okay Oh way to hide that India which is Egypt countenance as sub I in the note of it just like after two examples why don't you just put on the top I don't know but anyway each character a survivor being a set a B C and D so here's a for again is a four character alphabet the link of a sub R or s is okay so s is less than a thousand strings okay I mean so yeah so it's definite dynamic programming but the question is how to and they're just one thing example that I mean it tells you the numbers but then here okay and you took these and it called a thousand yeah - hmm I mean it step in thousand yeah - hmm I mean it step in thousand yeah - hmm I mean it step in town over both webbing I think the intuition for me is maybe a little tricky instead basically your map would be and you basically have a table or lookup table an N square table which you know it's a million and that's most and I will be going your substrings is just subproblems and yeah I mean I think the function is just I mean there is a cup of cases and that's how we have to consider it but I think you have like okay given a string gasps yes so how do you construct a power jump when I show you for example let's just say BCC be the first way to do it is okay well let's say you take off the piece on the edge weight so that so it just means it's something like so do so if this is you go to the summation of some other stuff way which is like let's say you take off the P in the edge or you take it off and it is part of the string and then you also have to count that it is not part of the string so I'm still trying to formulate this in my head but I say something like this and then it's not even true I don't know I mean roughly I mean we have to figure out the different cases I think that's quite a tricky point about it and then and you kind of Quinns from the exam well actually I think this is a way oh we see note that please no actually huh ash I was a little bit wrong about Am I why does it only count it once to sequence different it is some language oh I misread just one okay so do so yeah okay hmm anyway I mean that's just edge cases so we have to figure it out it's gonna be a tricky one and then just one step in the middle you could say well you know I don't we use or FCC you and then maybe F of and then you maybe just ignore the first character so in this case maybe you someone like that and then maybe also even have a PC or something like that some combination maybe not quite like that though because it's you have to have some sort of ordering to it otherwise you know you some of these will kind of double count in some ways so I mean there's definitely a lot of things out to be careful about here so maybe as someone like that and then try to think about what's the right to it hmmm I think actually I mean I think so I mean there's definitely some way of constructing this but I'm also kind of you know in terms of you know giving bounds and some of it in the notes is kind of maybe hints and that's where I would kind of maybe think about is in this case actually I think the interesting thing is that each character of that supplier should be in this sad way and even though it's something to quench over I think what you know in some of these problems it's important to solve the problem as specifically as possible and what that means is in this case like we don't just like village and Derrick string thing maybe it's too easy right I think the thing we can maybe think about figure out how to do is reframing some of this in terms of the four alphabet right and what does that mean that means in a way you can figure out how to compress the rest of this string so that instead of having like a thousand characters you could compress it with I don't really have a compression thing in my head yet but in theory you could represent it with in some way by just the fact that s for help and alphabets way and in that case it would kind of make the search space a lot smaller or maybe not search which is like the counting dynamic programming sub number of subproblems a lot fewer I think about I would work so I'm just thinking a little bit and I'm not you I think yeah I should have taken it a little bit better but I think one thing I'm playing around with is the idea that or the question I'm asking myself is that's ordering matter I think for each count in the beginning maybe this isn't even right necessary way but the question is okay let's say you have string that's huge I'm in the poem I'm also having a little trouble with its kind of to kind of it to that some sequence could be duplicated and how we factor that in how do we hmm this is a tricky one I mean having a nut more naive thing is for this just can you memorize I mean the tricky thing for me is try to figure out how to do in a way that doesn't double count some of these duplicate ones and I'm not really so that I can do it and there's a lot of Oh okay yeah haven't ya the tricky part for me is still trying to figure out how to remove the topic it's yeah what's even just PCP way I mean you could just how do you do not double count PCP cuz just for me I would PI identities to see something like some like X you know something like that and we'll have to figure that out but in this case just people I would apply a usually double Cal wait for what usual one by each character and this is and hmm ninis and you could even buy it up more complicated examples where we see CPA bczp then you're gonna get this PCP sequence way too many times right so I'm in the other way just to be a little bit better articulation the other way I would think about it that I was thinking about it which I don't know how to cut it to convincingly is it's kind of like almost like a pillow reverse there like a you know like a graph to kind of breadth first search to kind of add in the string maybe in a thousand it doesn't take that much but I don't even know how I don't think that really that tractable intractable anyway I don't think that's possible just to did a huge amount of non empty powdered room subsequences since when were you let me take a look at this how would I solve that you know I mean the little bit matter is that these problems are always a little tricky and you can tell that I'm it's hard to kind of take late in an interview if you're walking I mean obviously maybe the interviewer may give me hints but in some cases like it would not be good enough maybe they'll be like I remember it's an alpha base the size of the album is 4 but it's hard to kind of know I did you can deter you down sometimes right and I mean sometimes it takes a long time to work for it but it's hard to kind of see someone's toy process so that I and in a very pious kind of very probably the problem like this is an interview question as we saw mr. Nickleby perfect search but when a professor just string coding mm-hmm okay in the interest of time I'm just gonna cheat a little bit and let's see what the answer would care for this 20mm we pull you in and this isn't even that long I was sharing stuff hmm can i rephrase this problem can we go from middle out it sounds like I'm from Pied Piper or something but okay well that's assuming that it is a dynamic program form then we will let's figure out the base case when this case it's just well empty string I don't even know what that would be but to no place maybe this is one you see mmm it is true but maybe not that inside no that's not sure it's just too this is blue which means test records a little bit hmm because you could get p CP oh that's not tomato is that it so this one is using and then CP movie I mean I think this one is the one that I'm actually not sure about because in theory we double counted you love this one yeah so I think these problems that were how I would kind of slowly kind of yeah we construct on base case just to I mean I uses the last we sold almost but that's how I would kind of try to see him there's any insight into the structure of the form that I can kind of think about so this represents see this purpose ants PCP we have Modesto now this is also just really weird recurrence that I'm doing here because that's what you want is to just subproblems action mmm because C is just let's say this is this one and have a second see it's in theory PCP you just kind of wrap it around but then how do you get P and B well you can't even get PP how do you get PP in theory that's baked into one just f sub C which has two years or use not so me so maybe there's another dimension here but that's also that but that would make things maybe that's okay actually because only one count there could be in the coin called the middle so you either you don't sell okay so I think that also makes it so that maybe that's the missing piece but it's still a little tricky to kind of figure out as in this case I would have something like so I'm ringing and stuff just this function based on one parameter you need a second parameter where the second parameter is just whether you used you use the character as the middle piece the single piece that's inferi not too bad we're going to figure how to articulate that way also there's some like weird how do you get from PCP to be maybe just test and I don't know that's not quite as easy so I think some of the easier dynamic programming problems is just different ways of kind of constructing things so that it's exhaustive way like you know for me it's you know you tried all possibilities and well if you try all possibilities it's easy to kind of figure out what like you tried a more like if it's an optimization problem or something like that in this case because you're trying to count and it's clearly you can't even double count is a little trickier to kind of make sure you get some of them right like you can't just like in some cases ways like I say you're trying to get the max of something or the min of something I even if you say you sir you solve the same subproblem a couple of times pick a maximum change way because max of you know two numbers were always you know like you match the same numbers X I'm like I still have the same answer where we're encounted well then you're double triple counting so that's why it's a little trickier than usual but to do kind of these kind of things versus I think definitely we definitely need dimension of middle which brings our size complexity from N squared still to n square but now we at least double that way in size so yeah hmm and actually maybe I D bathing changing into language because you know okay let me night hmm Oh dad said I still try to figure out how to do this you know hmm so okay yeah maybe just need to recompute it yeah I'm having an I've been proving some of the stuff is kind of hard I think we just have to still we I can do something exhaustive about it and I think I mean I think the problem that this reminds me the most is kind of suffering the number of was it distinct sub-sequences sub-sequences sub-sequences way but man by man and to be honest I don't remember how to do it or not I mean I have some idea of it but uh Wow okay let me I think in what I need to do is kind of you know take advantage of the fact that it's four characters how did I do that right okay to be is critically enough okay that's a well I mean okay so well let's dumb it down for me a little bit let's say well only our alphabet is only two characters what would change well I mean I guess my example already only had two characters but I need to be slightly smaller than that I think maybe this is confusing me a little bit but because as I say we would it would quiet I mean we apply a just used indices okay that's in that case let me mm-hmm which I just see so that stuff mm-hmm which I just see so that stuff mm-hmm which I just see so that stuff it's slightly cleaner well I wouldn't say quite no necessary make sure discompose all right okay now let's say hmm so the base case is that let me we have from the beginning okay I mean we fresh my head a little bit well we store my head anyway ah so my inclination is still gonna be laughing way let's say F of hi that's the base case of one character that's gonna be one let's say you have two characters that's still one assuming that they are the same I mean that's fair wait mm-hmm okay I mean otherwise I mean maybe I don't even know if this is actually necessary maybe good question mark don't know so what is f of left and ever why did you go - okay well let's why did you go - okay well let's why did you go - okay well let's just say I mean in the very basic one is zero to five minus one if yes you go - zero to five minus one if yes you go - zero to five minus one if yes you go - that's a boy I mean that's what we said before where you chopped off to stop at the end if not and it's no way is that true No well it's actually probably someone like again this is I'm still trying to think about how to it's been a while cutting a number of distinct subsets in conscious in general not really in the powered room though this stuff may add up okay and if they're not the same and what do we do well I guess we just come to same a member plus I get it backwards mm something like that make sense now that I know you - this because I now that I know you - this because I now that I know you - this because I think this maybe that's how you take care of the overlapping oh man because you - to stuff tats and you - to stuff tats and you - to stuff tats and yeah because I think if you're you know your side characters are the same and you can just take one off and add it to the powder room and if they're not the same then you have to subtract because then some of these will double care okay I mean is that enough so this I mean that's enough ish for the number of distinct sub Queen sequences maybe but I think or maybe I understand them of sub sequences and now that the factor and now we have to factor in the fact that the brigade which is the part that I've had issues with how do we incorporate the up of it so I since it's only four alphabets get to can we have them or character just Angie coaching work well then I got kicked up the internet was I can do so what does this look like what does this mean well first of all this one if I surprise you go to character otherwise you just say what I guess and now this case will be well I guess this is still the same actually I think this one you still have to do the overlap but how about this hmm if it is the counter then and you have say someone like CCP laughing worried and you just us because not sure fine now you have to mmm I guess we just too and now you some coaster and you just kind of do that after each letters of alphabet probably but it's tonight I'm only time okay well I'll just Academy cardova means that this is already on the border with that character so it has to don't go sorry Eisen having troubled this one more than I am usually hopefully well I mean maybe sometimes I'm always into a little bit I think this part is very with it yeah to count the love it's not you go to have carried away tell you some weird pocketing things going on and you just keep the same character and then you count the ones and then you subtract out over counting or whatever it is this what that is you go to write and then it's you go to and then I guess you could try all the possibilities which is which in this case because it's only for alphabet so if this is the case maybe you do something like well you - two you do something like well you - two you do something like well you - two borders and then you do some and then a and then etc it was last T hmm that maybe should be okay now mmmmmm nope now the one will be here okay well sorry I think I'll explain my logic a little bit I think I kind of jumped a little bit from time to time I so I think the plot so my logic was that and maybe I should you know like I feel like one goes supervillain giving a monologue before solving a form so like it could actually totally be wrong but having my first intuition is - okay I don't know but my first intuition one of the more recent intuition is to kind of just count the number of testing sub sequences which is how I got the first formula kind of and subtracting it but taking advantage of kind of character which is which adds a dimensional of kind of would like what is the last character to be of what is the number of distinct eyelid from drumming sub sequences given that characters to the war you know and then inside you could kind of figure it out and if took out on the edge are not the same then you either you know move on to laugh or move on to their way and then you kind of subtract this stuff in the middle I mean maybe I could draw a diagram but you can imagine like but like you have like a big thing so this one ends up counting let's say this chunk and then this recurrence will count just chunk or actually I think I got them backwards but you get the point and then this chunk will kind of subtract out over counting from this chunk because we over counted dad over there and so that's of the two edges are not the same if they're the same then we can just chop them off and then and they're two ways to chop it off right one is to use the edges like I was saying earlier like if you say have say DCP to a stitch so that you could chop off to Abbey's which is to see which leads to someone like see but the answer we have essentially either PB or oh sorry in this case so I don't PPO or PCP or just C itself because you chopped it up and then not use it well so your two possibilities are chopping it off and use it or chopping off and then don't use it so those are kind of two things I'm so actually maybe this is two then yeah so that's kind of the way I would think about it and now that we have this recurrence it's I mean or it that's love to do it's kind of code it up this is I mean yeah I mean I think one thing to note is that both left first one and I mean laughs it's always gonna be left first one and white is always gonna be Y minus one so you can do something that takes advantage of that right now I'm very fearing a level a disease I'm just gonna do it with memorization and also I'm not actually super to be honest super confident about this problem and in those cases doing it with memorization allows me to kind of play around the recurrence a lot easier I need to change the order and even of how to do the recursion or something like that I'm gonna have a base tariff on something like that was that thousand oh my god yeah I know I didn't think right yeah that's a negative one that's what's and awhile you and then in this case we just need to kick it off using COBOL for recursion not sure I recommend it for quick okay now that what we do only need alphabet it's oh okay fine maybe there's multiplication somewhere maybe I'm missing something mmm and I'm gonna screw this up number of sales let's try that well guys what that point is that's the one implement with this chunk mm one case yes soon this is gonna be a mess to read mmm it is in the cleaner okay now I have to there's a subtraction that okay play okay like I have to check the alphabet I not if it said sure we'll play around just was I could be too it's more like that maybe let's see it compounds first oops I knew that yeah I was thinking about him when I was typing it but forgot to use to go sometimes I forget see my conan's now God is it works I mean well it compares I mean okay hmm let's try it easier case for us back to the basics okay so I'm double counting something for sure um okay how would I get eight well it is just to deform tutors to know hmm how do I get a that's a good Kush oh one other thing I need to do but totally forgot and somehow it still won some time it's memorizing stuff we had that inverse you know it's still warm okay so at least it's consistently wrong which is all you can ask for sometimes hmm yes this is supposed to be in there no careful there's some weird stuff about casting possibly but I know what we'll see what happens and always forget my double count on two alphabets seems like it because why does to with my diet to three alphabets okay my kickoff is no wrong it's double-check some still position it's double-check some still position it's double-check some still position not count four times probably not it should only be giving me a B so it's something subset of the times you know I never check for house we're here somewhere that's not quite okay well how did that happen - how cuz well how did that happen - how cuz well how did that happen - how cuz Maltese are doing this yeah I think I got these backwards that's why and where's my cup no well I guess I'll look at the locks but this doesn't make sense it's a bit ashamed and we could chop them off otherwise then we to that overlapping thing yeah I know I'm just some type of code here but okay I mean it's not white but at least it under counts which is good maybe Helena okay and the one thing that I don't maybe here is because you have to chop it off into two parts of Peru so let us play around guy so I think that's the thing that I had some doubts about face cases are hard well okay I mean that just seems to be right but I mean anyone could be right on one problem so let's try this another one and one test case about it we should try to see easier month Luis okay well I don't know how that worked it okay well let's try some empty strings and stuff like this there - magic form you demand it no okay there - magic form you demand it no okay there - magic form you demand it no okay well fine hmm well then these it's wrong I call it beforehand hahaha should we turn one once right Oh dumbass how did this even mmm how do I get this big thing right if i hears wait what was i even right okay I mean like maybe I maybe saw fly some stuff that wasn't out it oh yeah that's what I mean sometimes I okay when you get it get things white by accident you still want to know why huh I have no time another - you submit and I have no time another - you submit and I have no time another - you submit and then see what I get one but okay well I didn't even know what to say sometimes you just get things right but okay yeah I'm yeah so I so yeah so uh this took way longer than I really want to spend on this problem to be honest but uh yeah I think so the we added two extra dimension because so that we can Chi make sure that you know I'm having much really much earlier we were talking about kind of coding strings kind of in a distinct way and kind of keeping the character this allow us to kind of make sure that at each time that's the number of that's like how do you say this because you only carrying each possible pairs of or on the edges of characters once that's how you kind of keep it this thing I'm not probably not saying it quite right but you can think of it like yeah I mean I don't know this is kind of tricky but hopefully it helps me work on next time and that's now football but and that's why we keep on practicing a little bit and but I think you took their components makes sense it's just that I'm really rusty and slow and putting them together I think so good so how I would it improve this code I mean this is a standard memorization code the tough part in dynamic programming problems is not really the coding per se it's always and kind of the construction of the recurrence and in this case you can note that left or is only go well there's left over right and the right of only go left so you could build things kind of based on the fact that you only use the previous row in the matrix that way and then you could from - good constructive could from - good constructive could from - good constructive occurrence to pair with dynamic work when in a time in a dynamically programming leeway but so there's some optimizations there to quit but I think this is actually easier to understand as an interviewer I think I've mentioned it earlier I don't like the problems like this because there's some culture I mean it's not really a catcher for saying this you know a lot of time in program form that some of them has like a little bit of insight that it's just such a huge advantage if you've kind of seen it before so and it doesn't really usually help me think about like it doesn't let me see how to nwe things about problem so I don't really like this problem for that reason and specially if comet or icky stuff it's sometimes tricky if the recurrence it's not like straightforward like in this case it takes a furniture of just a bell which is the size of the alphabet which like maybe if you already understand why certain things that distinguish Elvis or not and it makes things a lot easier which is that something that I don't know it's no tricky but and like I said me definitely I'm a little biased and although I took him maybe if I have worked on this like five six times and it would have been okay but like the with enough practice on similar problems but given that I just don't like these kind of problems which we choirs like a almost like a light Bobby a moment where like I got this where a lot of things we're like well you know I certain constraints forces you to think a certain way and then you know maybe that's okay no but uh I mean it does I guess for me anyway there that it is a hard problem I probably in a post-mortem kind I probably in a post-mortem kind I probably in a post-mortem kind when I apply chef's think about in terms of distinct subsequence is a little bit earlier I think I was probably the idea of kind of first principles a little bit too much and try to like derive it from that way but I think as we served my explanation but this form is probably and maybe if you haven't uh you know got two distinct subsequent qualms before
Count Different Palindromic Subsequences
count-different-palindromic-subsequences
Given a string s, return _the number of different non-empty palindromic subsequences in_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two sequences `a1, a2, ...` and `b1, b2, ...` are different if there is some `i` for which `ai != bi`. **Example 1:** **Input:** s = "bccb " **Output:** 6 **Explanation:** The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'. Note that 'bcb' is counted only once, even though it occurs twice. **Example 2:** **Input:** s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba " **Output:** 104860361 **Explanation:** There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7. **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'a'`, `'b'`, `'c'`, or `'d'`.
Let dp(i, j) be the answer for the string T = S[i:j+1] including the empty sequence. The answer is the number of unique characters in T, plus palindromes of the form "a_a", "b_b", "c_c", and "d_d", where "_" represents zero or more characters.
String,Dynamic Programming
Hard
516
337
Hello Hi Everyone Welcome to my channel let's all the third problem of house road and series for this is a problem solved different in first attempt and less tourist problem like this time to stealing money from big boss house hair in this time is so face -2 Rok Di Houses In Sacha is so face -2 Rok Di Houses In Sacha is so face -2 Rok Di Houses In Sacha Website Do Exams Housefull-2 Directly Website Do Exams Housefull-2 Directly Website Do Exams Housefull-2 Directly Connected Houses No Deep In The Same Night Directly Linked House Which Means From This Root And Directly Connected Fan Following This Rule Please Subscribe Zura Den Roop Can Only After Delivery Subscribe Against And Child Veer Life Is The Root Apne Can Have To Wander Around 120 Three-In-One Total Romney Examples Pay 7 Three-In-One Total Romney Examples Pay 7 Three-In-One Total Romney Examples Pay 7 Plus Subscribe Don't Be Rudra Roop Dedh-Dedh Can Do Plus Subscribe Don't Be Rudra Roop Dedh-Dedh Can Do Plus Subscribe Don't Be Rudra Roop Dedh-Dedh Can Do Subscribe My Channel Subscribe The Maximum Money Can You Solve This Problem As They Can Include Or exclude maximum possible for this problem no maximum from tree and tree for true history for this problem subscribe thank you will always be pimple we can show this day route 200 from the route which can first robert e dravid and will have to record meanwhile Directly connected with Android Soen Virudh is not wrong in this can go to the child subscribe my channel subscribe will definitely solve this way crop will rock you can develop plus absolutely this and eggs subscribe and 10th shampoo first chapter of water of Ganges and You can go to The Child Crying Child Died From The Day The Left Ki And Arun Dot Left And Similarly The Light of the Channel and subscribe the Channel Root Dot Right Ki Dot Left Ki And Other Is Dot Right All Types Of Baroda To So Will Take Some words of all decision and you will also find default from difficulties for daughter Daughter is arriving from this point when skin no Veer will get value from difficulties subscribe for Live Wedding of Dainik Rudolph is not null bank Android System from Divine Presence of Witch Runes Platform Root subscribe Witch Runes Platform Root subscribe Witch Runes Platform Root subscribe The Channel subscribe Child With E Do No Evil Returns 10th Maths Cheese From Root From Road Root Subscribe Quote Pants Iss Zameer District Court Can Be Accepted His Mother Language Day Observed In The Cases Not Asli Task Acids Payroll Time Complexity of dissolution and every time you for every day and time complexity and see the receiver which rules so let's root rot in the bluetooth incident will grant from the day God bless you that don't left and don't love life like father of and right that don't left And Right Dot Right Choice Awards For Schools Will Make In Case Of Fear Of Being Rooted Radhe At All Root Don't Love Affair F-18 Android Love Affair F-18 Android Love Affair F-18 Android That Shows Father Is This Is Zaroor Lage In Root And A Call From Chronic Hydride Noida Will Not Prove It's An At All Root Daughter Fat That Not Left Sufi This Is Repeated All Problem Already Have A Girl As Well As Her Suicide Note Subscribe Property And Subscribe Solve Problem Will Result In A Very Fatal Attraction And Deposit That Note New Year Will Check Were That This Map Already Contain Map Donnison's For The Current Cry Will Return Water The Current Cry Will Return Water The Current Cry Will Return Water Value For The Too Tall And Ever Saw This Will Be Written In Otherwise Will First Calculated In The Map Root And You Will Come From Fear And Will Return Value From This Is The Subscribe Loot For Every Time You Will Not Only Give One Time Complexity Subscribe Impress Doosri Side Inko D Memory Yasmin District Magistrate Sudesh Isi Every Time You Have Two Options Like Thanks For The Ruk Kar Loot And Institute Of Going To Result First Same Result Like Share And Subscribe Vijendra 109 The Result Of Root Will Make You For The Result Of Ruth Hai A Dot Right Like Share And Of Verses Warning To And Brothers Who Don't Know The Results Subscribe Now To Receive New Updates Root Subscribe Song The First Case Solved Will get the results from including is reading will return to maximum number of this to and every time he z10 otherwise absolutely celebs result debit the receiver appointed not including a maximum of from the subscribe The Channel and subscribe the Channel Please subscribe this Video give yaar Do Quality is only about values ​​from where it Quality is only about values ​​from where it Quality is only about values ​​from where it is not like and subscribe Amount of money drowned in school on Thursday subscribe The subscribe like this problem subscribe The Channel thanks for watching
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
1,054
hey yo what's up guys babybear4812 coming at you one more time today with problem number 1054 distant barcodes so this problem came up in earlier this year in 2020 in one of the weekly or bi-weekly contests weekly or bi-weekly contests weekly or bi-weekly contests and it looks like it's been picked up by uh bloomberg predominantly so they've asked this one a couple of times and i think it's a really good problem with a uh a bit of a clever solution really uh pretty unique i'd argue so i haven't really done one like this before personally i don't know what happened there i haven't done one like this before personally so i thought it'd be a really good one to go over and maybe uh pick up a few tricks from so yeah if you haven't tried it yet pause the video give it a read give it a try and then come on back all right so uh 1054 distant barcodes we're told in a warehouse there's a row of barcodes where the ith barcode is barcodes vi rearrange the barcodes so that no two adjacent barcodes are equal you may return any answer and it is guaranteed an answer exists all right so if we look at an example like this one here where we've got one two easy to represent a barcode uh what we could potentially return is um maybe here what we could potentially return is two one uh they're also saying you can't return any answers so that means you could also do something like one two all right so both of those are acceptable we're good uh similarly we've got one two three they went with one three two one again i think it's a very easy problem to understand not an easy one to solve but easy to understand so every single bar code now does not have any it doesn't have a matching barcode to itself in either of its adjacent positions all right so how do we do this well maybe we can uh let me walk you guys through at least kind of what my first attempt was and how i failed horribly at it um and then i'll give you guys the correct answer and really like i'm only half joking but truly i do want to walk through the logic and see how we can actually get to answering this question all right so one two is what we got so one potential way of thinking about and this was again kind of my first thought um was to sail me you know maybe i was i think i was modifying this in place but what i'll do is for the sake of this example and for the final answer i'll keep a separate result array and build my answer in there uh what i was doing was saying okay well i can bring this first element down and then let's start from the second element and iterate onwards all right so i start iterating from here and i what i do is i ask myself is this element the same as the element before it if the answer is yes then what i'm essentially going to do is to jump ahead and say okay let me keep moving some pointer up until i find my first non-identical element which would first non-identical element which would first non-identical element which would be this one right over here and then what i said was okay well in that case let me swap those two let me make this a two and let me make this a one and then okay we're good so we've got this like one two one situation and i'll again i'll kind of keep this here separately um but this is a two all right so we um no i apologize that's a one that's still one i'm sorry i swapped these this is now one all right it's no longer two um so i keep on going i kind of place this item here now i'm doing some double tapping so this is immediately gonna become quadratic anyways it kind of felt wrong but you know you might think okay well this is fine now you know the one is different from the two and then oh we got another adjacent one here so let's do the same thing let's kind of traverse along until we find a non-one element non-one element non-one element which we do here so we say okay wicked let's swap those this becomes two this becomes one we get something like two one we check these numbers they're all good it's like cool all right we got a solution i forgot to write this down but you know it all kind of lines up i know i'm a bit messy and quick in my explanation but i think generally you guys get what i'm getting at the problem i found there was what if we had an example like two one all right so we look at the two we drop that down then we say well this one's not the same as a two so everyone's happy one goes down we get to this one and realize okay well you know this one is not the same or sorry this one is the same we need to swap it with something else i take a step forward whoops we're out of bounds we end up returning this and this ain't right all right and it's inefficient so this solution didn't work very well so how heck with this i'll start a new one so that one didn't work all that well for us and then essentially what we need to realize in this problem is uh is as follows actually there's one piece of information they give us which can kind of trigger a hint in our minds and this hint isn't necessary you can still solve the problem without it but what they do say is that an answer is guaranteed to exist all right so if an answer is guaranteed to exist and i give you a list of length and okay how many times can the most frequent element appear if i give you a list of length six right and again same question how many times can the most frequent element appear well if we want to start you know we've got an even number of elements and there's guaranteed to be an answer we can at most have three ones if i've got anything more than three ones i won't be able to do this and so if that's the case we've got you know we can get up to three ones if i had five elements let's think about if i had five elements could i slap three ones yeah if i had you know six i could have something like this x and then if i had something similar except an odd number i could have one x one so at most we're going to have you know n plus one maybe we'll have n over two or um n plus one over 2. that's the maximum number of times we can see the most frequently occurring element so why am i making a big stink over this well if we realize that's the case then no matter what if i wanted to fill my array with my most common element let's again let's go with a let's go if we had five for example if i had five elements in total and i potentially most frequent up here up to three times okay the maximum possible where do i have to put those right i would have to put them in the first position zero with index then i'd have to put in the second index then i'd have to put in the fourth index once that reached the end i would then have to go back and start filling in these other odd elements with other things and this is exactly where the trick lies in this question you're not even the trick but just the key to getting it if i had something even longer so let's say i had one two three four five six seven eight four and i'll do something like this i'll do five just we have an awe i forget the five we don't need it we'll do a an even number this time all right one is my most frequently occurring element so five two three four five six seven eight how i would playing again we'll obviously go through the code but logically to fill this in what i have to start from left to right in the zeroth index position and start filling every other element so i've done one okay i filled those now i've got the rest these elements to fill how do we ensure now what is so we could get in a situation where let's say i had something like oh well i'll you know i'll take these and i'll start filling them from left to right so i'll go two three and then maybe let's say we didn't have the four for example all right just to kind of prove my example then i'm like oh damn i'm out of space so what do we do here how do we make sure that we don't fall into this situation well what we'd have to do is we'd have to say let's do almost like a i like to think of doing a two pass fill through the result array skipping an element every single time so first we're going to fill in the even indices and then the odd indices i filled in all my ones let me keep skipping two indices at a time and fill this thing so i skip another two from here i fill in this two we got that now i skip another two whoops i'm out of bounds reset my index back to one we're now going to start filling the odd indices we're gonna fill in the two that's gone we're gonna fill in the three that's gone we're gonna fill in the four that's gone you passed your interview you're working at google thank you later does that make sense let me know down below if it does or of course if it doesn't as well but this is the key to solving this thing is understanding that we need to find i'll write these steps down we need to find the most frequently occurring element all right we need to find we don't necessarily need to find how much you know how many times each of them and they backtrack we need to find the most frequently occurring element in order to do that what we've got to do is to find the frequency of all of these so we'll do one pass through and we'll keep track of the frequency of how many times they come up of course the data structure we should use for that will naturally be a dictionary or a hash table okay to keep track of that we will then go and identify what the highest occurring highest frequency element is and we could potentially do that in one pass i think i'll break it on just two steps just uh just for clarity of explanation but we find the most frequently occurring one and we start filling from the zeroth index on every two spaces and we keep filling we keep doing we keep going when we run out of that element we start filling in with the rest of the frequencies until we kind of reach out of bounds here the first time then we jump back to this first index and now we fill the odd indices all right i hope that makes sense i hope i didn't go through that too quickly but like i said it at least for me this was my first time seeing a problem like this and i thought that it was a i thought it was a really clever solution so i think at this point we've hammered out the logic enough to kind of take a pause here jump back to the code and uh and see how to make this thing happen right now as per usual first thing i'll do is i'll do my error checking though i think the error checking might be redundant here might be i think the code would work without it but i'll put it in here for now um if not barcode so for given an empty list or none or something i'll just say let's return barcodes all right so we've done our error checking now next thing we need to do is to say uh find frequency of all numbers all right so uh essentially what we'll do is we'll create a let's say a dictionary and in this dictionary we'll loop through the barcodes now and circling frequencies and what i'll do is i'll say for all the numbers in barcodes what we'll say is this if the number is not the barcode so if i'm not in barcode uh sorry if it's on the dictionary already it's not in the dictionary then we're going to want to put it in there so we're going to want to say a dictionary of num and we'll set it equal to zero because what i'm going to do out here is just going to say we'll take dictionary of num and increase it by one so this way if a number is already in there we won't jump the safe statement we'll just increase the frequency by one otherwise throw it in first then increase the frequency all right so again i understand that as you're going through this you could potentially pick out the most uh frequently occurring element in that one step again i'm just gonna break it out here and then you know if you'd like optimize away let me know in the comments down below if there's a way to make this a lot nicer and cleaner um so then i said here uh identify uh max occurring element so maybe what we can do is we can find the max num and we'll keep track of the max frequency as well and we'll set both those equal to zero just by default right off the bat and what we'll do is this is we'll essentially say let's think so we want to go through all of the all the numbers in the dictionary so we'll say for number dictionary uh if the frequency of that number so if dictionary of oops none and maybe you actually know what let me just create a variable say frequency is equal to dictionary of num okay if frequency if it is greater than max frequency then what we want to do is we want to say uh maximum is equal to no and we'll say that max frequency is equal to frequency and i believe that's it so in that step not like for the problems thanks guys for watching but uh i think that's it in this step because again what we're doing is i'm just initializing these variables here and i'm saying if the frequency of this number in the dictionary if it's greater than the max frequency we've seen then we'll say that's our most occurring element all right so now what we want to do is we want to create a uh create a result array so let's maybe create result array and from there we want to or create a result or okay maybe that can be its own stuff so i'll say a result and we want to make it of size the same as barcode and maybe i'll fill it with zeros for now it doesn't really matter so i'll say zero for some underscore in uh in barcodes just so they're the exact same length so put a list comprehension there and now what we want to do is to start so we'll start filling list with most frequently occurring elements all right so what we're going to do that first and what we're going to do is let me write out the next step after that we'll say um fill out rest of elements right we can't forget those then after all that we're going to return the result at the end period or at the end of the problem so returners on that's over like crushing a ladybug with a sledgehammer um but being crystal clear here so we start filling this thing from like we said the zeroth index so i'm gonna say we'll start at index equals zero all right and what we're going to want to do is we're going to say let's do the following we're essentially going to want to say while um let's say this uh while max frequency is greater than zero what we'll do is we'll decrement that max frequency as we go and then eventually we'll get to zero so i'll say well max frequency is e uh is greater than zero we're going to say uh result at index is going to equal the max number that we had so we're going to be filling that in once we fill it in we want to jump the index up by 2 index plus equals 2. and so at this point what we've done up and max frequency minus equals 1. right i almost forgot that part i said it out loud if we had let's see our element occurred three times so max frequency was three we set result at zero to be our number and x goes up by two frequency goes down two all right we try it again we fill in the second index because it goes to one we fall on the fourth the next greeks goes to one um our frequency goes to zero excuse me and we're good there so we've jumped our first second third um and so now we've filled in the result with our maximum occurring element what i'm going to do is i'm going to take that element actually and delete it from the dictionary and the reason i'm going to delete it from the dictionary is as follows i'm going to want to iterate through the rest of the dictionary and get the frequency of all those numbers as well i don't want them iterating through it i don't want to pick up this max number because we finished with it already so delete uh dictionary of maximum so that's going the way of the dodo that's gone and what we're going to say is this if we look at the example that we had here when i filled in when we were filling out this area here we had one and by the time we got here to the end if we went back to start filling in the twos we would have already had to have jump back to the first index conversely if you know we had this scenario we filled in the ones then we still had space to keep going so we're not sure yet that if that index is out of balance or not so what we can simply say is if index is greater than or equal to the length of the result then we simply want to set index factor to equal one all right otherwise what we want to do is this is we want to say four uh again four num in a dictionary and again these two steps i'm sure we can make uh maybe a cleaner way to merge these together into one i just i really wanted to do it i wanted to do it this way again to separate the logic because the other way to do this thing is to pull all the items with their frequencies um pull like a dictionary.items or pull like a dictionary.items or pull like a dictionary.items or something and sort them by frequency sorting would take and log n time i wanted to do an in end time so that might make the steps seem a touch clunkier but it's the performance will be better so that's why that's how i opted to do this so for the numbers in the dictionary we are going to say following uh we're going to say uh result of index or maybe let me say this i'll say while the even better let me do this again frequency of that number okay we want to know how many times we got to fill it in so i'm going to take the frequency of that number by saying frequency is equal to dictionary of num i'm then going to say that while the frequency is greater than zero so similar to the trick i did above i will say that result of index is equal to the number i'll then say that the frequency or the index needs to jump off by two frequency needs to go down by one now the index i said two i typed one the index needs to jump up by two and every time we jump up by two we risk jumping out of bounds again so every single time i check this for example imagine we just got to this so we started here right then we realized we're going down to that second while loop the one that starts right here we fill this thing in okay cool we're happy we jumped the index up by two after we filled it so we filled in this two we jump the index up by two but now we realize if we try to fill it again we're going to get out of balance so what we've got to do is again to do the same check that we had up here if we've gotten there then let's go back to index one and start filling from there and then that'll take us straight to the end and so again this point is overkill i don't need that there um i do need to align this though and i think that this will do it so let me i'm going to run and make sure that i didn't make an error oh boy that is surprising very pleasantly surprising and you love to see that happen 98 percent okay around in 97.59 percent okay around in 97.59 percent okay around in 97.59 super quick um memory usage i did create a result array a separate one there is a way to do this without one i believe um and it will it might require a bit more thinking so i'll leave that with you guys maybe as in it's an exercise left for the reader uh to play around with that if you're interested this is this all kind of fits just on one screen here so i'll leave the code if you want to take a look at it any questions about this any other questions you want me to solve you've heard this bill before drop in the comments down below like subscribe share with your best friends your teachers your mom your pet dog everybody should see this i think um yeah let me know what you think guys is always something to mess around with you and i will see you next time peace
Distant Barcodes
complement-of-base-10-integer
In a warehouse, there is a row of barcodes, where the `ith` barcode is `barcodes[i]`. Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists. **Example 1:** **Input:** barcodes = \[1,1,1,2,2,2\] **Output:** \[2,1,2,1,2,1\] **Example 2:** **Input:** barcodes = \[1,1,1,1,2,2,3,3\] **Output:** \[1,3,1,3,1,2,1,2\] **Constraints:** * `1 <= barcodes.length <= 10000` * `1 <= barcodes[i] <= 10000`
A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case.
Bit Manipulation
Easy
null
678
Hello Guys Welcome Back To Decades And This Video Will See The Valid Parents Is Trick Problem Typical From List To Dresses For Wedding Challenge So Let's Look At Problem Subscribe Tanning Only Three Types Of Characters Which Tend To Check Weather This Is The Subscribe Like Subscribe and subscribe the Channel and subscirbe Temples in the First Example You Can See Reduce Opening Practice Bank Balance Bakons Racket Sufism If Star Justin MT Strings and Destroys Balance by 0.2 In the Second Example You Can See This 0.2 In the Second Example You Can See This 0.2 In the Second Example You Can See This Practice Bank Balance Subscribe Button Last But Not The Least To Interest Balance Thursday This Is The Most Of The Distinct Will Not Possible To Balance Subscribe Must Subscribe And Bell Quote Here Of Minister's Intervention In Brackets Solar System That We Can Be Taken To Our Battery Interesting Net Balance This Poster Will Get Converted To May In This Tree To Understand This Problem subscribe to subscribe our The Validity Problem The Thing Which Comes To Mind Can We Do Subscribe To My Channel Must Open Half Open In Brackets But They Need To Take Care of ministers will be costlier option see here also opening racket according racket in this string will make the position of the subscribe like this is not away be like this is this what is this subscribe and subscribe the Channel Please subscribe and subscribe the Channel subscribe Positions instituted of putting a characters so let's just traverse through this interesting the character reader will do subscribe now to the value of Quote 9 You can directly raw elements in the OpenStack so will look into the time because they can always convert Dual App Disclosing Racket in 250 Assume that we can convert into doing so will give they to learn adherents directly can be maintained a sentence subscribe to the Page if you liked The Video then this text will be achieved its nt strings in this case basis of string and go through latest look at the next example2 is vansh and will start from this post at which app open subscribe The Channel and subscribe the character can be written letters in hindi where already subscribe Video then subscribe to the Page Know the second step is to balance there opening racket sunavai travels and the leftovers open in brackets in this openstack and tried to balance by converting textbox using back end No the first element which left 100 will start setting this star no you can see the district has also arranged in ascending order because while passing from left to right with just the right most element will always be the highest value is 0 balance subscribe and subscribe the Channel and subscribe this Video not have much gain welcome per it is the current tax balance star delicious top-10 stories have star delicious top-10 stories have star delicious top-10 stories have value 410 relying on the right side of this opening credit the forest scam balance subah pau this element saudi operation will be performed For all elements with app open subscribe and will not possible to balance the open floodgates and subscribe not give no example for example subscribe element from this and women exposed and subscribe chittor dual and closing brackets and balance no the second step is to balance the Opening Racket Sorry for open traffic jam daily and practice positive balance otherwise it is not lead and will balance sheet using sisters show in this it is not empty so will have to balance and so will start balance in from right to left days from top Down Now They Are At The Side Three Opening Racket And They Want To Balance By Using Star So Will See The Star The First Service Presented At Index 29 The Position Of The Star Should Always Be To Right Hand Side For Opening Racket If You Want This Opening Credit Balance And Because You Can Convert Text To According Racket In This Is It Back Side Reaction Band This Is Not Available To Celebrate This Is Not Possible To Distract Him From Left To Right Brothers Pushing The Index Values ​​To A Faint Pushing The Index Values ​​To A Faint Pushing The Index Values ​​To A Faint Most Index Is Not Able To Satisfy his condition given element in best actor will be able to satisfy software will just returned all lands at distic will not be quite a few important cases which are necessary for solving this problem using this problem can be solved in just to enter traversing distic only one Who does subscribe The Channel Please subscribe and subscribe this This Is The Industry And Processing Subscribe From Here This Opening Racket Center Both Are Finished And You Encounter Using Back And You Will Just To Return Forms For This Is The Hills On This Number Balance Singh Bablu Singh Rackets will also subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe the Channel and subscribe the Veer Vikram Balance This What is This Channel Radhe-Radhe Channel Radhe-Radhe Channel Radhe-Radhe Quid Faster in This Can Not Balance This Will Not Be Valid Backlink Edition in Vancouver Destroyer of Losing Its Own This is the Third K Switch Returns for Proving That Everything and Finally Will Return Truth No Matter How Many Star Subscribe Center Code with Different Approach and This Solution in Different Languages ​​Then You Can Come and Different Languages ​​Then You Can Come and Different Languages ​​Then You Can Come and Everyone Can Like, share and subscribe Benefit from YouTube channel.
Valid Parenthesis String
valid-parenthesis-string
Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_. The following rules define a **valid** string: * Any left parenthesis `'('` must have a corresponding right parenthesis `')'`. * Any right parenthesis `')'` must have a corresponding left parenthesis `'('`. * Left parenthesis `'('` must go before the corresponding right parenthesis `')'`. * `'*'` could be treated as a single right parenthesis `')'` or a single left parenthesis `'('` or an empty string `" "`. **Example 1:** **Input:** s = "()" **Output:** true **Example 2:** **Input:** s = "(\*)" **Output:** true **Example 3:** **Input:** s = "(\*))" **Output:** true **Constraints:** * `1 <= s.length <= 100` * `s[i]` is `'('`, `')'` or `'*'`.
null
String,Dynamic Programming,Stack,Greedy
Medium
763,2221
1,359
Hello everyone welcome to my channel, today we are going to do video number 13 of our maths playlist. Lead code number is 1359 hard but I will explain it in such a way that it will become very easy for you. It is important to understand that tuition is necessary, that I am definitely clear. I will do it in my video, the count is fine, the valid pickup and delivery options are fine, let's see what the question is to say that you have placed n orders and you must have given a value of , and there are two things in every order. given a value of , and there are two things in every order. given a value of , and there are two things in every order. Obviously you would know that in order to complete any order, there is a pickup and then a delivery. Example, okay, first one order, then the first order is picked up and delivered. Is there any other way to do this sequence? There is no other way to write, isn't the first one written dog, after that not the other one, how can you do delivery without first picking up, now first delivery is done and then there is some pickup, this will be wrong, isn't this wrong? The same way of writing the sequence means there is only one possible sequence of doing this order n = 1 order, means there is only one possible sequence of doing this order n = 1 order, which is what is p one the one is ok for n = 2 let's see the answer is ok for n = 2 let's see the answer is ok for n = 2 let's see the answer six. They think it's okay, so look, first of all, one way is visible to me that p2d2 is visible, second one is seeing this is also valid, after that what is p one p tu di one look, what else is there sorry then look. Understand intuition and see in general how to deal with such questions. See in general, such problems are very brain-wrenching because you do brain-wrenching because you do brain-wrenching because you do not have a direct approach in your mind as to what can be done. Either way, the worst way is to Let's take N = Ma, if way is to Let's take N = Ma, if way is to Let's take N = Ma, if you are there, then make one, okay one, make it of kar size, because what is the make of p1 p2 p1d2, okay, then make an area of ​​kar size, p1 p2 p1d2, okay, then make an area of ​​kar size, p1 p2 p1d2, okay, then make an area of ​​kar size, zero, one, three, first write p1 p2. d1d2 After that, take out as many possible combinations as possible, take out as many possible permutations as possible, take out as many possible solutions as possible, but definitely in the beginning, you can say that this bread force method will be yours, if you do not understand anything, then you will root. The first method you will apply is this, take out all the permutations and whatever valid permutations are there, how will you check the well permutations, see that if p1 is shown here, then story d1 should come only after p1, if it is p2 then story d2 should come only after p2. Okay like ma take a permutation of this ma take this happened t tu p tu di one to p one dikha di one later very good di tu dikha di u p2 so till now we have not seen it so brother this is a wrong permutation so This is what he is saying, you will have to take out all the permutations and check and that method will be yours, it is fine but we have to see what is the best way to solve it, see, I know how I have approached it, understand my thought process. Try this, how do I think about it, I saw such problems that N = 1 I saw such problems that N = 1 I saw such problems that N = 1 means p1 and one is given one, then I saw that okay, there is only one way, first you have to pick up and then you have to deliver. Clear, one was there because this is the only sequence possible. Right, one second is possible, so I write it here. Now coming for N = 2, I was asked that there must have been two orders p1 p2 and given one, you are right, there will be two orders. So there are two orders, that is, I write that N = 1 of order one, so I already know the answer, now one more extra order has come, the second one has to be adjusted, right here, it is okay, so see, let's erase it here. Okay and let's draw this clearly, either here or this, right here, let's reduce one, how many possible spaces do I have, one, this possible space is visible, how many possible spaces are there, three possible, after that I said that You can also put deto here, okay so p2 next it was p one it was this was last me di tu kar diya in the last space so three way a went if I had chosen this p2 to keep it okay good now ma I said no, if I keep p2 here, how many possibilities will there be if I drink, now I am writing p2 here in the middle, so I have written p2 here, I will do the same with d2, okay and there is nothing further, okay now. Can count, a total of six possibilities, I got 32516 3251 right, so why did it happen, think about why, understand, it was fixed, so remember, it could have been either here or here are these three ways, because three spaces were visible to me. 30 pages were visible ahead, so three ways were found, then when I said no, if we keep p2 here, then d2 could either be placed here, one or two ways were found, then look, if I said no, then what would be the total, we would get 5+4. +3+2+1 Yes, this is correct, I 5+4. +3+2+1 Yes, this is correct, I 5+4. +3+2+1 Yes, this is correct, I showed you that when you tried to select p2 here, how many spacecase children are there, for d2, one, two, three specials, added here, added. Similarity happens in the case of five. We can know the number of space in it. Okay, look, this is the time of first natural numbers. Remember, what is its formula? Remember N in N + 1 / 2 space account here. N in N + 1 / 2 space account here. N in N + 1 / 2 space account here. Friends, it is five plus one by you, till now it has been cleared, look at N = 2, we have taken out the look at N = 2, we have taken out the look at N = 2, we have taken out the total, its difference was six, so we have taken out six, now you will come to N = 3, otherwise one more now you will come to N = 3, otherwise one more now you will come to N = 3, otherwise one more important thing will be cleared, look ahead, now look carefully. There are two very important parts, now you are going to understand, okay for N = 3, then remember okay for N = 3, then remember okay for N = 3, then remember we had calculated for N = 2, so remember we had calculated for N = 2, so remember we had calculated for N = 2, so remember what I said and saw how much space is there, then second. I had placed the order there, so when I have to remove it for N = 3, I will see when I have to remove it for N = 3, I will see when I have to remove it for N = 3, I will see what are the possible options for N = and I what are the possible options for N = and I what are the possible options for N = and I will put the third order in it. I will try to do so. For N = 2, brother, try to do so. For N = 2, brother, try to do so. For N = 2, brother, six. I can see 6%, so first I am six. I can see 6%, so first I am six. I can see 6%, so first I am laying down one, after that people will see the others. First, I have placed this one on p2d2, is it okay, I am writing p tu di tu p one di one is okay, how many spaces are possible in the third. For the order, there is talk of third powder, one, two, three, five, there is talk of third order, because I have taken out up to N = 2, here are so many, so I have taken out up to N = 2, here are so many, so I have taken out up to N = 2, here are so many, so I am picking all of them one by one, first. I have picked this, okay look at it, let's see a way to place the two orders, one, two, three, five, it is visible, you can find that too, see, it is working on the formula, is n't it okay, you subtract one from it. Multiply it by 1 then do plus one and see, the number of space will be calculated. It is simple maths and is based on observation or pattern or you can also find it. If you look at more examples, if you look for N = 4 If you look at more examples, if you look for N = 4 If you look at more examples, if you look for N = 4 and if you look for five, then you will get the count of space. You will know if you are not able to find it, then look and what is the value of N? Three is three minus one, you are 2 * 4 + 15 A. Look, the number space is five, so * 4 + 15 A. Look, the number space is five, so * 4 + 15 A. Look, the number space is five, so now we can find the space also. Very easily, is this every Yes at the place, see here also how much space was there in N = 2, see here also how much space was there in N = 2, see here also how much space was there in N = 2, remember there were three spaces, let's see Neither 2 - 1, it becomes 1 * 2 + 1 3, remember there were 3 spaces, Neither 2 - 1, it becomes 1 * 2 + 1 3, remember there were 3 spaces, Neither 2 - 1, it becomes 1 * 2 + 1 3, remember there were 3 spaces, see, it is correct. I mean, it's okay, the space has been taken out, it's good, now let's move ahead, just remember, I have only read this, I have to pay attention to this, I am seeing how many possibilities are there, okay, so let's see how many are possible, I have found only 15 ways to insert the third order. For this, only 15th date is taken out, just for this, then this is also long, so here also there are five spaces, for this also 15th date will come, then for this also there will be 15 ways, 15 for this. How many times did we add 15? We added it six times. Remember, what was the addition of six? What was the answer for n = 2? times. Remember, what was the addition of six? What was the answer for n = 2? times. Remember, what was the addition of six? What was the answer for n = 2? What was the answer for n = 2? It was six. What was the answer for n = 2? It was six. What was the answer for n = 2? It was six. And for n = 3, when I And for n = 3, when I And for n = 3, when I came out with a special formula, 15 was applicable for this. Application means as many results as there were N = 15 * 6 = 90 ways, it should be like this, what was the answer of N, one was one, six, one, okay, great, I wrote it here, I tried to solve a pattern for N = 3. great, I wrote it here, I tried to solve a pattern for N = 3. That is, 15 is fine as per the space, so there were 6 possibilities in N = 2, then 15 so there were 6 possibilities in N = 2, then 15 so there were 6 possibilities in N = 2, then 15 sixes, 90 total, with 90 possibilities, it is fine for three. This thing is very important for you to understand that how and why multiply in the result of N = 2. It is understand that how and why multiply in the result of N = 2. It is understand that how and why multiply in the result of N = 2. It is important to understand one thing, why multiply? Many people get confused as to why they are multiplying. It is very important to understand this thing. I am repeating it again. Look, I had raised this. There are 6 total possibilities of N = 2. Look, I had raised this. There are 6 total possibilities of N = 2. Look, I had raised this. There are 6 total possibilities of N = 2. Here I had taken it out and saw how many ways are there to put the third order in it. It turned out that there are 15 ways to put it in this too. There would be 15 ways to put it in this too. So what was the total. Here there were six and 15. * 6 = 90 will be what was the total. Here there were six and 15. * 6 = 90 will be what was the total. Here there were six and 15. * 6 = 90 will be written, this is clear till now, this thing should be clear, you should know the reason of each and every thing, why multiplied here, I know why I was wrong in the beginning that this is a question of Math because as soon as I saw that okay, here there are spaces, number of spaces and I have to adjust the chapter on spaces in my maths, there was such a thing that there are so many empty spaces, if you have to fill something in it, then how will you fill it, the question is from combinatorics only. If that is okay, then in such questions always understand that DP, don't think about anything, always think in terms of mathematics. If it is okay in such questions, then you see, our problem has become very simple, so its solution will also become very simple, you know this. That is, if it is equal to one, then the answer will be one. First, I am writing in the result that yes, I know the answer of N = 1. What was yes, I know the answer of N = 1. What was yes, I know the answer of N = 1. What was one? Now I have to find out the answer from where to where because N has been asked. Please attend, friend, how much space will there be, the formula of space, I had come to know that by doing N - 1 * 2 + 1, the I had come to know that by doing N - 1 * 2 + 1, the I had come to know that by doing N - 1 * 2 + 1, the formula of space comes out, how much space will there be, okay now it is clear, after that whatever comes. Also my possible result will be, not the result yet, that means for now, remember the time, how the current possibility was found, the current possibility is ok, 15 was taken out, 15 and remember what was the answer of the previous one, it was six, every one, there are 15 possibilities for six, this is For everyone's sake, multiplying those six by 15 is fine. It is possible that the value may be a very big question. It is also saying that apply modulo mode because a very big value will come. You can enter it easily to understand this. I am telling you till here, that is why I have to say each line, you should know the meaning of why the space was taken out, how much will be according to the current possibilities and why it was multiplied here, you should also know this in the result which I have explained above, now your For this, I am giving a small exercise as to why the formula for space will be the same, you can derive it yourself, if you think a little then you will understand, it is okay, this is an exercise for you, otherwise I will put it in the comment, which will help in the butt due to doing the exercise. You had to understand that, you have already understood, do a small work, this is a five line code, it is finished, okay, quickly let's finish and finish this code, so let's start, it is quite good but you should make it once. Otherwise, without making such a question, if such a question does not come new in the future, then it cannot be made. Generally, it is okay, you should make this type of combination first. Okay, so let's start. We have given a very big value in the question, so first. I am taking the power of 1 A in the same module, it has been said to take 9 plus 7 modular, here it is okay, it can be a very big result, if it is equal to one, then the answer is going to be my one, okay return band. Given here, ok, what do I do after this, long result is equal, you keep one here, whose answer was n = 1, one is neither, then the n = 1, one is neither, then the n = 1, one is neither, then the result of last n, I have started, now in time = where to start What has to be done is to find out from tu to i time = where to start What has to be done is to find out from tu to i time = where to start What has to be done is to find out from tu to i &lt;= n till &lt;= n till &lt;= n till i++ i++ i++ ok, first let's calculate the count of space, what will be the account of space i - 1 what will be the account of space i - 1 what will be the account of space i - 1 * 2 + 1 ok, whatever is the value of n, do * 2 + 1 ok, whatever is the value of n, do * 2 + 1 ok, whatever is the value of n, do minus one tu plus one. Okay, now let's see the current possibility, how much will be the result in this possibility * They have this question was a very good question, if you have doubt then comment area Ultra Next Video Thank You
Count All Valid Pickup and Delivery Options
circular-permutation-in-binary-representation
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1. **Example 2:** **Input:** n = 2 **Output:** 6 **Explanation:** All possible orders: (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. **Example 3:** **Input:** n = 3 **Output:** 90 **Constraints:** * `1 <= n <= 500` Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1.
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
Math,Backtracking,Bit Manipulation
Medium
null
1,356
Hello everyone welcome to my channel Codesari with Mike, so today we are going to do video number four of our bit manipulation playlist. Okay, the lead code number is 1356, it is easy, that is why I have kept it more informative, meaning you will learn more extra things from this video. What do we learn? The name of the question is Sort Integer Sort by the Number of One Bits. Ajan has asked this question. It is a very simple question. You have been given an Array of Integer Sort. You have to sort it in ascending order by the number of ones. In their binary representation and in this case, if any two numbers are found whose number is one, if they are the same in their bit representation, then it is okay to sort those two numbers in ascending order. Let us see the example here. As if I were assuming that this was your input, I have just done the binary representation of everything and have written it. See how many one bits are there in the binary representation of five. Two, here one bit is one. Here one bit is two. Here one bit is one. So in ascending order. The one who has the least one bit will come first, so who has the least one bit, this and this, both have the same, but one is one, so what to do in that case, we will write in ascending order, first we will write two, look, it is two. First after that we will write 8, okay after that, look at this, they have two one bits, okay, so first we will write three because three is small, I said to write in ascending order, then after that we will write five, okay so it is the same. It is quite simple. Now see, before we start we should know how to write a Comparator and Lada for Sort Utility. Look, I know that you are going to use the sorting function, you have to sort utility, I think in all. It happens in C+, it is also in Java, you happens in C+, it is also in Java, you happens in C+, it is also in Java, you can use it directly, okay, earlier it was very simple, we used to do it in ascending or descending order, but here we have to sort in a different way, by number of one bits, okay. So the obvious thing is that we will have to write Comparator or Lada. Okay, so we will learn how to write it today and will understand it in great detail. Everything is fine. So it is very simple. All you have to do is write it, you just have to sort it. From beginning to end, but if you want to do it in a different style, then you write 'Lada', there is no Comparator for that, you either write 'Lada', there is no Comparator for that, you either write 'Lada', there is no Comparator for that, you either write 'Lada', 'You do the sorting in my way, write 'Lada', 'You do the sorting in my way, write 'Lada', 'You do the sorting in my way, okay, so I will write 'Lada' here now and explain the whole thing by writing. write 'Lada' here now and explain the whole thing by writing. write 'Lada' here now and explain the whole thing by writing. One thing is fine, so let's start writing the code. Here, first of all, let's write what is the return type of our code expression. Then I leave it to the compiler. Let's write auto. What happens by writing auto? The compiler itself deduces what the return type will be, otherwise you can also write the boolean, because we are going to compare, it is there inside, so I have written auto and left it to the compiler, after that the name of the argument is there. You can see the name as my function or anything, I generally write Lada, whatever I have written here is fine, this is your return type, this is my name Lada, whatever you want to keep is fine after this. We give it equal to OK, now pay attention to the very important thing here, you will understand that this is a capture clause. What is the meaning of capture clause? Understand what it means. I am writing here that capture clause means that if the value Let us assume that you have defined any variable or any data structure outside Lada, whether it is a vector or anything else, you can capture it here so that you can use it inside Lada. So let's say. There is int a, so if I write a here, then I can use a within this thread. Okay, and if you write this and a, it means you are taking a by reference, is n't it extra? Copy will not be made, hence only reference is taken. Generally, if you take by reference here then if you make any change here, if you make a = 5 then the same make any change here, if you make a = 5 then the same make any change here, if you make a = 5 then the same exact change will come in it too, this will also become equal to f. Okay, so let's call it Capture clause is fine, if you leave it blank, it means nothing will be captured. Okay, generally I leave it blank. Okay, have you understood what this is your capture clause, so I am underlining it. Capture clause is fine. What was your return type? This is the name of your Lada which you have given. Okay, after this comes the actual expression of Lada. Okay, how do we write the expression of Lada like this? Okay and open bracket, close bracket and here. Semicalculus is fine, now look pay attention to this part, it takes parameters. Okay, here I write the receive parameters. Okay, that means whatever parameter you have to take, whatever you are passing here, int A, int B. And so on, let's say here you are seeing the whole 'Hey, isn't it? Hey, you have passed 'Hey', so what will it do internally? here you are seeing the whole 'Hey, isn't it? Hey, you have passed 'Hey', so what will it do internally? But what will I do, int a, int b, I have taken two numbers, they will be compared, only then sorting will happen, so I write end and end here so that a copy is not made by reference, I prefer passing the parameters, so this is my parameters. And these curly braces here define the Lada expression, meaning this is your body, okay, now do whatever you want to do inside it, now remember when you wanted to sort in ascending order, hey, what did you check brother? a If it is less than b then it is okay to return true then it was sorted in ascending order ascending and if you had to do this in descending then a was greater than b then it was okay it was descending but this time we did not like that What we have to do this time is how many number of bits are there in a and b and we will find out the count of one number of set bits count of one in a so I will write a function and take it out from there ok find one bits count one We will write the function and send it to a there, it will find out how many bits are counted in this a, it will take out and give the similar count of one, this was in a, this was in b, let's take out the count of one bit, we will call the same function in that b. If I pass it then how will I know how many number of one bits are there in both of them. Okay, so it is given in the question that if we take it as C, we have written a very big variable. Let us take it as C. Okay. If the count of one bits in A is equal to the count of one bits in B then remember what is said in the question that brother please sort it then what I will say is ok A lesson B which is smaller will come first i.e A lesson B which is smaller will come first i.e A lesson B which is smaller will come first i.e in ascending order. Sort it okay and if it is not so then what do I have to do whose count of one bits is smaller will come first C take C B okay ascending on the basis of count of bits is Na bits Now see if this which is the count of A It means that if the one bit in A is reduced then A lesson C will be returned to C and B will return true. Okay, if it returns true then first it will take A, whatever is the sorting, after that it will take B. Okay, till now it is clear. So this is what we have written our lda and we just don't have to do anything, in short look at this lda, I have called it, I have passed the lda parameter, okay, it was quite simple, now here you must be seeing that I have called a function. Well find one bits count means now I just have to do one last thing that brother find the count of one bits in any number and write its function ok this is also very simple which will give me the number of one bits in number ok so First of all, let's start by counting int. Count is equal to 0. Now look, it is a very simple method. Almost many people would know this thing, but now I will teach you. Let's assume there is some number. Let's take your value and it is 10. How many number of one bits are there in it? Is it one or three? Total, so I have to find out the value of how many number of one bits are there. So look, know what I will do. I will simply take one and end operator. What is one and end operator one? 00 This is one, isn't it? If you take one to AND operator, then see what answer will come. 0 Okay, what is the benefit of doing one to AND operator, otherwise all the rest will become zero and look here, the last bit, this one and this one will get one. If you get it then see what is its value. If you get one, okay then if you get this one, what does it mean that the right most bit of this number was the one, that is why this and this together gave one, so count one bit. I took it, okay till now it is clear, now see what I will do, this number was mine, first I will hit right shift on it because this one's work is done, I done, this one's work is done, I counted from this one and then take butt. Now if I shift right then see what will happen, this one zero will come here this one here then zero one is ok and zero will come on the left side it is ok to be pad Shifted right how to do right shift Nam by doing like this Let's do it, okay like this, the right shift will happen. Okay, now we have done the right shift, now our number is done, we will do the same again, take one from the end operator, this is what happens, right, take the end operator, look, all these are zeroes. Will go because it is zero but will be saved, this last digit is zero and one is zero, what does it mean that the bit here was zero, okay, if there was not one bit, then we will count, otherwise the count is still mine, look at me. What is one's one is one bit 's count is one, 's count is one, 's count is one, okay now again which was my Nam, let's right shift this again, then see what will happen Nam is equal to two yew will come here and this one will come here, okay this is zero here. OK, again let's end with one, 10, OK, so 1 has come, the rest are all zeros, so here if the answer is one, it means I have got one more bit, I have got two bits, OK, again right. Will shift, 001 will come, my name is right shift, so it is ok, it is gone, right shift again, take one to end, will it come, see what is it is one, meaning this one was definitely one bit, its ok. Again got another one, now if you shift right then see what will happen, it will become 00 G, okay if it becomes zero, then stop now, look, now it becomes zero, if you shift right, now stop, okay now? The story is over, so see how many bits have we counted. So, we have counted three bits and it is correct. Look, what was our reason number, this was the slogan, tap number, this is how many bits are there in it. If one has three bits, then simply right. By taking shift from one to end, we can easily get one. Okay, think about what will be its time complex and I will show you further. Okay, what I said, I will keep taking right shift till the number which is not equal to two. Okay, till it becomes zero, I will keep taking right shift and how will I count? What did I tell you that brother, I will take the simple and moist one and will take the end operator from one. If the one comes, it means one bit. If it is right most then I will add it to the count because only one will come, count plus equal to nam and one, if one comes then the count bit will increase by one, ok and I have to right shift nam also. Keep doing that then. Till not equal to zero, story ends, what will we do from here, return count, okay, so see, we used this function in Lada, what will it give me, count bit one, okay, now look, give time complaint here. You see, I am iterating over all the bits of any number. Let's assume it is 10. So once I have seen it is one. Well, I have counted it. I have looked at this. I am looking at all the bits. So, how many bits are there in any number? It is possible that in binary equation there are log of num to the base two. If there are so many bits then how many times will this while loop run, what will be its time complexity of log of num. Okay, remember from where we were calling this function, we started from here. We were calling from Lada, here it is ok and we have passed the sorting here, so it will take n for sorting, it will definitely take place, but look inside Lada, we are calling it every time, which is taking so much time. Log of Nam to the Bastu, so the overall time complex will be so clear, you will get to learn a lot, it is an easy question, but you have learned a lot, you have learned the complete details of it, then how to calculate the count of one bits in a number. We have also learned it is clear to you till now and you have also understood the time complex very well, now let me teach you one more thing, my approach to this is the first approach, it will be submitted and it will also be accepted. Now you are seeing here that I have written a separate function, I had to work very hard here, right if he says in the interview that can you do it without writing this function, that means any other better function which you know, if you know any. If you know STL or know anything then tell me yes I know an STL which can give me a more efficient count by calculating one bit count which is my approach to see what happens in c+ p Underscore see what happens in c+ p Underscore see what happens in c+ p Underscore built in pop count One, this is a function, call it directly, pass any number in it, you do n't know what it will do to you, how many bits are there in one bit, in its binary representation it will give you immediately O of one time, remember this it is independent. Of the size of the number, it will give you in one go, you will find the details there, it is ok, it is clear to you that the built in pop count can directly give you the number of numbers in one time. Off one bit sets is similar to C plus, similar to what happens in Java, it is like this in Java, yes, integer zero dot bit count, you will also pass num in this, it gives you how many numbers in O off one. There are off one bits, okay, so what will we do, we will try to make it in both the ways, that is, here I have already written my function which will calculate the count of off one bits, but I am saying that you can use that also here. I will take once the underscore built in pop count and integer cow bit in Java, both are approachable. You do not use this function and use the underscore built in popcon. If you remove it in offv, then all the operations here are offv only. So okay, so we did not take extra time in the log, this time remember the last time, the log off seemed moist because we had written our own separate function to extract one bit but here it will be in the offv, so in this case approach two is the approach. My time completion in 2 is n, it will seem like the overall time complexity because this time the log off number which was supposed to be found has not been found, I have taken it out in wow, so let's code with both the researchers and finish it, so let's quickly. Let's code it with the explained method, we will do it exactly the same in both the ways, so first of all what I said was that we don't have to do anything, we just have to sort from the beginning of a RR till the end of a RR, we just sort in a different way. I have written my own separate lda, in the end I will return ARR only. Okay, now I am going to write lda. I am ok, it is auto return type. I have named lda as lda. You can name it anything, it is equal to capture. Claus parameter will be taken here Lda expression is ok so here int and a int and b will be comparison on two numbers ok int count of bit one bit a ok and I will write the function count one bits ok a passed Similarly, which is my B, we will also find out the count of one bits in B and here we have passed B. Okay, now look in the question it is given that if count of one bits in A is equal to I, equal to count of one bits in B If there are two numbers whose number of one bits account is same then brother go in ascending order ok in ascending order i.e. first A will ok in ascending order i.e. first A will ok in ascending order i.e. first A will come then B will come ok if A is lane B then first A then B after that if it does not happen So brother whose count is smaller will come first Count A Lesson Count B If it is true then A will come first B will come later If it is false Count A take B false then B will come first then A will come Okay so I fought this too Wrote the story ends here, what do we have to do now, we have to write our function, count bits is ok, count bits int number, this is also very simple, we had learned int nam equal to zero, sorry count equal to 0 until nam. I will keep going till it becomes not equal to zero, okay, you can write it like this also, the only thing is the same, okay, count plus equal to two, and one, I told you to do the end operation, okay, after that just Nam. Let's shift right to Okay and what to do in the last one is return count and that's it, we just have one thing here, you pay attention, this is inside the body of Lada, you called a function count one bit which is in the body of Lada. I told you that if you have to access something from outside then you have to use capture clause. Okay, so if you just write on m here, then who knows what will happen, whatever thing is outside the lda. Everything will be accessible by reference, so now if you call count one bits, then the error will not come. See, I will call without M and see if the error will come. Okay, that too is important to understand, so I try to tell you every detail. Look, here the error is coming, now here I give m but ok, now see it will be accepted ok because I used the external function inside lda, see it is accepted ok now see what I said that Count one bits were written separately, and this log off number is its time complex. Okay, built in underscore pop count. Probably something like this. Okay, let's use it similarly here too. From here, take out this in our O Offv. Will give how many number of one bits were set bits were see in our number the same exact java code will be accepted you will get it in the description of my get hub link is there any doubt raise in the comment section come try to help you out see you song next video thank you
Sort Integers by The Number of 1 Bits
minimum-number-of-moves-to-make-palindrome
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr = \[0,1,2,3,4,5,6,7,8\] **Output:** \[0,1,2,4,8,3,5,6,7\] **Explantion:** \[0\] is the only integer with 0 bits. \[1,2,4,8\] all have 1 bit. \[3,5,6\] have 2 bits. \[7\] has 3 bits. The sorted array by bits is \[0,1,2,4,8,3,5,6,7\] **Example 2:** **Input:** arr = \[1024,512,256,128,64,32,16,8,4,2,1\] **Output:** \[1,2,4,8,16,32,64,128,256,512,1024\] **Explantion:** All integers have 1 bit in the binary representation, you should just sort them in ascending order. **Constraints:** * `1 <= arr.length <= 500` * `0 <= arr[i] <= 104`
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
Two Pointers,String,Greedy,Binary Indexed Tree
Hard
1437
354
hey what's up guys this is sean here so today uh let's take a look at this problem number 354 russian doll envelopes uh i think you have some of you may know this russian though right basically so this is like a door inside another door right which is another dough so you have a number of envelopes with width and height given as a pair of integers with w and h and one envelope can fit into another only even only if both the width and the height of the one on one envelope is greater than the width than the other one so it means that we can only fit in one envelope into another one if the both the if both the height and the weight is strictly smaller than the other one and then it asks you to find the maximum number of envelopes you can you russian doll right put in put one inside the other note the rotation is not allowed so and here's some here are some examples so the first one is you're given like this envelope with this kind of like width and height and the output is three because the uh that's the three envelopes you can fit into each other basically three two you can fit in four and five because four is greater than two four i'm sorry 5 is greater than 2 and 4 is greater than 3. so that's 2 and another one is 6 and 7 right because 6 is greater than 5 and 7 is greater than 4. so if you guys watch it closely as you guys probably already find out right so basically this is like the two kind of like two strictly increasing sequence here right so first one is the width and the second one is the height i mean if you guys have done the problem called the longest increasing subsequences so this thing this problem is it's just like a two dimensional version of the of that the longest increasing sequence because both the height and the width they are like basically you have to satisfy that longest increasing subsequence in both of the in both height and width right so and i and actually this problem is a little bit similar than the than last week's weekly contest problem which is the i think it's called uh best team with no conflict something like that so from for that problem it's similar basically you have you're given like a team with the agent score and it asks you to find the maximum score without conflict so basically just similar as this one i mean so every time when you guys see this kind of like so the longest sequence longest sub increasing sequence uh longest increasing sequences with two conditions we need to satisfy right so this in this problem is a we have to satisfy both the height and the width so every time with this problem you just we just need to sort one condition first we sorted we satisfy one conditions and then we can utilize that longest increasing subsequence logic to get our the maximum value based on the other instant on the other condition here okay so for the uh so for those who still uh don't know the logic for the longest increasing subsequence basically for that one the basic logic for that one is we have a dp we have dp array here right so this dp array stands for the longest increasing subsequence this number at with this number as an ending number okay and then so what do we simply do this right we do a max of what max of the dp i right so max of dpi and the dp j plot plus one right if the number i is greater than the number of j so that's the lsi logic basically you know at each of the uh the ice locations we look through out numbers before i and then we find out all the numbers we for each numbers whose number is smoke smaller than the current i then we know okay so we have find the uh another validate of valid candidates that we can calculate our current dp right so it means that since this dpi my dpj is also strictly increasing since we have these like conditions for each of the dp so it means that we have dpi here right and then we have uh some numbers and then we have a db a dpj right because dp from zero to dpj this is increasing and since dpi is sorry since number i is greater than number j so which means that from 0 to dpi plus and to dpj this is also strictly increasing that's why this thing works okay so that's the uh that's the basic lis logic and we can just simply utilize that utilize this method here okay i'll give you guys this straightforward solution first but and then i'll be discussing another one another solution because for this problem if you're using this like kind of like the na the native lsi solutions it will tle so which means we'll need a better solution for this okay but let me try to implement this one first okay so like i said since we have two conditions we need to satisfy here right so we will be sorting at first condition we'll basically we'll sort on the uh we can sort out any one it doesn't really matter so we'll just store it on with first envelopes we do a sort we simply do a sort basically this was sort by the first condition right and then we have an end level here okay envelope and then we're going to have a like a dp so for we initialize all the values with dp with zero and with one because at each of the locations as you guys can see the this the envelope itself still counts at one so even though we can do a this russian dot twice but the total number is three that's why we start this thing with one or we can initialize everything with zero and then in the end we increase it we increase the final answer by one either way it's fine but in this case i'll just initialize with one so and then we have i in the range of n here right so now since we have already sorted by the uh by the width first so it means that the width is always increasing it no it's not inc it's always non-decreasing so that's why it's always non-decreasing so that's why it's always non-decreasing so that's why like i said for j here right so the j the range is from zero to i here and we need to check basically the envelopes i one that's the that's basically the height right the height is greater than the j's height then we can do about there's like a little there's a thing one more thing you guys need to be careful here because it says both the width and height has to be strictly greater so which means that even though we're sorting by the by not by the weight already but the weight could be the same right so for that case we cannot consider it's a valid candidates so which means that basically we have to do this zero okay so it means that the first one is the height but still we need to check if the uh if the width is not it's not the same because we have already sorted from sorted the width here but so here we're essentially only checking if the width let's let me do this yeah like this basically i'm only checking if the current width is now the same as the previously weight then we know okay so we can use this one to calculate our current j here right so it means that the dp i is equal to the maximum of the dp i and then from dpj plus one because so now we have find another envelope so that's why we can do another russian doll here right yeah and that's it so in the end we simply return what we return the maximum dp yeah so why is that i mean this is because you know if we have like a bunch of numbers let's say for the uh for the li lis right we have a numbers here like the uh zero one two 8 right and then 2 3 4 6 9 10. i mean basically the longest increasing subsequence could add any location it could end up here so that's the first increasing sequence and this is the second one which is which in this case the last one is our final answer but it's not always a true always true right so the longest subsequence could end up at any location so that's why we have to do a maximum of dp yeah so this thing in large in terms of the logic whites i think it is correct if we run the code yeah certainly pass but if we sub if i submit it will okay sorry yeah so of course we need like this if not envelope we seem to simply return zero right so let me submit one more time yeah so this means tle yeah so let me check the details how many yeah so it's almost past everything but it's still tle here so why is that because for the traditional lis longest increasing subsequence solutions this is clearly a o n square solution right and even though it didn't give you give us the range of the problem but seems like so this on square solution will fail then it only leaves out no other choice but to find a better solution which is the unlock and solution of this l i s okay so to do that let me try to explain these things here for you guys see we can have this hmm okay i'll just try to explain it here so let's assuming we have like a bunch of numbers i'm only trying to solve this uh is problem let's say we have a 0 8 4 10 2 6 9 11. how about this so if you're trying to solve this longest increasing sequence problem what is another way to solve this so a better way is this basically we're maintaining like a dp here but in this dp here we're only maintaining the current longest subsequence we are we can get by this position so what does it mean it means that in this dp here we're always maintaining like a increasing number so which means that you know for example we have a zero here at the beginning we have zero okay and at eight here we do and every time since we're maintaining like always increasing numbers here we can do a binary search to find the proper insert location for the new numbers here okay so and based on this location we'll would decide if we will replace update the value or we will append this value so at the first one zero of course it's zero at number eight here we do a binary search right so we do a binary search and then what values we get we got like we got a we got one here so one is the same as the length of this dp here right so it means that okay so the eight is greater than all the numbers in this dp here so that we will basically will append we'll append this number to the end of this dp here and now we have four right so we have four here so what's the uh what's the index if we do a binary search of four it's one right and then basically we'll update 4 here we'll update 4. so why is that because so why we can update 4 because you know four is great it's smaller than eight right because four is always smaller than eight because we're doing like the uh the binary search so it's always guaranteeing that the current the new numbers that we are having here will be this was either equal or smaller than the previously numbers at the same location and then we can re we can replace that so this is a little bit like greedy idea behind the scene here because we have find another number right which is smaller than the previous one so that this one may give us a better a longer subsequence so that we have four here and then the next one is 10 right so now the next one is 10 so 10 is what 10 is okay so 10 is another one so 10 is greater than that everything so that's why we append these things to the end okay and now we have two here so what's the index of two it's also one here because the two will be inserted into one so now what we do we update again right so we update one with two to ten and then what and then six right we have six here so six what's the index of six is two right so which will be here and it will be updating that two to zero six sorry 0 2 and 6 and then we have 9 here so 9 is greater than everything so we do a dp equals to 0 2 9 0 6 and 9 right and then the last one is eleven do the same thing six nine and eleven so basically so the present this approach in the end the length of dp will be our answer that's going to be 5. so as you guys can see now this business solution the time complexity will become n log n right because we look through everything n times but with each of the loop here we do a binary search which is a log and that's why this func this solution is much faster and the key observation for this pro for this solution is the uh you know this append is easier to understand but it's the most important part is this replace part basically you know every time when we have like a numbers we find the index here we will be replacing that number with the same index so why we can do that because we are still maintaining like the in the increasing pattern here right because we do a binary search we find the place for this slope for these new numbers and after replacing these numbers we know okay it still complies with this increasing pattern that's why we can replace that okay so with this in mind let's try to use this one for this problem right okay cool so for that you know let me try to come out the first one here i think we can come out here right we need we'll be needing those sort there so like i said you know we'll be maintaining like an empty dp first right and then we'll basically loop through the uh the width and height in the envelope and envelopes right so we'll first find the index of the we'll do a binary search for the current number which is the which in our case is the uh is the height right because we're searching we're storing this height in this dp okay and we're doing like the by the binary search uh sorry left sorry it's not right it should be left so why is that because the issue with doing a binary search left is because in case of the same numbers here right let's say we have another eight here we come after eight there's another eight we don't wanna append this eight because remember we have a condition right if the current index is smaller than the length then we do a replace otherwise if it's equal to the length we do a we do append and when there is a same eight here we want to get index one not two because with the left it will give us 1 but if we do a right it will give us 2 which is not what we want right so here so the logic like i said so if the index is smaller than the length of the dp okay then we do what we replace this dp index with the current h right elsewhat else we simply append dp append the current h okay and then we return the length of dp right so these things it looks pro this looks promising but does is this one correct with everything here no so why is that so this is because you know we are replacing these numbers right since you know we have for the one 1d like the regular lis after replacing here right we have all the numbers in dp still confirm uh i mean following the increasing rules here but here even though right even though we have like this w here we have w like increased already but if we're only doing this h here we have like we have this w we still need to consider here so i'll give you an example here um you know what let's so the best example is just to submit and this will give us the example here okay so basically that's the example we have we need here right so okay so if we sort by the uh by the width and then the height so what we'll have one right so that's the and then we have two three and then we have four and five right and then we have four and six and then we have six and seven okay so that's the sortings after that sorted the list and this is okay from one to one this is okay which means we will have like what let's see so in this case we'll have like dp equal to what since we remember we're storing this height in the dp here we'll have one three and then five right five okay so we have one three five and then what and then we have six right but can we use six probably not because we have this thing we have the uh we have this i mean this width we need to be taken care of because we cannot for this six here we cannot one three five we cannot add at six here because 5 and 6 they have the same width right so which means we cannot simply using this numbers here so we have to find out another way i mean someone might may think that the uh maybe we can like introducing another like a width dth array here which will be storing the direct the corresponding width for each of the height here and every time when we do this kind of index or either insert or update we check that width will not work either this is because you know so what every time when use when we update this height here will be uh sorry when we get the index for this height here we'll be updating the dp with this height and we're assuming every time when we update this height here so the both of the conditions will should still be maintained right but if we're doing that even though we have a the weight here it's it will never so the width the increasing pattern of the width will always be broken i mean you guys can try to do it i already tried so it won't work even though you're trying to tweak this width an update or where we checked if the width is smaller or greater and then you do append it will always broke it will always break the pattern so then it only leaves us one com one option which is to change the sorting a little bit so as you guys can see here so the issue happens right here when we do a four five and four six and the issue happens when we have four and four have the same width and then if we are sorting this height in the same increasing orders so we will process this four five first and then we'll process this four six what does it mean it means that even though the four are the same we're still considering this five and six are valid a valid increasing sequence so the easiest way to fix this is that we simply reverse these two sortings here so now we have one two three and 4 and the 4 6 right so if we follow the below logic here so we have 1 3 and 6 okay and now we have a 4 and five right so if we have four and a five here and we do it we do a binary search instead of three here we'll get two which is here so which means that so we will do up update this time and the length is still three so now the problem is soft so what which that means is we simply do a customized sorting here we do a key equals to lambda what x and what is the key so the key is we stored by x0 ascending order and then we do a sort by the second numbers descending order right so that's the sorting and that's how we fix this problem here okay so let's let me try to run the code cool so this thing works and submit yeah as you guys can see this one is super fast you know this is because the time complexity is now unlocked in here yeah and if you guys know how to solve this problem instead of doing a reverse sortings here if you guys can find a way of introducing some additional arrays to solve it i would love to know it no know that as well yep and other than that i think it is a great problem you know so the first one the first solution is the traditional dp solutions which is the n square solutions this one is pretty easy to understand right basically we try all the previously enveloped of course we need to sort first and then anyone that satisfies the conditions we can use that as a candidate and then in the end we return the maximum number and the second one here i mean in the interview i'm not sure if it will if the interviewer will ask you to improve your n unsquare solutions i think thirty percent of the chance it might happen so it's at least it's better to know there's like another way of using this dp basically we maintain like the dp arrays here and then we're using a binary search to help us to find the maximum length so this part i think it's not that hard to understand right basically the why this thing works is because first we're maintaining like a length right and every time when we find the smaller numbers we find the smallest numbers in the uh comparing with the previously numbers we update the numbers because we know that once we find the place for that right because basically we're replacing that number with this number because in later on we might find out like better a better different numbers based on this number right a greater number based on this number that's why we will do the update okay yeah basically we are as if we are finding a better candidate for this index previously we have an index uh at index eight here we have so at index one here we have eight so now we have four here so now basically the you know the uh we have better candidates at four here so why is that because we have a we have eight zero eight four let's say we have five and six so we have zero and eight we have four here so now we have four because four is smaller than eight which means that between four and eight later on let's say for you for example in this case right we might find a better solutions by using 4 as this at this index okay yeah actually speaking of that you know we might can we might also be able to use the uh amount of q to solve this problem you know something like this since we're getting the minimum the sorry the increasing sequence i mean every time when we have a new numbers here right we pop anything that's that is smaller than the current one and in the end that's the answer right so let me try that you know this might also work interesting let me comment out these things here so basically this is what i mean here while the dp is not empty right and dp minus one sorry or where the four is either or either the h is either small or equal than the dp minus one okay we do uh oh probably not sorry forget about that you know forget about that it won't work because for in this case we have a 10 and 2 here right but we don't want to pop this 10 out because that will give us the uh actually that may also work sorry because we can update the answers every time when we have a number here so which means we have answer here it's going to be 0. so we have a while loop here right while dp is stat and then we do a dp dot pop okay and then here i don't know if i'm doing something useful here or not and let's have dp dot append h here right and then we every time we do update we get a maximum of the answer dot the length of dp in the end we simply return the answer i'm hoping this will also work yeah accept it submit let's see okay sorry forget about what i said about the monocule just forget about it so it won't work here all right guys so that's it so stick with the uh the dp and this binary search solution here and cool thank you so much for watching this video guys stay tuned see you guys soon bye
Russian Doll Envelopes
russian-doll-envelopes
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_. **Note:** You cannot rotate an envelope. **Example 1:** **Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\] **Output:** 3 **Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]). **Example 2:** **Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\] **Output:** 1 **Constraints:** * `1 <= envelopes.length <= 105` * `envelopes[i].length == 2` * `1 <= wi, hi <= 105`
null
Array,Binary Search,Dynamic Programming,Sorting
Hard
300,2123
347
looking at problem 347 top K frequent elements just per usually the three steps implementing any problem are one understand it to visualize and then three implement it given an integer array nums and integer K return the K most frequent elements you may return the answer in any order you have an example we have one two and a three k is two so we want the two most frequent elements and just with the cursory look we can see there's three ones so that's the first one and then there's two so that's the second one and that should be your output example two is just a very basic example we have exactly one number k equals one we output one the constraints there's between 1 and 105 numbers each number is between negative 104 and 104. and K is in the range of between one and the number of unique elements in the array and it is guaranteed that the answer is unique and here we also have a follow-up your and here we also have a follow-up your and here we also have a follow-up your algorithms time complexity must be better than o n log n where n is the array size so there's uh two ways two approaches to solve this problem that I know the first one is using heaps the problem with heaps in for this particular problem is that it does have uh it is an o n log n time so you know it is a good algorithm in general and you know if the problem was just for finding the most frequent element then it would uh it would be faster but because it's top K and you know the constraint is that K is between one the number of unique elements in the array it is possible for it to just uh you know the end result to just be a heaps or algorithm uh where you just Traverse the entire area at which point it's n log n so with that in mind let's do the approach that's actually uh that can actually happen in linear time and so let's take a look at the numbers here so we have these one ones and here let's keep tabs uh since your frequency frequencies so we're iterating we see and let's see so one is starting off uh two is zero we have three numbers we're tracking uh number to frequency so we just iterate over each one that's one it's another one of those guys now for two we see one let me see a second and then three we see one so like this is just a do you need to do this like whatever approach you take you need to just you know count the frequency of each number and you know the question then becomes how can you um then in uh without sorting your numbers or your key value pairs in any way like still give out the K most frequent elements so that's where the magic happens and let's just uh let's first Implement what we've done so far of just getting our frequencies and then let's discuss how to just uh just return the K most freaking elements the map uh let's call this a frequency map just like we did a new map and then we iterate of our numbers just as we iterated earlier and let's see if uh brick map that has num like we've already looked at this number before we just add to it otherwise we reset it to one oh and then sorry uh that guy to that and then this guy to just one okay so that's how much we've reviewed so far in our examples and our visualization and now we have to think about uh this interesting JavaScript Quirk which revolves around how arrays are unbounded so let's look at um wait let's create an array I actually will create it over here I already is you know just an empty array and Let's uh let's take the frequencies and make these the make the indexes of the frequencies make the frequencies into indexes and then the values into these numbers and so in example one three so that's the frequency is equal to this one in the case here our frequency is two we make this equal to two and then our frequency here one is equal to the number three now look at how our array looks now so we've actually like expanded the array like we didn't have any problems we said now it's actually its length is now four and it has this you know empty value and we can take this property of JavaScript and what we're going to do is we're going to move all the frequencies uh we're gonna like do this exact same process of filling up an array with uh the frequency indexes mapped to their number values uh the one more thing is like imagine we also had uh four and four then we would actually see the number four is frequency is two and we see that these two overlap so you know zero one two units value is two we don't want to override it with four so we can use a different data structure instead of just uh a single number we can do a set and just uh have sets for each of these and that will solve so I can just show you with the set example looks that are is that then we would say R so start from beginning R3 equals new set add one then we hit look at the next guy our 2 is equal to new set add uh two look at the next guy the frequency is one R1 equals new set add three and then we look at the last guy so this is R2 so this guy already has a value so we can say R2 dot add four and oh shoot I didn't add to our oh you know it's okay like I created a new set but you can see I overwrote the previous area but you can see how it looks like so three then we have these two four and then one and at that point because they're already sorted from largest to smallest we can just go back until we've uh you know K number of elements and just return those and we are done so let's Implement what we just described we are obviously other frequency maps and we want to create our in our set array and we want to say or let you know key value of our frequency map if I set our if uh if this already exists then we can our value dot add key so that's exactly what we did down here uh we just added four in that case otherwise set r equals new set key dot add um oh sorry a news oh no it's just new set dot add key okay there we go and you can see what this looks like it should look the same as what we already did and what example do we run let's use uh this guy and there you have it so you have this three and then you know if I were to add the fours that we did in the second example oh uh I guess we can use that for this example but you can see that you have these sets so at this point we just need to iterate over our sets until you know filling up our result and return our result so we need to iterate K number of times and then we are out we're out of here for let I equal remember we had to start from the right hand side because the for the art to the right the larger number of frequencies you are set our I think minus one I is greater or equals to zero I minus so we say so remember that we have these empty items so we want to clear those guys out and there's no set r i just uh you know skip over that but now we actually do have a number so result dot push set r i and then we want to say if you know how have we already exhausted the K number of elements like how do I already have you know K elements in the array let's ask that question so that length greater equals to K you know we want to stop adding stuff to our area let's just call it quits let's see this guy runs to that path example cases submit okay and there you have it that's the first approach with the unbounded array approach now let's look at how we would solve this with a heap like a heap strategy so this is uh you know it won't perform as well but it's still good practice to know how to do heaps so as a reminder a heap is a data structure where it's an array but it's in when we think about it and treat it like it's a binary tree an example you know again if you don't remember so you know the array one two three four five six seven eight we represented as a binary tree so the first thing you need is a so the key element of a heap is a heapifying function and you know as a reminder like a big summary of what we're going to do is we're just gonna add our heapifying function that you know churns arrays into heaps as a reminder a heap is uh it could be their Max Heap or Min Heap uh this is an example of a mini heat because the root node is the smallest value Max Heap would be where the root node is the largest number we are going to do Max Heap because we're only really interested in we want to do a Max Heap where we where the numbers with the highest frequencies are at the closest to the root or at the root of the tree and so yeah we're not concerned at all with Min heaps only Max heaps and we need a keepifying function and all you need to do a heapifying function you need the array and you need the index value and you need to know how to uh you know grab the no what the left and right note of the tree is and you know so I won't describe this in all detail like if you're really interested like definitely check out our uh video on sorting algorithms using the Heap Sort algorithm so let me just uh assume you know that I'm just gonna write what we have to do I'm gonna try to not make this video too long times two plus one let's write equals left plus right that largest equals index we need uh to bound our Heap let Heap boundary equals uh so what will this be oh so we do need to know like how many unique items there are if you want to use the heapsort approach so let's quickly grab that so unique nums equals a frequency map how will you get that so we have I guess it's just uh frequency map that keys are the unique numbers and then we say nums the length and the reason we need the heat boundary is that as we like in any good Heap Sort algorithm at a certain point like you're going to be you're going to have your numbers at the perfect position like the largest number will be at the rate of the array and you don't want to accidentally run your keepifying function on that number and you know reintroduce it into the array so we need to set up like a boundary where our algorithm no longer runs to keep those numbers safe and locked in so if left is less than our boundary and free map dot get will this be that get uh our left is greater than freak map.get our is greater than freak map.get our is greater than freak map.get our largest then that means that we actually have a number that has higher frequency largest equals left and do the exact same thing for the right side and then you get Heap function would do if R just does not equal index then we need to do a swap let's define a swapping function left right temp this is just boilerplate stuff are right equals our left oh it should be the other right around and then our right equals temp and then I guess call that guy so we pass our array and then large is an index so we swap them and then we need to just uh check all the inner notes make sure that they're nicely humified as well because we did this change we need to compare against our you know the value that we swapped out so that's the hebify function and the only distinction here between here and the user algorithm is that we want to just compare the frequencies we don't want to get the compare the actual numbers because the numbers themselves aren't relevant and so at this point we're just simply just writing a heapsort algorithm it's just it's a two-step process the it's just it's a two-step process the it's just it's a two-step process the first step is to run the Heap Sort algorithm from right to left and that what that will do is that at the end of doing that the largest number will 100 be at the leftmost spot at you know index zero and then the second step is we take that value we swap it with the rightmost number and then we move this heat boundary down one to lock it in and protect it from ever being heapified again so it'll so we're basically we'll basically be sorting the uh the array and then we'll grab the K elements the rightmost side of the array and then call it quits for that I equals uh unique so we should at this point we should probably let me just uh let me just log this to double check something okay so let's actually make this a full array like we're done with treating it like uh like you know a different type of data structure let's just keep symbol with an area okay so for that I equals unique nums the length minus one so that'll be the rightmost number I is greater equals to zero minus then we need a Max heap of Phi array and our area will actually be unique nums and will be I so that will and you can see that the rightmost number will be the one with highest frequency left plus one and let me just hello yeah okay so yeah there's the one is at the rightmost side and two is there next so this is looking good and now we need to grab the leftmost number move it to the right and close down or bound and then so it's that for let I equals in terms of length minus one I is greater than equals to zero I minus so we want to swap unique nums we want to swap the left and right zero with I and we want to close down our heat boundary and then we want to because the numbers may have changed and like that rightmost number is necessarily at the right Heap spot let's hipify that guy nums zero and then we can just return unique nums that slice pick numbers of length minus k and let's see how that does that example I think the other these examples and there you have it we have implement this with a heap and we have implemented this with uh using an unbounded rectangle strategy so thank you and catch you later
Top K Frequent Elements
top-k-frequent-elements
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\], k = 2 **Output:** \[1,2\] **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `k` is in the range `[1, the number of unique elements in the array]`. * It is **guaranteed** that the answer is **unique**. **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
null
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
Medium
192,215,451,659,692,1014,1919
1
what's going on guys welcome back in this video we are going to be solving leap code problem number one Numero Uno and it's going to be the two sum problem so get excited guys let's go ahead and jump straight into the code so let's get started by checking out the prompt guys so they're going to give us an array of integers and a Target and they want us to return the indices of the two numbers such that they add up to the Target so really quickly it's pretty straightforward if we just look at this example in this array here the reason we get back zero and one is because two plus seven equals nine which is our Target and 2 is at index 0 7 is at index one in our array and they explain it down here and then you know down here we get back one and two because two plus four is six and two is at index one four is it index two so it's pretty straightforward so with that being said let's just go ahead and hop straight into the code so the first thing I notice guys is that the problem is asking us to return an integer array so what I'm going to do to start this off is create that array and we know it has to be an integer array I'll call it result and then down here at the bottom we're just going to return that result and we know that in order to solve this problem we just need to go through this numbers array that they give us and see if we can find values A and B such that a plus b equals our Target which we can call C or something like that so I'm just going to add that as a note here in my problem trying to find two numbers such that a plus b equals c okay so the easiest way to accomplish this would be to use nested for loops and what we could do is start let me just go ahead and get my array copy and paste it over here so we can take some notes with it let me just create a multi-line comment here as well create a multi-line comment here as well create a multi-line comment here as well and paste this in here cool so this is our array so I'm going to put seven at the end guys and put 15 right here just to illustrate this concept a little bit better so basically we would start one loop at two and then within that have another loop that goes and checks every number after two and we would just have some logic in there that says hey if any of those two numbers equal the target then we know we can return the indices of those and solve our problem so let's go ahead and just code this out so basically we would say 4i in 0 up to nums.count nums.count nums.count so this would start our Loop here at the first end of X the first index of the array then we would want to check every number after that within this iteration right and then we would go to 15 and check all the numbers after 15 then go to 11 check all the numbers after that so that's where the second for Loop comes in and here's the trick to this we would say 4 J in I plus 1 up to but less than nums.count so what this does is it's nums.count so what this does is it's nums.count so what this does is it's going to take a look at what I is at the time right so it starts at zero then it's going to start this second loop at one because 0 plus 1 is 1 and it's going to go to the end of the array and at each point we're just going to check and see if any of these guys plus 2 is equal to our Target so we would say if nums I plus nums J equals Target then we would just say return I comma J so you guys could also say results equals I J which we can do for now and we can discuss why the other way is better in just a second let's just go ahead and run this to see if it works so we notice that this does solve our problem right but this is not the most optimal solution for this problem so we're going to go over how to optimize this version of it and then create an entirely different algorithm to solve this program or this algorithm in a way more efficient fashion so to illustrate why this is not the most effective way with the Brute Force approach guys I'm just going to add a print statement here so I'm going to say print and let's just print out the result of num's eye plus nums J so if I run my program we'll see that I get a bunch my program continues to run even after I found the correct solution so you guys will notice that I get a bunch of print statements here right but the correct answer here is nine so all of these additional Loops or iterations of my Loop that I did were completely unnecessary so I'm getting the right answer but it's not the most efficient way of doing it so basically what I want to do is as soon as I find the two numbers that satisfy this condition I just want to return those numbers so we're sorry the indices of those numbers and this way as soon as I find my solution the execution of my program will stop right then and there so let me run this again and you'll notice that we get back a single print statement and it's just going to be nine so yep that's all we get back and you guys notice that we didn't get back all of those other print statements because our program stops as soon as it hits this guy so to illustrate this a little bit better I'll change this around where I put seven at the end of my test case so you guys could just go to the test case tab right here and you could customize this to have whatever test case you want you guys will see that we get back you know a couple more print statements but it's still a more efficient solution so at first we get back 17 then 13 then none and then we stop because we found our answer so that is a good way of optimizing The Brute Force approach but the Brute Force approach in and of itself is not the most optimal solution for this problem it's in fact the worst way to solve this problem so if we were to look at the Big O notation or runtime complexity of this on this chart here we would be in the O N squared time complexity and that's because we have to use that nested for Loop and essentially visit every element in the array twice basically so we are at O N squared so we notice that as my array gets larger my time complexity significantly increases which is very bad we can solve this problem in o n time which you can see is way more effective than O N squared right this goes parabolic in terms of its time complexity and we can see that it is terrible right so this guy is fair which is what we want for this problem so let's talk about how we can accomplish this well we're going to be using something called a map or a dictionary and basically what we can do is use it as a lookup tool to see if we can find the complement of this equation right so imagine we are looking for a number B such that a plus b equals c well we could say that hey if I have B which equals c minus a right this is what's known as the complement of B and we can store all of those values in a map to look it up then we know that we have solved our problem so that's what we're going to be doing to solve this more efficiently guys so let's go ahead and code it out and then I'll break it down a little bit further because I know that sounds a little bit confusing so let's go ahead and just delete all this code or you guys could comment it out if you'd like but basically I'm going to create a map here and it's going to be an integer to integer dictionary so basically we're going to have this key value store and it's going to store an integer as the key and have an Associated value as the key so we're going to go over how to populate this dictionary in just a second so if you guys are uncomfortable or unfamiliar with dictionaries I highly recommend checking out a video instructional on maps and when if you're watching this in the lead code killer course I will have a video posted on this in the data structures intro section but if you guys aren't comfortable with maps or how to use them I highly recommend checking that out so anyway guys let's continue with the solution to the problem we're still going to need to run a for Loop here so we're going to say 4i in 0 up to nums dot count and what we need to do is store the complement here in a value so I'm going to say let comp equal Target minus nums I so now that I have this complement value right so I'm going to Simply do a lookup in my dictionary and see if I can find that value in my dictionary and if I can return the associated value with it which in this case will be the index of that number so I'm going to say if let index equals map comp return I in the index and if we can't find that then we just need to make sure that we actually populate this map with the correct value so we're just going to store num's I and its Associated index so I'm going to say map nums I default zero equals I and you guys will notice that this is going to solve our problem too we just need to add a return statement down here so outside of my for Loop just go and say return some blank array so if we obviously can't find any two values that satisfy this condition we would just return a blank array so let's run this and see if it works so we guys know you guys notice that this works as well so what I want us to do to break this down guys and make it easier to understand is actually add some print statements here so we can see what's happening at every step of the problem so first thing let's comment out this return statement just so that we can see what's happening at every iteration of the problem and below this line here where we set up where we populate the map with values let's go ahead and say print comp is comp and then let's print the map as well and then let's just print out like a line with a bunch of dashes to get some separation here and let's run our code and talk about what's happening line by line so this is our input array guys remember we modified it slightly from what we got back in the example we just put seven at the end to make it more interesting but let's go ahead and just scroll down and take a look at all these print statements which is really going to help us make sense of this solution so we're just going to break this down step by step so basically we've created our map here and then we start looping through our nums array right and we store this complement in a value which is equal to Target minus nums I and if you guys remember the logic we're trying to find two numbers such that a plus b equals c so the complement of B would equal C minus a and on the flip side the complement of a would equal beam or C minus B so that's what we're storing here right in this complement value so here we see that the complement is seven first up because 2 is the first value in our array nine minus 2 is 7. so this piece of code that comes up next is very important guys so what this is doing is trying to look up the complement in our dictionary because we know that if the complement exists in the dictionary that we have solved our problem because we have seen that number before which is the number that we're looking for right we are currently looking at 2 the complement is seven so if 7 is in my dictionary I know I've seen it before and 2 plus 7 satisfies the conditions of my problem it equals nine so I'm trying to look that up and see if it's in there and it's not because there's nothing in our map so then we go down to line 12 where we actually populate our map with a value so we're saying hey in the future if we ever see seven again I just want to look up and see if two exists in the dictionary and give back this Index right here which is the location of two in the array which is what I need in this situation right I need to know if 2 is in the dictionary and if it is what index that it's at because that's what the problem's asking me to return the indices of the values that add up to my target so that's why we get back the complement is seven and then currently our map is 2 and 2 is at index 0. so then we move on to the next value right the complement is negative six because nine minus 15 in this case is negative six and then we try to find that in our dictionary and we obviously can't because um the complement of that doesn't exist in our map so it just stores 15 at the one index so we keep going same thing happens for negative two um or sorry when the complement is negative two and then this is what our map looks like 11 is at index 2 15 is at index one two is at index 0. and here on this last iteration is where we actually solve the problem right so let's break this down because this is the key to understanding the solution so we are looking at the complement here right what is the complement of seven such that some number plus seven equals nine well it's two right so in this case the complement is two and when we go to look that up in our dictionary in this case we have two in the dictionary so when we go to do that lookup it says oh hey dude 2 is there and that's exactly what you're trying to find because in relation to the number seven and the number nine two is the value that we need and we need the index that it is located at in the original array of nums so we find that value and then this gives us back the index of it right that's the value associated with two and then we stop there and we return I which is the current index that we're on in the array which is seven and we needed to look up and find two which is in our map and it's at index 0. so this would return three and zero and luckily for us guys we can return the numbers in any order so we could return it a zero one or one zero it doesn't matter so really quickly just to make sure this works with all text test cases guys go ahead and delete that and let's uncomment our return statement and let's just go ahead and hit submit and see what this gives us back so we notice that does solve our problem and the numbers look really good here right guys it's better than 91.72 percent of all Solutions in than 91.72 percent of all Solutions in than 91.72 percent of all Solutions in terms of runtime and beats 86.4 in terms of runtime and beats 86.4 in terms of runtime and beats 86.4 in terms of memory so that is going to wrap it up for this video guys that is lead code problem number one the twosome problem we went over how to solve it in a really good way and a really bad way and went over the differences between the two so hope you guys enjoyed this video we'll see in the next one peace out
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
6
hi everyone let's all today's daily challenge that is zigzag conversion so in this question we are given a string and it is written in a zigzag pattern on a given number of rows like this right and then what we are doing is we are taking the first row of it and then after the first row we are appending the second row and to that second row we are appending this third row so we get a string like this and that is what we have to return so we have to write a function in which it will be taking a string and then it will be creating such a pattern a zigzag kind of a pattern out of it and then we will consider all of its rows right and we have to Simply return a pattern that we will be obtaining after reading this pattern row by row so let's understand uh what this exact pattern in this question means so in this question the zigzag pattern that they are considering is like this right so we will have something like this so this is the zigzag pattern that they are considering so let's uh try to understand it for n is equal to 3 what this exact pattern is so when n is equal to 3 we will be having 0 1 2 3 rows right and within these three rows we have to form this exact pattern so how will we forming this exact pattern so we will consider p a y along this and then we have to fill this diagonal so we will fill P here right and then we will fill out a l i then again we have the diagonal so we will put s here and then we will consider h i and R and then we will have um I here and N here and G here right so this is the zigzag pattern that will be forming okay now what we have to do we have to take its rows right so we will take phn then we have to take this a p l s i and G and then we have to consider the third row and we have to append it to our resultant string so this is what we have to return right so now um let's do it for n is equal to 4 so that things will be more clear to you now we'll do it for n is equal to 4. now our n is 4 okay so how do we have to form this exact pattern you have to form this exact pattern like this okay so first we'll place so we have four rows here 0 1 2 and 3. so we'll Place p a y and p here and then we will have a L along the diagonal then we will have I s h and I and then we will have R and I here and n and G here right so this is the pattern that we will be forming and then what do we have to take row wise character so first we will have p i n then we will have a l s i g then we will have y a h r and then we will have p and Pi so this is the resultant string and that is what we have to return so I hope you uh you are clear with the zigzag pattern that we are considering in this question so let's see how we will solve it so uh let's see how will we get the first row if you try to evaluate that how will we get the first row so we have P right so how many characters do we have to skip to get to I right so it will be 1 2 3 4 5 and 6 right so the sixth character we have to take right then again one two three four five six character we have taken from here how many steps do we have to take one two three four five and six so we will get n right so this is how we will get the first row right let's see for second row if we check for second row what we'll be doing will again be doing the same thing will come to a now and from a how many steps do we have to take so if we take uh six steps where will we reach so one two three four five and six right so at the sixth step we have S right then after S one two three four five and six we get G but what about L and I they are also in this row right and we have to consider them so how can we get lni so let's say from a how many steps do we have to take so we have to take one two three and four so at the fourth step we will be getting L right and similarly from S at the one two three and fourth step we will be getting I so what did we do so first of all uh how will we get six steps right so if I just do 4 minus 1 into 2 is it equal it is equal to 6 right similarly for L and I if I subtract 6 minus 2 what do I get 4 so we are considering four steps for it right now let's move on to the third row for the third row we are at y here right so we are at y from y if I take six steps where will we reach one two three four five and six we will come at H right and after that we don't have anything here so we'll not be getting anything we'll be going out of the bounds of the length of the string right so we will get y h how to get a and r so from y it is at a distance of 1 and 2. and from h r is at a distance of one and two so what are we doing now we are doing 6 minus 4 that is 2. right we're also doing this along with the six steps for each and every Row for each and every character along with the six steps we are also taking the numbers at 4 sorry the num characters at a fourth and second steps right we are also considering these so uh can we generalize it so if I do six minus 2 into that particular row that is 1 here so I will get 4 for the first row similarly if I do for the second row what will I get I will get 2 here right because for the second row I is equal to 2. so I hope the pattern is clear to you now right so what we'll be doing we will be taking the number of rows minus 1 into 2. these many steps and then we will be skipping it so for first and the last row you can see that we can simply get the whole row by taking six steps at a time right so P then six steps I then after six steps we get n so our first row is complete similarly for the last row what do we have to do because we don't have any diagonal characters here right we don't have any diagonal characters so we can simply do six steps for the first and the last two only for the middle rows we also have to consider characters at these steps also right so I hope the um logic of the problem is clear to you and the pattern is also clear to you select quickly code it out so what do we have to do first of all also there will be a base case and that base case is that if the number of rows given to us is one in that case we simply have to return this string because in that case we will not be able to form any zigzag pattern so if num rows is 1 right then we have to Simply return this string s now what if this uh number is not one then we have to Traverse in these rows right as we saw we'll be going from uh this row and this row right for four all the four rows we will be traversing so we'll be traversing in I is equal to 0 I less than num rules right the number of rows and I plus now let's also make the string in which we'll be appending everything uh let's call it result right and let's initialize it to null and also we have to consider the number of jumps that we will be doing so the number of jumps right or the number of steps that we will be skipping are numb Rose minus 1 into 2 right so these are the number of jumps so after this so for each and every row what do we have to take these many jumps so let's also create a loop for that so we'll be going from J is equal to I that particular index to J less than the size of the string and then what we'll be doing will be taking jumps number of steps right and that is what we'll be including in our resultant string so we will add jumps here now we have to add the characters at this particular jump right so it will be inside of J only right so we will take s of J here but we also saw that for first and the last row it is okay right but for the middle rows right as we saw for the middle rows we also have to consider the characters at then jumps minus 2 into that particular row number we also have to consider these diagonal elements right so for these diagonal elements this is what we will be doing so let's see so first we will check if we are in Middle rows right if I is greater than 0 and less than num rows minus 1 right and also this particular index that we are considering that is 6 minus 2 into I if it is also in Bound that is it is less than the number of jumps sorry the number of the size of the string right so J plus jumps minus um it will be 2 into that particular row that we are at if it is less than the size of the string only 10 what do we have to add this particular index also in our resultant string right so that will be this particular index only 2 into I right so what this will do is for this row will be consider from a we also have to consider the fourth step right one two three four so we also have to consider n so along with a after this it will append at the fourth step and then it will append the next character which is at sixth step and then again from here it will go here and it will append this I which is at the fourth step and then it will also append the G that is at the sixth step so this is how it will be working and after this Loop we will simply return the string so let's run it right so it's accepted let's quickly submit it so that's how um you have to solve this problem
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
863
or not anthony it's me and sexual what he did or didn't do in the country in game to Busquets they know a game of murray I'm fine he said and it's not up to them valdez the same as always the water although there is show credit suisse first world brown defense and trying information no there is fastball 36 modified five the one being the three are spam one in them for the web you like web slices attack which was the five in the usa five 2 gates shot laude this is the show and five comment 3 is north strawberry shaikh le mans ace then ok of lacy croce nuts ice in private of much lamy wave white distance and you don't realize that I'm going from israel wing black hawk ride soul among the issues that luckily I am I returned both types of interest from here with cruelty monster example of this one of five years ago while first multi of 56 like one I say sexy la de child of five by jane lynch like one to one on one schuchat like agents trick like one tourists who go out in ray charles ford web show included and now youtube with ones know committed 6 one2one was committed in the fis west of the west indies walsh security and venice is going to be yang wei I go to a place tour and as one and many do not decrease if it is not in retail best seller one jaguars these tests we are going to discard Alfonsín highlighted the Kristaps sales late now the same many things city in Guayas to list that this one in the 'pheasán' bar click efe
All Nodes Distance K in Binary Tree
sum-of-distances-in-tree
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **Output:** \[7,4,1\] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. **Example 2:** **Input:** root = \[1\], target = 1, k = 3 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 500]`. * `0 <= Node.val <= 500` * All the values `Node.val` are **unique**. * `target` is the value of one of the nodes in the tree. * `0 <= k <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Graph
Hard
1021,2175
108
hello everyone welcome to learn overflow in this video we will look into today's lecture problem that is the convert sorted array to binary search tree so this is an easy level problem and we will understand how we can uh solve this problem or how can think of solving this problem so before starting this video make sure to subscribe to this channel for regular record videos like this also every details about this question will be there in the description make sure to check that out as well so let's start this uh the question says that we are given an integer arrayed nums and the nums is the array that we are given over here five and it says that while the elements are sorted in ascending order so the elements are already sorted that we need to remember the elements are already sorted so the array numbers given to us is a sorted array file uh in ascending order and we need to convert it to a height balanced binary search tree so it should be a height balanced binary substitute and what does the height balance ionic surgery means uh that it explains over here that the highest balance binary tree is a binary tree which uh in which the depth of the two sub trees of every node never differs more than one okay so it basically means like there's a tree say there are two sides of a tree the depth that is the height of each of the subtree never defers more than one like uh that never was the first one so uh that's the whole thing okay so once we so the best thing is like how many like the number of elements or uh the total height in this length is more or less equal to the height on this uh the other side so for each of the loops like it may not be equal as well like it can have a difference of one but it shouldn't be more than one like it should be like a huge difference in height as well so it cannot be like uh it's only going on the right it's currently going on the right so this cannot be a possible height balance the binary search okay so once we are trying to find a solution like this like where the spinach has to is in height balance then how we can actually uh go ahead finding a solution in this case okay we need to see and i'm going to see what the question gives us and we need to see how we can actually think uh all the stuff given to us in the question the first thing given to us in the question is the elements are inserted so once the elements are already inserted then can you think that if you have say you have a scale or a ruler in your hand fine so if you need to balance the ruler you need to uh like you need to say need to balance a ruler that so that on your finger or on any object okay so how would you do you start with middle element isn't it like what do you whatever reach center of mass if the ruler will balance from that position fine so if that is the concept we use in physics now the similar kind of concept we can use uh in uh constructing the binary search tree because we need to do that it's a balance this should be height balanced okay so the first thing you need to do in height balance is you should the what whatever be the middle element that should be the uh root okay so like say there are five errors given to us in the nums array in that the middle limit zero becomes the root in any of the cases fine so that's the idea in this now uh further you see if faded element 0 becomes root then there are two elements on the right there are two elements of the left so you can start with the thought in mind that it's going to be balanced more or less okay you are balancing the tree because the number of elements at least are same in both the side for the first root okay next we need to go ahead and check for the next roots fine further we find that there are five and nine so you can start by taking like the five as the next root and then uh keep nine so that's more or less like the other solution uh given to us fine uh what i mean is like after taking 0 it's like the 5 you can take the 5 as the root and then try to balance the 9 or you can take 9 as the next root or and you can try to balance the 5 when it's left ok so that's the idea now uh you may say like what happened uh like it's uh how is it balanced look uh form nine the other side is none fine uh that's the that's what we know so we say it's like it should be the difference should not be more than one but the difference is what the other side is zero there here is one element so the difference is in this one so we know that this is like height balance because the difference is one it shouldn't be more than one okay the next case is on the left hand side that is minus three and two minus two so you can go ahead with something like simply taking minus three as uh your root over here or you can so mine you can take minus just root and then take 10 on its left and like minus 10 is left on the right it should be it's not fine so you can take like that or on the reverse case what you can take you can go ahead with taking minus 10 as the root or and minus you on its right so this may happen okay so the question is like an explanation tells us like the both the solution can be an accepted solution so that they will accept both the solutions fine so there won't be any problem uh related to that how can you think of uh finding a solution like this okay the thought is pretty simple considering the uh what i initially gave examples at the uh center of mass of an of our object okay the center of gravity what do we say uh how we go ahead with that the idea was uh just find the total number of elements okay and find the middle element at each position so if i even find the middle element make this your root and then go ahead with uh the all the elements on this left are these lip subtree all the elements on his right are his right sub tree so that's the idea okay and the next case uh when you are in the left subtree so what is the middle element will be 0 plus 1 that's 1 by 2 is like once the middle element comes out big three okay so minus three it doesn't matter it because you did minus three or the minus two because both the weights are accepted solution fine so now we find that it's minus three ah if you take the middle element this comes out to be minus 3 fine now take the minus 3 and take minus 10 and this leftward element and another is right towards the element so that's the whole idea okay that's the idea just on each of the pieces on or each of the subtree just take the middle element uh who is your whatever element on its left eyes left subject whatever this right is slight subtree so that's the whole idea you need to follow to come a solution to this so we'll follow the same thing and write a code uh or based on that okay we'll exactly do the same thing and write a code so that would be our idea so let's go ahead and write our code and then understand how we exactly try to follow what we uh wanted to do in this question okay let's go ahead with that see here the particular solution we came across is actually is again a zero millisecond solution is faster than 100 percent java solutions okay let's understand what a solution you came across over here the solution is uh exactly the tribe we were discussing till now the idea was um we took another like helper function within the same name but the different parameters so it's like a function overloading is going on so what it took we took the nums at it we took a start and the end it was just the uh index uh to point what's the current starter what's the current okay so if the start is greater than n written null so what this condition is whenever we need to add a null uh value to any of the roots okay any other subtree so that's the uh this will help us in that fine now further what we did we took up meat i said we will take a mate and meat is basically uh finding the middle uh like the middle element from the starting okay so that's the how we are calculating the meat and then for what you are doing we are just doing like we are creating a new tree node like a current node and that node is basically uh tree node uh is visible we are creating a new tree node and that's the value we are giving it as uh tree nums dot nums meat the mid value whatever the meat uh pointing and so we just gave it a numspeed so which uh construction we are using uh is in the like commenter section you can see the constructors are given so ah there is a construction like this uh this one so like tree node in val if we just send a val so this will initialize uh the current value of the tree node as like the file or whatever valve we are passing it through next we just went ahead with that root left that's the root we created and the root equator so we just went ahead with the root letter and root right so root left is again calling the same uh like the same function with uh with a different parameter like the nums uh array being sent as it is and the start being the starting till uh the we're on the left side so it will be like starting uh till mid was initially zero uh like this uh this element was initially made so what we did on the left we said start till uh mid minus one because mean is that just the pointer we had so we start to meet minus one and on the right what we are going with uh mid plus one till end okay so that's the whole idea we just break it in that format and we found that this is the ultimate return uh we're determining this rule so once in any case say on the left or on the right we don't uh find a expected solution or we don't find any particular value that's uh lies this so we end up with that as a null path okay so that's the whole idea that's how the question like we are trying to solve this question and you folks already saw that the question works pretty well as a zero millisecond solution right so that's the more or less the idea behind this question i hope i can make you understand how you can go ahead and solve a question like this fine and you should try this question and definitely if you face any problem understanding this question make sure to comment it down i'll be more than happy to help you out in the comments as well fine so uh i like this video for making me understand that you actually uh you find this video helpful for you as well uh commented uh you know if you face any uh doubts or if you just want to uh convey any other approach that you have in mind i'll be happy to read that and ex like communicate with you as well in the comments so that's more or less about this video guys thank you all for watching this video make sure to subscribe to this channel for regular echo videos like this i hope to see you soon in my next video as well thank you
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
543
hello guys welcome to study algorithms and today we would be looking at finding the diameter of a binary tree first we would be understanding what is the diameter of a binary tree and look at some sample test cases next we would discussed a brute force solution and the problems you may face next we will try to intuitively think of the problem and come up with an efficient solution followed by a dry run of the code so let us dive into the problem to understand this problem first you need to understand what do you mean by the diameter of a binary tree is simply stated as the longest possible path that you can find between any two nodes in a binary tree so to demonstrate it let me just take up three examples you have tree number one tree number two and three number three entry number one the longest possible path between two nodes that you can find would be this entry number two the longest possible paths that you can find would look something like this so for tree number one our distance is 2 and tree number 2 our distance is 7 but please note that it is not necessary that the longest path would include the root nodes a good example of this can be seen entry number 3 the longest path would be something like and this has a length of 5 so this is how you define the diameter of a binary tree so as for the problem statement you are given a binary tree and you are required to tell me the length of the diameter let us see how we can go about solving this to get started let's just try to have a small tree as an example a good way to solve any problem is to come up with a solution first and then try to optimize it so given this problem what solution can you think of the first solution that comes to my mind is what if I just find the distance between each of the node of the binary tree let's say 1 2 1 3 1 4 and 1 5 now each of these notes would have some distance for node one to have a distance of one three have a difference of two one four have a difference of two and one five have a difference of one similarly if I go ahead and compute the distance of each of the nodes with respect to every other node how would it look like now these are all the possible distances between each of the two nodes in that minor tree and if you look at it the maximum possible distance that we found is three and hence this would be the diameter of the binary tree the problem with this solution is very obvious we only have five nodes in the tree and we have ten different distances to calculate what would happen if the tree size is let's say a thousand nodes or if a tree sizes a tenth of the nodes the number of these distances would just explode and calculating all of them would result into unnecessary calculations and a lot of time wastage so definitely there should be some better way to solve this problem let us try to have a look at it let us try to look at the original examples that we had in the problem if you think about this problem intuitively how long or how deep a tree is it can be determined if you know how deep its left subtree and how deep its right subtree are going so if we can calculate the depth at each node in the tree then maybe we can come up with some kind of a solution so let me just try to calculate the depth at each level of each node in the binary tree I would start off with all of the leaf nodes so no - we have the depth of leaf nodes so no - we have the depth of leaf nodes so no - we have the depth of one node fix has a depth of one node zero has a depth of one and no nine have a depth of one now moving on to the parent nodes node seven has a depth of two nodes five have a depth of two and here's the tricky part when you come to node 4 you need to just know the maximum depth so the left subtree has a depth of 1 and the right three has a depth of two since we are interested in calculating the longest path we would be looking at the maximum depth so in this case the maximum depth at number four is three going over to the right the maximum depth at node number eight is again three because it has no right subtree going up to node number three it has no left subtree so it's maximum depth is four and going to the root the maximum depth is five to verify our result we can easily see that for node number one this is our maximum depth for node number four this is our maximum depth and hence we can easily conclude that these numbers are representing the maximum depth at each of the levels of the binary tree now given this scenario we can come up with the total depth for each of the nodes in the binary tree and this depth would be given something like depth of left tree plus right tree so if we are able to calculate the total depth at each of the nodes in the tree and we keep a track of what is the maximum depth that we could found by combining the left subtree and the right subtree that should give you the diameter theoretically so let us just try to calculate it for each of the node we are adding up the Left depth and the right depth in hence you see we got the maximum depth at each of the node in the binary tree if you see the maximum depth that we found was at known number one and its value was seven which comes out to be the diameter of your binary tree and hence this is your answer let us see how we can go about implementing this algorithm this problem also has a recursive solution where we treat each of the left subtree and the right subtree as a problem in itself and then recurse on the way up to the stack but recursion gives you a lot of problems while debugging and hence we would be looking at an iterative approach for the iterative approach we initialize a stack and a node depth map this known depth map would be storing the known and the maximum depth of each of those nodes we start off with the root node and that if one to perform a post order traversal we push elements into the stack until we reach a leaf node because the root node needs to be processed at the last so while hydrating through this code we would wishing one into the stack then four and then do now to does not have any child nodes and hence we can process it for processing what we do is we calculate the left depth and the right depth in this case both of them are zero and hence the maximum depth available at node number 2 is just 1 and hence we update this value as 1 if you just try to look back a couple of seconds ago we had updated this value to 1 moving forward we pop out two from the stack and hence we reach node number 4 but for still has some child nodes so we would be processing 5 and then 6 would be treated in the same way as node number 2 and hence we are updating our map as 6 and 1 while we are updating our map you see that we are also trying to update the diameter of the tree that we find now this is the maximum value we can find for the left nip and the right depth so up till now our maximum value is 1 and 0 and hence we update our diameter to be 1 going forward we pop out 6 and then will we are looking at node number 5 for node number 5 we see that left depth is equal to 1 and hence while putting into the map we would be updating its value so this would update something like this and if you remember we had put the value 2 in here going forward we've opted for from the stack now 4 has both left depth and the right depth the left half of 4 is 1 and the right depth of 4 is 2 and hence when we updated into the map we would be putting like 4 and 3 now we are again updating the value of diameter and that would be the value that we have found so far and the new value that you're finding at node number 4 this would be 1 plus 2 and hence our value updates to 3 moving on we go on to the right sub-tree moving on we go on to the right sub-tree moving on we go on to the right sub-tree so then we push three into the stack since it has neighbors we push seven and then again we reach zero is again the same as number six and no number two so we would just pop it from the stack and update our map same happens with number nine now coming on to number seven we are looking at the left subtree and the right subtree so this valley would update to two going over to number eight this value updates us three and then going over to number three this value updates us four and now we've reached the main node and that is number one so when you reach at number one let us just try to look at the left depth so the left depth at node number one is three the right depth at node number 1 is 4 as you can see over here and we need to update the diameter that will be the maximum value of the value that we have up till now that was 4 and the new value left and right so that would look something like max of 4 comma 3 plus 4 which turns out to be 7 and hence this is your answer the time complexity of this algorithm is order of n and we occupy order of n extra space more details on the recursive solution can be found in the problem description mentioned in the link below both the solutions work in order of n time it's just that the iterative approach it's easier to visualize please feel free to reach out to me in case of any doubts and leave your feedback in the comments below thank you
Diameter of Binary Tree
diameter-of-binary-tree
Given the `root` of a binary tree, return _the length of the **diameter** of the tree_. The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`. The **length** of a path between two nodes is represented by the number of edges between them. **Example 1:** **Input:** root = \[1,2,3,4,5\] **Output:** 3 **Explanation:** 3 is the length of the path \[4,2,1,3\] or \[5,2,1,3\]. **Example 2:** **Input:** root = \[1,2\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Binary Tree
Easy
1665
114
hey what's up guys it's Nick white here I do tack encoding stuff on twitch and YouTube and check the description for everything about me I do all the problem ly code problems and they're all on my youtube channel so just check those out same intro as every other video this one's called flattened binary free to a linked list and we don't really flatten it to a linked list at all I don't even really know why it's called that it says given a binary tree flatten it to a linked list in place so for example given the following tree so we have a tree we would turn it into this so basically as we can see here we're basically kind of just turning it into a tree it is kind of a list type thing but it's you know I could see how they could say linked lists cuz none of these have a left child so basically now it's just only nodes with a bright child and if you wanted to think about it would be like a node just dot next in the right dot right would now be dot next or whatever if you wanted to think about it like that but yeah we're basically taking these and turning it into position wise kind of an in we're taking the position of the nodes and turning it into a position wise ordered kind of path here of all right children right so basically the right children will be in all the right children of the nodes will be kind of an order of the previous tree position wise right so as you'll notice all of the you'll basically be taking the left children and be setting them to the right children of from root down so yeah you can see just position wise like 1 2 3 4 so it's kind of leftmost to rightmost is how we're kind of gonna be traversing this tree and setting the right notes right so to do this all we have to do is if root equals no it's pretty easy honestly so return a lot easier I've seen harder easier problems and trees than this so then we'll have our stack like all the other problems so we have a stack of tree nodes we'll call it stack add the root to it just like the other ones while the stacks not empty so while the stack is an empty pop the current node tree node current stack pop and then what we do is since it's a stack we're going to traverse we're gonna add the right node to the stack first because we actually want the left node first so we're gonna add the right node to the stack first so what we do is if current node right this will make sense in a second right it's not equal to null stack top push current node dot right and then same thing for the left now left is afterwards dot left is not equal to null stack push current node dot left right so you push the right then you push flush and then all you have to do down here is if you do the same check again stack isn't empty because I'll explain that in a second - because I'll explain that in a second - because I'll explain that in a second - then you do current node dot right is equal to stack top peek and you're gonna set yeah we'll go through an example here and then you set every node no matter what they're left to null because you can see every now it's left is no so let's go over an example here so the first node we're gonna put on is one right for the root you would check you'd see the left node is 2 and the right node is 5 so you push the right node onto the stack which is 5 and then you push 2 onto the stack for the left node then you just do this check down here if the stack is not empty which it's not it has five and then it has two we pull two off because that's the peak and we said well we don't pull two off we just get it we get two because that's the peak so the stack peak is two and we set one dot right to two and you can see one dot right is to here and you do that over and over again and eventually it sets all the proper right notes and it sets every left node to null and it does that because and you have to do this check down here this the second is stack is not empty check down here because let's say it was just a room note so all we have is room we popped the root note off the stack so it's just one you add nothing because the left and right are null so these never get executed and then you would have to do this check because you don't want to set right there's nothing in the stack to set the right to so that's why we just do the second stack we just do the second check here because we are popping off the stack so we're technically decreasing the size of the stack so we do have to make sure that the stack has something in it's pretty self-explanatory it would set pretty self-explanatory it would set pretty self-explanatory it would set although it takes all the left notes kind of puts them in the stack and sets all the right nodes to the first left the leftmost nodes and then as we go the right notes get set to other right notes so it's kind of a left-to-right type of so it's kind of a left-to-right type of so it's kind of a left-to-right type of deal here and hopefully I explained that pretty well let me know in the comments if I need to do better it's pretty kind of self-explanatory I don't think it's of self-explanatory I don't think it's of self-explanatory I don't think it's that hard of one if you really just think about it and go through a couple solutions in your head that's pretty much it so thank you guys for watching check out some other solutions and I'll see you guys later
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
69
hello and welcome to python programming practice in this episode we are going to be covering lead code number 69 called square root x given a non-negative integer x given a non-negative integer x given a non-negative integer x compute and return the square root of x since the return type is an integer the decimal digits are truncated and only the integer parts are returned so basically i guess that means we find the square root but we want to return like rounded down to the nearest integer like the floor function of the square root example i don't know that we even need examples we kind of know what the square root is if x is 4 the square root is 2. if x is 8 the output is actually 2 as well because the square root of 8 is somewhere between two and three and if we round that down to uh the nearest integer well it's showing us here the square root of eight is two point eight whatever but if we round that down then it's going to be two as well our constraints are the numbers going to be between 0 and 2 to the 31 minus 1 so we are going to have to be able to handle fairly large numbers here now this is seems like a very simple problem because it's just asking us to do an operation that is just math that python can just naturally do with either basic imports or just exponentiations so it seems like they should have really maybe put more instructions as to kind of how you're supposed to approach this problem because there's a few easy ways we could do this without really doing anything interesting like for one we could say an import solution all you'd have to do is import math to gain access to the square root function then return math dot square root of x that should be a easy working solution but of course we need to also do int of that since the problem called for rounding to the nearest integer that should strip off the decimals and just return the int portion of it so that should be a working solution so let's go ahead and submit that one just to get a start on this problem so let's just pull over and see the result of what that is we can see just even with that basic submission i'm assuming lots of other people did that the run time was 32 milliseconds faster than 81 of other python 3 submissions now in reality i don't see why you would ever do anything more than this if you want to do square root in python you should just use the square root function but i guess there is probably other ways to solve this now one other very simple way to do this without even importing math is use exponentiation so we could say exponent solution so the square root of a number is the same as that number raised to the one-half power one-half power one-half power so all we'd have to do is return int of x to the one-half and this should also get to the one-half and this should also get to the one-half and this should also get us the same answer as what we just did so let's submit that and it's probably going to result in the exact same everything but who knows so for some reason that run was a little bit quicker than the math one i guess because we didn't have to import the math module first or something but so 28 millisecond runtime faster than 92 percent of other python 3 submissions now again these two solutions are probably the easiest and best way to do this but clearly if you want to make this problem more interesting than just importing something or doing basic exponentiation you'd actually have to go out and figure out how to find square roots mathematically and that's something that most people probably have no idea how to do so i didn't know how to go about manually calculating square roots because i'm not sure that's something i ever learned i went to wikipedia and looked up some different ways so we can look at wikipedia here and there's a whole bunch of different methods for finding square roots i found this thing called the babylonian method which is supposed to be one of the first algorithms used for doing this which is basically an iterative approximation of a square root basically what it does is starts with some estimate of what the square root is and then iteratively gets closer and closer to the right answer we don't need to go too big into the details the most important part of it is this here it basically says that the method can be represented by this algorithm so we start with some estimate x0 that's supposed to be somewhat close to the square root of s or whatever number you're working with it actually doesn't have to be close to it just means that if it the closer your initial estimate is to the square root the faster it will converge but it doesn't actually have to be that close we can just use whatever initial estimate we want to and then we just keep updating this estimate based on this formula so the next estimate which is x n plus one we start with x of zero n plus one of zero would be one but then we go to the second estimate third estimate and so on so the next estimate after whatever initial one we have is equal to one half times that current estimate plus s divided by the current estimate where this value s is the number that we're finding the square root of and then mathematically this method will converge on the square root as you go through more and more iterations that's what this is saying here it's saying the square root of our number is actually equal to this value xn in the limit as n goes to infinity so basically as we're doing more iterations and we keep doing this update this number will get closer and closer to the square root of our target until enough iterations and it'll basically be effectively the same thing so i thought for an exercise it could be interesting to try to code up this algorithm as a solution to the square root problem even though you would never actually want to do this if you're having to calculate square roots in python so let's go ahead and try this so it's going to be called the babylonian method and we don't want to have to deal with cases where the target is too small because when x is one and x is zero things get a little weird so if x is less than or equal to one let's just return x because that deals with those corner cases where the square root of 1 is 1 and the square root of 0 is 0. so let's get rid of that and then else we just want to implement that function that we just looked at so let's come up with some initial estimate x n um it could really be anything let's just set it to say half of the target that we're given so the integer target we're given is called x in the little algorithm we looked at was called s but it could be whatever we want and we now also want to keep track of how big the number is changing so basically we want to keep running the update until the change that we're seeing from one iteration to the next is small enough that we want to exit we don't know exactly what small enough should be in this case but anything that's quite a bit smaller than one we're probably then in the range where we're going to be close enough to an answer to round it to the nearest integer and get the right thing so let's set the change equal to just one initially and but we're going to keep iterating until the change is smaller than that so while the change we're seeing is say greater than some value that's kind of small maybe 0.01 or something like that maybe 0.01 or something like that maybe 0.01 or something like that should put us pretty close to what the real square root is then we will do the algorithm updates that we saw so we need to calculate what the next n is going to be and that was equal to one-half so 0.5 one-half so 0.5 one-half so 0.5 times what the current value was so x n plus the actual number we're looking for x and the algorithm we looked at was called s but it's called x for us divided by the current number so this is what the next estimate is going to be the change is now going to be equal to the old estimate minus the new one so minus the next one that's the change and in theory the change here could actually end up being negative it's if it's being adjusted the right way for that to happen so we actually want to take the absolute value of this to make sure that it's just the magnitude of the change and we don't get a negative value here and then we just need to do the update so after that we'll update our x n to equal the next n and this while loop now will just keep running and finding a better approximation of the square root until the change scene from one iteration to the next is less than 0.01 that should end up being less than 0.01 that should end up being less than 0.01 that should end up being a pretty close approximation to the square root so at that point we can just return so we will return we need the integer again so we'll return the int of our xn that we are finding the approximation for so this should essentially be a working implementation of that of this function here that was shown in wikipedia so that should also get us the square root we'll see how good these babylonians were with their algorithm efficiency i guess so let's uh hit submit on that one as long as we didn't make any errors in the code now again we didn't come up with a very smart kind of initial seed for our estimate of the square root if we could come up with maybe a smarter way of doing that this might be a little more efficient but regardless it should eventually find something that works let's pull over and we got a working result it was 36 milliseconds so the runtime was maybe a little bit slower than some of the python built-in ones we used but it's python built-in ones we used but it's python built-in ones we used but it's still relatively fast giving that it was faster than 60 of submissions and i'm guessing most people that submitted this one probably just did one of these more simple ones and if we didn't want to be so exact in our approximation we could probably get something faster like here we're trying to find where the change is less than a very small amount well if we maybe made this little bigger maybe the approximation wouldn't be quite so good and it might actually fail the greater but if we make that 0.1 if we make that 0.1 if we make that 0.1 we won't have to run as many iterations let's submit that and see how fast it is so i guess that didn't make too big of a change but it was slightly faster than the one where we had a few more iterations so you could probably play around with this with the seed value and how many iterations and maybe get something that's about as good as these built-ins as these built-ins as these built-ins so this is a case where the easiest solutions are probably what you should be using in practice there's no reason to reinvent the wheel and try to find a new way to implement square root when it can be done so easily in the base language but for the purposes of having a somewhat more interesting coding problem i thought it'd be interesting to actually try to implement an algorithm that finds a square root mathematically instead of just using something baked into the language so thanks for watching and keep coding
Sqrt(x)
sqrtx
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well. You **must not use** any built-in exponent function or operator. * For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python. **Example 1:** **Input:** x = 4 **Output:** 2 **Explanation:** The square root of 4 is 2, so we return 2. **Example 2:** **Input:** x = 8 **Output:** 2 **Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. **Constraints:** * `0 <= x <= 231 - 1`
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
Math,Binary Search
Easy
50,367
888
hello everyone so in this video let us talk about a easy problem from lead code the problem name is fair candy swaps okay so Alice and Bobs have different total number of candies you are given to integer array Alice size and Bob size where Alice size I is the number of candy of the ith box of the candidate Alice hold whereas Bob size J is the number of candies of the J box of the candidate Bob has okay so I'll just take you the next input as well that Alice size as you can assume that these are different candy boxes okay one candy box is of size one another candy boxes of size one so Alice has two candy boxes of size one similarly Bob has two candy boxes of size two got it so plus they have these type of candy boxes since they both are friends they like to exchange one candy box okay one candy box will transfer the box to Alice and Alice will translate to Bob now they want to do that such that they have the both has a total amount of same candy okay so the total sum of the candy boxes the value of these candy boxes whatever you can say will become equal after that one exchange okay now I just have to tell that what is the value that should be given by Alice and what is the value addition by given by Bob so that eventually they have the same number of candies and it is guaranteed at least one cycle the first thing which comes to my mind is okay uh they have different candidates but eventually they will reach two same candles same condition means a middle of whatever candidates they have so let's say one has more candies one will have less candy and they will come to the middle so what you can what is the middle value you can directly get out at what value they will eventually reach when they are equal candles so what you can actually do is just sum all the value of candies Alice says and Bob have divided by two you will get what is the amount of candy both should be having in the end of The Exchange so that they both have same number kind I hope you get the point so what we'll do is we first find out the sum of all the elements of Alice and Bob and divided by two so that we got to know what is the final lead of Alice and Bob after doing this machine now they have to do an exchange now how they should be doing an exchange the first thing is what we can do is that let us there will be only one exchange that is given to you so let us try to iterate over Alice voxel of candies and one by one we'll check that whether if Alice give the first blocks if Alice give the first box what is the candy that Bob should give so that they both will become equal okay we have the final point at which we should reach the final state that we should reach we have the current state if Alice gives the ith box we will iterate over every box of I because they will do bearing out only one box so what we'll do is we'll enter over every box of LSi and let's say that Alice give the ith box if Alice give the ith box Alice has a total sum it gives the ith boxer to subtract from this but eventually they want to reach a final state in which they have equal amount so this is the final needed so this total final needed State minus the amount of Andy as like candy Alice gives from the total sum will gives you what is the amount of candy it should receive to reach this final state hope you get the point so Alice has given something and it will also receive something so how much Alice should be receiving to reach the final state after giving the is capital now if Alice give this candy to Bob or Bob will also give you something now Bob should be giving that much of candy so that Alice should reach this final state so I knew that this final state is other I have stored in this at this variable so I just checked that whether this other type of candy is present in Bob's candy collection or the different candy boxes we have so we what we can do is to make it more quicker we can just make a map out of all the candies present with Bob and we can just check in the map or you can also make a set not met like I said multi set because they can multiple same candies as well but if a candy is present with Bob that Alice wants then uh Bob can give that candy to Alice and Alice is giving one candy to Bob and eventually because we decided that this is the final State and this is the final State Alice will reach So eventually Bob will also reach the final State because uh the candies are same only like they are a fixed collection of category so what we'll want to is that if Alice is giving the is candy it should be receiving this other amount of candy from Bob so that Alice will reach the final needed State and for that can it be received by Bob you have to actually check that whether that can be that amount of candy pop should have so we will check then in the map that whether the amount of candy pop have if it has that particular candy then we got the answer that Alice will give this eye candy Bob will get to this or this other candy and both of them are fine so we just make and like because you have to return what amount of candy Alice and Alex should give and Bob should give so we just return an array of the candy that is Alice should be giving and the Box should be giving and that's it so it will always occur this state so this will be returned always and this is a zero comma zero I'm just in like just to make this function more clean that's why it is written but this condition will never hit because it's a uh the condition is like for every case it will always sit and then uh we have just make an unordered map we just checked it whether I put the candy special job for a particular candy given by Alice okay that's our logic so coming down Your Dragon City we have done an O of n to find out the sum this o of n make another map then we have done the fall Loops of n so it is all together o of n only for doing this whole operation if you are using a map it will be o of n log n but that's not much of a deal because it would probably that time home safety as well so that's overall logic and the good part for this particular problem if you still have any doubts you can mention not in the comment box of this particular problem thank you for watching video till the end I will see you in the next Monday reporting and bye
Fair Candy Swap
mirror-reflection
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
Math,Geometry
Medium
null
211
hey everybody this is larry this is day 28 of the january lego daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about this problem which is design ad and search word status structure restrained design hopefully i've been doing all right it's still very cold here in new york and i've been just feeling a little bit unwell uh hopefully not of the you know thing that's going around i mean i've just been having poor sleeping habits to be honest but uh okay let's see uh okay matches if we did it i'd would add was it can be matched later search okay oh it may contain dots okay length is 500 uh okay huh kind of these things are always a little bit tricky because are they do they have the same length hmm this i guess it's not clear um i'm trying to also see where how many words there are but i guess the implicit part is that there can be you know 50 000 words or whatever but of course you know you'll just be searching this is also like one of those type of problems that i feel like is um kind of guests to input a little bit what i mean by that is that you know it could be they could have really hard test cases and you know almost no solution would pass or it could have you know silly um silly cases but yeah i don't know but yeah i mean let's do it naively and then we'll see if that's fast enough because that's going to be if they really want it to they can make it very sloppy but yeah i always do struggle a little bit of these wild card things because you can pre-process it but it's because you can pre-process it but it's because you can pre-process it but it's always like i said like that also depends on a bunch of things um because like the word length being 500 means that it prevents you from doing a lot of the pre-calculation stuff doing a lot of the pre-calculation stuff doing a lot of the pre-calculation stuff with respect to like you know brute forcing um wild card on order sub uh subsequence is it yeah so it's a little bit awkward but okay let's uh let's just do it naively and then we'll see what how it goes um yeah okay um what if oops if uh someone like i mean you could write this in a for loop but yeah so if x is equal to y or x is equal to 2 for x y in sip of word talk uh the other way target word if all of this then we return true otherwise we return force now this is basically as naive as it gets we might have to think about optimization i mean i didn't really you know but i guess we'll see oh this actually may be wrong because if target and word has different lengths um then this may actually give you a true even though it's worse yeah i mean so target length is equal to length of target and then if target let's talk the length as you go to length of the word and all this stuff um and you can kind of actually test this i should have tested for demonstration um but basically for example if you search for let's say this should give you force but if we didn't have this then if i it might give you true for example if i took this away i think this would maybe give me true um yeah so i'm glad we fixed that but now we'll see if it's fast enough um we could also do something like do a look up by the length so that we can save this uh and maybe even the first character or something like that but ah i did it okay last time i wonder how i did it last time we'll see if this is fast enough also like i feel like they've been adding a lot of test cases for the last couple of years so given if i did the same code it might not be fastened up and this is too slow apparently um oh well how many test cases are we uh well there's only 13 test cases and we've not do um oh there's a lot of dots uh but i also saw like a lot of two characters in one character so i guess what we can do is just have like a lookup table right so yeah and then just do something like this right and then we can let's copy and paste this i'm still a little bit tired to be honest let's see if that one's fast enough uh ooh whoops now my keyboard is fine but i've been put i think i've moved my keyboard to a weird place and then my fingering's a little bit off uh two point okay that seems fast enough but we'll see if that's actually fast enough um yeah that's a little bit silly though it's like i said right everything depends on the exact input this is such a weird optimization uh or maybe not weird just i don't know what i did last time i did it with a try well i was actually thinking about doing with a try but i didn't i wasn't sure that it would be fast enough um because the period can branch off multiple places right so i guess in the past i just yellowed a little bit differently but because we have a word and then if it's equal to word then we look at every edge right so i feel like in theory again like i guess that's why i didn't do it this time uh even the last time i was happy with the yolo but the problem is that yeah the problem is that technically i want to say technically you can branch out like in many ways and it becomes almost looking at every word but that said looking everywhere was basically what i was doing before so because you can think about it as a tree where you know there are multiple branches and all the branches you go you know you're going to get um yeah this is brute force on like almost a deaf researcher like if you have a wild card then look at every leaf or not every leaf every children to see if one of them is good um i don't know how i feel about how to do it i think this one is one of those classic problems that is a little bit reading um reading the mind of the problem setter and those are always a little bit tricky because they just want you to implement in a specific way and the number of test cases and the not even just the number of test cases because that is something that i complain about as well but beyond that the um the like the distribution of inputs or something like this right um like i think the uh this case like this case uh apparently filtering out by length saves a lot of time but even if they're all the same length let's say we moved order one period to two periods then he is essentially we would check a lot more words right so then like maybe that's enough to make it time limited i don't know but that's kind of things that's like a little bit about or at least in lead code a lot about just guessing what the writer is intending so those are always a little bit yucky um in terms of complexity this is really like this is naive right to be honest it's naive with a very minor optimization so there really is um i mean i don't know it is not a very good optimization there's not really good complexity so i don't know all right um let me know what you think about this farm let me know what you think about my solutions either this one or the one that i did previously um that's all i really have i don't uh this is a very yucky problem i don't really i'm not a fan of it uh at least in terms of you know there's two too many ways you could have done this and like i said it's just about guessing the input uh just like the texture of the input say so yeah anyway that's all i have stay good stay healthy to good mental health i'll see you later bye
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
7
hello my friends this is Alexander barmin and this is my YouTube show lead code with me where we solve coding challenges from lead code recently I conducted my first live stream and hope you enjoyed it and if you have topics for the next streams to for me to cover please don't forget to write a comment for this video and they'll definitely arrange a next stream and if you still want to play powerblade game for NES also please write a comment they will have it so let's get started and go ahead okay let's start the Korean challenge so we're given an integer and we need to return and not the integer with its digit reversed so for example if you're given one two three we should return two three one so there are multiple ways to solve and git and this most simplest option is to convert this integer to the string one two three and next read the string in a reverse order simple yep relatively simple but maybe not so efficient because we have number to string and next we need to convert our string three to one back to the number little one which is not really good let's try to because we know it's a slit code we know it's lit court and Lead code ordinary asked to think about our challenges from the mouth point of view so let's think so we have number which is equal to one two three and what we need to do we need to take the last one number from it's free in this scenario right so what does it mean we need to divide our number by 10. and take a rest so roughly speaking well we need to divide and by 10 and take a rest so in this case the rest is free and what is left is 12. right again next step we have 12 we again divided by 10 we take two and one left again 1 divided by ten it is 1 and 0 left okay fine uh other than that we need to find a way of building numbers in a reversed order okay let's start thinking about it let's assume that by default we have zero and we will start adding these rests zero plus three is equal to three okay next time what we need to do we need to say three is not the first number and not the first number in our in is not the first digit in our number it should be moved one position to the left what does it mean we need to multiply it by 10 and plus the second rest so roughly speaking it means it's 30 plus 2 which is 32. next step okay I have 32 If I multiply it by 10 and add 1 because 1 is the rest here what I will have 320 plus one which is three two one okay so I managed to reverse my number and I managed to do it by doing F2 operations first of all dividing by 10 and second multiplying by ten and the last one bit is in case if number was negative I need to persist the sign if it was negative it should be negative it's positive it should be positive okay that's it traffic speaking let's write it down long result is equal to zero I start with long because the conditions the task says that it's uh in case if it is outside the integer uh range I need to return zero so I need to know is it outside or not and um uh in order to do that I want to continue and write something like this integer max value if it's more than max value of result is less than integer mean value it is zero that's it just because I'm sad that I need to return zero because integer my might overflow and next I need to convert my result back to integers so this means that in case if number is more the is outside of the integer range which I should return zero and in case of my in my value is inside the integer range I need to return this integer so easy okay other than that I need to persist a sign so Boolean negative because positive it's fine uh this is the sign in case if number is negative this condition will be related to true in case if it's positive it will be evaluated through uh false and other than that I need to return my sign back if negative my result is Multiplied to minus one or it's better to write it like this results multiply to minus one because it's more readable and X is math ABS X so uh I take an absolute value just because it's easier so I edit all the conditions and right now I may start implementing the logic I just described first step is to divide by zero next step is multiply by zero and add a rest so while my number X is more than zero what I wanna do is I will take my result and multiply it by 10 as I said here I'm multiplying my result by 10 and other than that I need to add a rest after division by 10. so this is what I do and Next Step so because this is not an assignment it is just a computation what else I need to do I need to say okay X is everything which left on the left hand side after dividing by 10. so this first line says that I multiply what I had before roughly speaking 0 multiplied by 10 again it's a valid condition and plus a rest of the division it's free next time I take what I already have in my result multiply it by 10 and add a result of division by 10. okay and also I need to decrease value of the X so just by dividing it by 10. let me submit it okay I'll work and final submit while it beats 97 and 75 percent of all users who wrote it in Java I suppose this is exactly what they expected that's it for today hope you enjoyed the video and if so please don't forget to give me a like write a comment and subscribe to my channel foreign
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
857
hey guys it's iran with another coding interview question and this one is called minimum cost to higher k workers this one is really popular with google probably on account of it being really difficult it's also labeled as a lit code hard and i do agree with that label so that's exactly why i wanted to make this video i really hope it will help you guys and if it does please let me know in the comment section because i would love to know okay so let's get straight into the problem description there are n workers the ice worker has a quality measurement and a minimum wage expectation i'm just going to change the name of the array because i want it to be called expected wage now we want to hire exactly k workers to form a paid group when hiring a group of k workers we must pay them according to the following rules so the first rule is that every worker in the paid group should be paid in the ratio of their quality compared to other workers in the group and in other words it means that the ratio between the offers that we make to any two workers has to be exactly equal to the ratio between their qualities so in other words the first rule says exactly that now the second rule is that every worker in the paid group must be paid at least their minimum wage expectation so again in other words the offer that we make them has to be larger or equal to the expected wage of the worker now we want to return the least amount of money needed to form a paid group satisfying the above conditions okay so we want to return the minimum cost that it will take us to hire k workers considering these rules so the first important thing to notice here is that because we're trying to pay the least amount of money there is always going to be at least one worker in the group that is paid exactly what he asked for otherwise we pay everyone more than they wanted which is a missed opportunity right we could be paying everyone a little less and still satisfy the conditions so again there's always going to be at least one worker in the group that is paid his expected wage we'll call that worker the captain so the second important insight here is that once we decide who the captain is once we decide uh what to pay one worker we know exactly what we need to pay all of the others and i'll show you exactly what i mean so uh we decided that we're going to pay the captain his expected wage right now we have this a second rule that states that the um ratio between offers to any two workers including that of the captain is equal to the ratio of their qualities so if we substitute this uh term with this one we get to this equation here now i want to isolate this term so i'm going to multiply both sides with the captain's expected wage and then i get to this equation here so basically what this means is that once we decide who the captain is we will know the value of these two terms and then we will know exactly what we need to offer each of the other workers the amount that we'll need to offer to worker i is equal to the quality of worker i multiplied by the captain's ratio now let's see an example so we have three workers in this example we're going to call them jay tom and ben each worker has a quality measurement and an expected wage and we want to find the minimum cost to hire two workers so the way we approach this is we give each worker a chance to be captain then for each captain we calculate how much we're going to have to pay each of the other workers then we pick the two workers that cost the least amount of money and that's going to be the cost for this captain and then at the end we will pick the group that cost the least out of all of the captains now let's see how this works so if jay is the captain we're going to pay his minimum wage expectation which is 80. and then the captain's ratio is going to be 80 divided by 10 because 10 is j's quality so 8 and then we're going to offer tom 5 which is this quality multiplied by 8 which is the captain's ratio so 40. then we're going to offer ben 15 times 8 which is 120 and then we're going to pick the two workers in this group that cost the least which are uh jay and tom so the minimum cost with jb and the captain is 120. now if tom is the captain we're going to pay his expected wage so uh 35 and then the captain's ratio is going to be uh 35 divided by 5 which is 7. so j is going to be offered 10 multiplied by 7 which is 70. now notice we're not allowed to offer 70 to j because his minimum expectation is 80. uh so if tom is the captain we are not allowed to hire jay ben will be offered 15 times 7 which is 105. it's above his expectation so it's good so if tom is the captain the cost of the group is going to be 35 plus 105 which is 140. and lastly if ben is the captain we're going to pay his minimum expectation the captain's ratio is going to be 30 divided by 15 which is 2. then we're going to offer j 10 times 2 which is 20. that's below his expectation so we cannot hire j we're going to offer tom 5 times 2 which is 10 and this is again below his expectations so we cannot hire tom and that means that ben cannot be captain because there are no groups of two workers that satisfy the conditions and now we choose the minimum cost between the captains which is 120 and this is the value that we want to return okay so let's start with the code we'll start with the nav way and go from there so i'm just going to start by getting the number of workers then we're going to need a variable for the main cost i'm going to initialize it to the maximum possible value a double can have in c plus it would look like this now we're going to give each worker a chance to be captain so we go from 0 to n and we want to calculate the captain's ratio it's going to be the captain's expected wage divided by his quality next we're going to calculate how much we're going to offer each other worker we're going to offer the quality of the worker multiplied by the captain's ratio then the offer is accepted only if it is larger or equal to the expected wage of the worker so we're going to need an extra vector here that will hold all of the accepted offers so i'm going to call it accepted offers and now if the offer is larger or equal to the expected wage we want to add the offer to the accepted offers array now at this point if the size of the accepted offers array is less than k it means that this worker cannot be captain because he cannot form a group of um k workers that satisfy the conditions this is the exact situation that we had with ben being the captain in the example okay so we just want to move on to the next captain the next thing we want to do is we want to find the sum of the k smallest elements in accepted offers array finding the k smallest okay largest elements in an array is actually a very common problem with a very common solution and the solution is to use a heap for k smallest we want to use a max heap now this is not the main topic of this video so i'm going to do this very briefly if you want to get more information about this algorithm uh you can just search for uh k smallest elements and you will get like a million results so uh for now let's just write the code for this so we're going to define a max heap in c plus bus it's called the priority queue we're also going to need a variable for the sum of the heap initialized to zero and then we're going to build the heap out of the k first elements in the accepted offers array and update the sum of the heap next we want to iterate over the other elements in the accepted offers array so start at k all the way to the end and if the heap is not empty and if the current offer is smaller than the maximum element in the heap then we want to replace the maximum element with this current element so the cost for the minimum group that this captain can form is actually exactly the uh sum of the heap and then we want to keep track of the minimum cost out of all of the captains now we want to return the main cost so let's try this it's pretty inconsistent with the capital age here okay so the code works for the example but it's not going to be accepted because of the runtime let's think about how to improve this so i want to focus on this line here an offer to worker x is only accepted if it is larger or equal to the expected wage of the worker the offer is equal to the quality of the worker multiplied by the ratio of the captain if we divide both parts by the quality of the worker we get to this expression here which means that the only offers that are going to be accepted are the ones to worker that have ratio that is smaller or equal to the captain's ratio so if we sort the workers by their ratio we will know in advance which workers are going to accept our offer all the workers that are on the left of the captain in the sorted array will accept the offer and all the workers that are on the right of the captain will not accept it so we could just avoid making them in the first place and save time so let's get back to the code and see how it works okay so the first thing that we want to add to this code is an array of workers that is sorted by the ratio each pair will contain the ratio and the quality of the worker and the size of this array is going to be n now i'm going to initialize the array and now we're going to sort this array so it's sorted by the ratio so now we don't need to give each worker a chance to be captain because we know that workers at index below k minus one will not be able to form a paid group because they don't have uh k workers that have uh smaller ratios right so we can start this loop from k minus one now we already know the captain's ratio because we calculated it here right so you can just take it from the workers array like this and we only want to look at workers on the left of the captain because these are the workers that are going to accept the offer so we can stop this loop here and then we can also remove this condition because we know that all of them are going to accept the offer and we want to also um take the quality from the workers array and uh not from the quality array because we want it to be sorted so uh it's here now we don't need this line right because we know for a fact that the accepted offers array is going to be uh larger than k so we can remove it and the rest of the code stays exactly the same okay so let's try to submit this okay so as you can see this is still taking too much time so let's look at what we can do next so basically what happens in this section is that for each iteration i the captain is worker i and we want to find the k smallest elements in this array we want to find the k smallest offers to workers that are on the left of the captain so that's why it goes from zero to i then in iteration i plus one the captain is worker i plus one and we want to find the k smallest elements in this array that goes from zero to i plus one now this feels like a lot of duplicate computations right it would be great if we can somehow reuse the results from previous iterations and not start from scratch for each captain right the problem is that these offers are not the same for each captain because they depend on the captain's ratio so the trick here would be to just remove the captain's ratio out of the equation like that and now this array is exactly like this array plus this one extra element right because it's just an array of the qualities which don't depend on anything so by the time we reach iteration i plus 1 we already know the k smallest quantities in this array and all we have to do is decide how this last element fits in and this is pretty easy so let's do that in code okay so because we now try to find the k smallest qualities and not the case smallest offers we can just remove the part that calculates the uh offers right we can also take the part that initializes the heap and put it outside so it's only done once and again because we are talking about qualities this is not a double it's an int this also and this is not for the accepted offers we want to put here the qualities and the qualities are so now we have the sum of decay first qualities so let's also compute the cost for the first group and we don't need this here we can just put it here okay so now we also have to start here from k and not k minus one and now we also don't need this loop here right because for each captain all we have to do is figure out how the captain's quality fits in which is the last element in the array so we don't need the loop we can just take this part and do it once and of course instead of this term we need to put in the captain's quality so now the sum of the heap is not the sum of the offers it's the sum of the qualities so we need to multiply it by the captain's ratio and i think that is it let's try it okay so let's try to submit this now this should be k minus one okay so this is a success we passed all the test cases and with pretty good time so let's say a few words about the complexity this loop will take of and worse time and then sorting the loop would be o of n log n building this heap is o of k and then this loop would take uh o of n log k because we have uh n iterations and uh with each iteration we do a push to a heap of size k which takes low k so that's how we get to n log k so the total time complexity would be n log n because this is the most uh time consuming part right so uh the time complexity of this algorithm is o of n log n okay so that is it for this video i hope it helped you guys if you liked it please give it a thumbs up and i will see you next time thanks for watching
Minimum Cost to Hire K Workers
positions-of-large-groups
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to the following rules: 1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. 2. Every worker in the paid group must be paid at least their minimum wage expectation. Given the integer `k`, return _the least amount of money needed to form a paid group satisfying the above conditions_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** quality = \[10,20,5\], wage = \[70,50,30\], k = 2 **Output:** 105.00000 **Explanation:** We pay 70 to 0th worker and 35 to 2nd worker. **Example 2:** **Input:** quality = \[3,1,10,10,1\], wage = \[4,8,2,2,7\], k = 3 **Output:** 30.66667 **Explanation:** We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately. **Constraints:** * `n == quality.length == wage.length` * `1 <= k <= n <= 104` * `1 <= quality[i], wage[i] <= 104`
null
String
Easy
2260
70
hello and welcome everyone let's continue edition prasad lists by solving climbing stairs while climbing is stick is and it takes n number of stairs steps to reach the top we can take either one or two steps and how many distinct twists can we claim to the top we can see from the first example that we have two staircases and we want to get to the top so drawing a picture we can see that this is one staircase this is two stickies and this is you in one huge step you can get to the top this is one way or you could start slowly and get to the top in which case this is going to be two ways and we also have um let's try the second example where we have three the staircase is at three and once again this is you could start slow and climb to the top this is one or could start slow then take a big chunk of step and this is going to be one or rather one or you could take a big chunk and decide to go slow and then this is three but imagine that our staircase we're giving five right we're giving five staircases rather this is one two three four and five this could get really complex and confusing in that you could start here this is one you could start one go two three and this get really confusing this just tells you that we can try something like a decision tree should we try that maybe um so this is you here and you want to get to the top of the staircase right the top of the staircase is basically when there is no more stickies for you to get to but we know that you can take either one stairs or two stairs at a time basically so you either taking one staircase in which case you would have two more stickies to conquer or you could taste two stickies in which case you would have just one more staircase to climb again we can see that you can take for each step that you've taken now you can either take one more step in which case you would have one step to conquer or you could take two state cases in which case now you have zero steps to conquer now this basically means that okay cool yeah at the top you're at the top here because you have no more stickers to conquer now let's continue with this side where you want to take one staircase and this is zero you have nothing else to conquer you've gotten to the top ray you're at the top or you could take two staircases in which case one minus two is going to be minus one and this doesn't work right this is invalid that means when at this from this point you can take two stickies because it will lead to it's really to you falling off of the staircase there is nothing else you can take minus one now we can go back to this final one and whereby take one staircase and you arrive at the top again because there is nothing else this is zero or you take two stickers in which case we have what we previously had here in which you fall so now we can see that we have three staircases using a decision tree now why am i using a decision tree i am using a decision tree because it is easier to picture a decision tree for large cases we can't count the staircase for having five but we can use a decision tree to picture what we want now as for to make it a little bit neater the left arrow or the left side basically we're taking off we're taking one step and the right is going to signify that we're taking um two steps also rather than getting to the zero keys can we make it better we see that when we are three we would kind of see when we get to zero case image because when we get to zero there is no more staircase to conquer and we are good but if we go beyond zero then we can't take that step and we know that's wrong now rather than getting to zero is there any best case that we can get to and yes there is we know that if there is only one staircase if you are giving just one staircase and you are asked to get the top of the staircase you can take just one step you can't take two because there is just one staircase if you take two they are definitely going to fall off because there is nothing for you to land onto so one is a base case because one stairs gives us one step two is also a base case because if you are giving two staircases it is clear that you can take just two steps at a time or just two steps to get to the top either you go slow you take one or you take a big chunk and take two so we know that these two are base cases whereby um you take one stairs to get to the top once in one move or there are two steps and it takes you two ways to get to the top now continuing our decision tree let's move on don't forget that left and our right signifies that we are so just to make this to start this over and give ourselves more space we have five left means that we're taking one step right means that we're taking two step our best cases are one and two cool so now we can take one step here in which case would have four left to conquer or we take two in which case we would have three now we could take for each decision now we could take one again in which case we have three to conquer we could take two in which case we have two steps to conquer but our base case tells us that when we have two staircases left then there is only two minimum so at this point we've got it to an answer because we know that there are two steps to take from this place so we're kind of like good here now let's continue with this one we take one stairs one step rather and we are left with two or we take two and we are left with one in these instances we are also good because we've got into a base case whereby two is going to give us two movement and one is going to give us one this is a dynamic programming problem and to better understand this you need to understand things like recursion and memorization because you'll be using that in this problem though there's a way to solve it iterately iteratively rather but this is just a good intuitive way this comes more intuitively to me picturing it then i'll rather solve this where i can picture the decision tree and then solve it iteratively so i feel like recursion is a good base knowledge to know to solve a dynamic problem knowledge now this three is already repeated here and we know that having this repetition this is going to be a question it's not good for our call stack basically because now we have to go down this decision tree when we've practically already gone down there and this is where we need the memoization technique whereby we have already stored decision tree that we visited earlier so for instance we visited this decision we can store it somewhere and then when we get to another decision we can just check our storage at a storage have we seen this sub problem before and then our decision tree is like oh yes you have and then we're like okay what's the results rather than going down all this path this is what the memorization technique is for to store sub problems so we don't have to go repeat um problems i've already solved and that's bad for efficiency but for the sake of this joint we're going to go down this path whereby we take one step we have two we take another step and we have one you take one step we have to take one two steps and we have one and we know that our base cases is going to give us two and one if we sum this up together we should have two plus one plus two plus one two four six eight so we have eight ways eight distinct twist to get to the top now this is the first way of solving this problem whereby we use our decision tree to traverse where this is this approach is called bottom it's called top down rather we're going from the largest number and we are going down to our base cases this is precaution and memorization this takes um two of end time complexity this is because for every decision we have two decisions to take and it's just going exponentially right our decision keeps growing exponentially but we can shorten this by using the minimization and then we reduce the um the time complexity to o of n we can go from 12 n o of n using the memorization basically won't be taking two decisions because it's possible that we visited each and then we're just storing this minimization num um yeah our memorization but if there is a way whereby we don't even have to use the memorization technique we don't have to go down the two path can we try that and yes we can actually try that part and this is the iterative top down approach whereby once again we're also going to be considering our base case and what's our base case our best case is one stick is being solved in one way you can climb one staircase in one way or we have two staircases and we can climb this in two ways now we have one and we have two if we want to climb three staircases now in our decision should we know that if you take one or you take two then basically you are taking two or one step but we've already have we already computed this we already know how many steps we are taking in one way or two ways def so we don't have to compute this again or go down this path because we already have this stored so what can we do instead is that we just sum up what we have for taking one staircase and for taking two stickers and then we have three i hope this isn't confusing i hope it isn't confusing at all because it might take a bit to wrap your head around just let's go over it again so we know that our base case is one and two in one for one staircase rather you can take one step and for two different staircases we can take two steps now for three different staircases you can take either one or two staircases now instead of computing all this all over again we can just visit what we already computed we already previously stored and just sum it up together because now these are the ways that we can get to it and we just have three basically we're climbing up of each other if we have four ways of or first decay while giving us first decades rather we know that it is always going to be the sum of three staircases and two staircases which we've computed before so we don't need to compute all over again basically we can just get the sum of the last previous computation now this is going to give us our six no sorry this is going to give us five and we know that for the fifth staircase computing this is going to give us eight which is what we got previously so this is the iterative approach and since we're just getting the last two computation we're doing this in linear time and extra space though because we are storing or saving the last previous value but there is a way to not store the previous value whereby just using variables to store them i'm going to show it in the code but i'm not going to be coding that because i don't think it's very intuitive but i'm going to provide it in the code solution linked in the description box but for the purpose of this um problem we're going to be solving using the recursive approach and using the iterative approach all right let's solve the problem so to solve recursively since we have a function i'll be calling itself we need to define that function and we need to define our base case if n is equal to basically if our staircase is 1 then we want to return one but if our staircase if we have two then we know that we want to return to these are base our base cases basically then we want to return um want to call this function on itself and you want to take one staircase plus another chunk of two staircases then we can return this function this is not going to run okay yeah this run but if we submit it we should get a time limit exceeded error like we have here and this is the case whereby if you recall when we're talking about memoization basically this is going to take a while because we are recomputing what we already computed how do i stop this okay time limit exceeded so basically we are recomputing what we already computed since we are taking we have this decision tree it's growing exponentially and this is really bad because our call stack is just calling itself over and over again this will use the memorization technique to store it now we're going to have a global memo variable and we're going to say that if n exists in memo then basically just return the um value basically if we've already computed this number before then we do not need to compute it again we don't need to compute it again just give us back this number there is a imbued function in python lru cache but i'm using this hash table because i think that some languages don't have el rio cash and might be easier for them to understand what's going on using this hash table basically instead of so we're going to be storing our results in this hash table and we will be returning this so basically what we are doing is this is a if we are giving five number of staircases and we go down we take one stairs this is going to give us four or we take two steps which is going to give us three now we are storing each of this value for four and four three in a hash table so that if we go down four paths eventually when we take one step from four we're going to visit these three again rather than solving for three all over again we already have this saved in our hash table this is what we are doing here and it's just to um solve for efficiency to make our code more efficient this is why we are doing this and if we submit this now we should see that this runs and we no longer get this time limit exceeded error now let's this is the bottom up rather top down to like i mixed up you know this is the top down recursive approach we're going from top to down like while breaking it down basically now if we want to solve for this iteratively we can kind of like have an array where we have the base cases now why do we have an array of the base cases you can store this using a variable but you know that we are kind of like pretending that our array is one indexed year whereby you are taking one staircase and you have you are doing this in just one step or you are taking two steps or you're giving two staircases and you take two steps for it we are not considering what if you are giving zero because basically that'll mean that there is nothing to climb there is no stickers to climb staircase is non-existent so in this um staircase is non-existent so in this um staircase is non-existent so in this um our area we're only considering you are taking one step you are taking to step and ignoring the zero index but i will come in and do soon now since we already have the base cases of one stickers and two staircases we can iterate over our number we already have for two so we don't need to include two we're starting from two and up to the end staircase and we're going to be appending to our array the value of the last two decisions basically if this was three there basically saying that sum the last the value at the index before and the value at index two steps before because we can only take one step and two steps at a time and we are pending it to discount and for this array keeps growing to accommodate the number of staircases that were given and eventually we are going to return the this should be square brackets because we are accessing we're going to return if this was three if this had grown it was finished compass and this is three basically we want to return zero one two we're still going to assume that the index is zero one two i want to return the index at this point this is what our answer is going to be this is basically i was going to be growing for three it's going to sum up the last two for four is going to sum up three plus five which is um five three plus two which is five four five is going to sum up five plus three which is eight and basically this is the visualization of what we are doing on line five and line six now we can just run this code and see that it works and once we're sure this works we can go ahead and submit it all right this is a very good way to practice this is similar to the fibonacci number this problem and is a very good um way to practice dynamic programming to warm us up for more complex dynamic programming problems because the manufacturing problems can get really complex but i really hope that you understood it i tried earlier to explain it as much as i could if you had not come across dynamic programming problems before but yeah let me know what you think in the comment section below thank you for watching this video see you on the next pattern bye
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236
1,706
And hero Ram is being seen after a long time, today we are the ones to see Ok Ok Ok Varna, I will explain, there is no problem, see how much Ram becomes, what are you trying to say, the question is ok, the question has been raised brother. You must have been given a grade as if you are seeing that the lines cannot be represented in the matrix So this is a matter of keeping things in mind and keeping an eye on things then it will come into it, what do you guys want to say? As for Hope, I understood that where there is this cylinder, there is a van where this cylinder is, the mines van is fine and it is not complete, only one raw is left, okay, so what to do now, what is the issue, brother. Aapke bol de rakhi hogi ball de rakhi hogi like yeh de bol de rakhi it is ok it falls till the bottom if it is following the path ok then you have to return it to the place where it has fallen i.e. return it to the place where it has fallen i.e. return it to the place where it has fallen i.e. which is the caller number? Its van is, if I show you, it is not being returned anywhere, it is not returning anywhere, this ball which is not being returned, if you look at its post, it ends here, there is an issue here, so you have to understand that it means problem. It is not so much, it is just a small thing which you have to understand, a small concept, if it is not coming, there is no problem from within you, it is not coming, no problem, see, there is a pattern that if it is in any of the indexes. And there is this one on the adjacent one too, so I am writing that it will go to row plus van column plus van, right zero and here van is from both sides, so I guarantee you that row plus van means. Well, there is a condition there, meaning if yours is from this one and this one, then it will definitely reach here and if you have this one and this one, then I am from, definitely it will reach here, it came out here but It is right here, in this sector, and when will the ball not reach down? In this case, if you have this one on the left, this one on the right, this one, or you have this one on the left and this one on the left, then the ball will never go. I ca n't, it's a simple thing, okay, so I hope you have just understood, no, I will go back once and listen to what I have said, okay, now all this has been discussed, now how to code in this. So you will understand more and how to do it, if you see a little constant, what is done in it is M grade length and your M means daily, it is starting from one and the columns continue till 100, so this one we call global constant. Or we can create a vector office of this size and we can pass reference to it. Creating global variables is harmful for health, it is harmful for interviews. So what we will do is first enlarge the screen a little. And we will do it with difference, so what do we have, let's first check the inter row, how will you get it, okay, if you do it like this from here, then you will also get the column, you have got the column bill, now what should we do ] You will have to make DP, from where to where, is it ok? It is not on charge, it does it from infinity, ok and I have written the spelling of vector very beautifully, ok, now what will we do with all this, now basically we are DP, ok. Yes, we will store it and that is, we will call the type and it will be done So in these less give the column high plus ok Yes, we will have to start, so we will start from 0, meaning the first box will come and start from that. Will mean, if this one is fine from this sector, then if the column is running with you, then let's mix it for the daily, zero earned is ok, zero earned, there should be no problem, if that ball reaches the bottom, then we will give its index. Will give the column and column com number, on which column is the induction started from zero, otherwise if we give it in mines, then we will give the vector of brick to make the solution and send the vector and percentage grade difference, do not write inter row, give one DP pass to the standard thing. If you are doing this then let's write vector in portion DP and what can we do later Apart from this I don't think there is any need for anything, everything is fine, first of all if and when our scene will end we We have to put a check that we go into the bound, so let's write a boolean function and the current column is the current N current standard row and column and what can we return if row is greater give equals zero and If the column is &gt;= 0 and the row is smaller zero and If the column is &gt;= 0 and the row is smaller zero and If the column is &gt;= 0 and the row is smaller than N and if the column is smaller than M then brother will return it. Before checking if this is valid, it is giving us the correct value, which means which condition is to be checked. We all understand okay if row of column de great and the column on which I am now is equal to us row of column plus van what are we doing okay if this is the scene then what to do now If possible, we would have checked the DP in Simply DP, now we can return the set Apart from this, if the condition comes, we will do the routine, we will call to set the DP of row plus van, I am not able to solve it, I am a little behind in the line. I am doing it will look a bit dirty but okay, now in a similar manner, we have to reduce it to N - 1, we do it by it to N - 1, we do it by it to N - 1, we do it by copy paste because I am a pro copy paste. Column minus one will be grade off. Let's also check this -1. Okay, grade off. Let's also check this -1. Okay, grade off. Let's also check this -1. Okay, I want want want In this one, there will be -1 case. In this, there will be row plus one and plus one. [ and plus one. [ and plus one. So that's enough. Interesting question, here is the code, its ok and if you enjoy this video then remember, nothing else is required, ok Radhe
Where Will the Ball Fall
min-cost-to-connect-all-points
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Array,Union Find,Minimum Spanning Tree
Medium
2287
93
here we go let's start the timer and read the question okay restore IP addresses four integers zero to 255 inclusive cannot have leading zeros so it cannot be zero one mm-hmm okay a string containing only digits return all possible valid IP addresses hmm okay by inserting dots not allowed to reorder or remove we can only insert dots and three dots we can insert three dots okay hmm okay we have an input that's only digits and we want to insert three dots to make valid IP addresses and we want to return all of those valid addresses in any order okay if so hmm I guess the length of the input we could do so the length would at most be three times four since each integer can be at most 255 so if length it's over 12 at least we know that's invalid so in example one length is 11 which means it will have to be three digit and two digits so how would we I mean we need to think about how we will solve it just like using our eyes and brains just like looking at how we would solve it first so if we have this I know that I need to use at most one that's only two digits the rest has to be three digits so we can start with 255 or 25 and those are the only two options if you start with 25 we see a five which is bigger than 255 so that's instantly invalid because it will need to be like this so that option is over so we need to have 255. and then we do this we try with two digits same case wouldn't work it has to be three digits okay now we do this we try two digits that works we try three digits that works okay so example one we have a clue of how to solve it but now let's look at the next one okay only four digits in total which means there's only one option we just have to add a dot between each digit okay what about when we have a six digits in the input string um so six stitches and our options would be like one we could do one three or one two um yeah I guess that's the only two possible um so first we try with just one digit oh so we try with one and we see okay we tried one I will try one again then we have two or one three two works one three does not work because there's um there's the leading zero the three one works okay now we try it with two okay one two or two one two which does not work because of the leading zero okay so two one and then we go two three okay three one that's the only option so we have 101 dots 0.2.3 101 dots 0.2.3 101 dots 0.2.3 okay um this is starting to feel like a pretty difficult question um how would we solve this okay what if let's make up another example um let's see let's take I mean we can do the one provided here so this is 10 digits in total so what could we have for 10 digits we could have one three we could have okay let's one three two three um I think that's probably it hmm so if we have ten digits it has to be one three and two three hmm and when we had 11 digits what are the options two three that was the only option okay so of course we had 12 digits it has to be like this what about nine digits um I could do one two three we could do hmm are there so if we had one the rest has to be eight you cannot have one here because this could be at most six okay could we do anything with two eight seven this will be the same thing or no actually no because it's it will be different this will be different at the addresses huh which means even though we have only this combination we will need to do all the permutations as well so when we have one through three we not only have to try for one three we also have to try four three one three and three one so all permutations of that same combination okay getting very troublesome all right so here we have just the possible combinations and for each combination we have to try out all the permutations okay let's finish this eight digits we could do one three one two three um if you have one three only have one three two it's the same there or one three this is still the same so this same combination then okay that's all the options what about seven digits you can have one two three what about one two um I think that's it okay six digits one equal to one on one three one two what about one two something one two that'll be the same combination okay five digits one two and that's the only option four digits then it has to be one okay that's all we have so these are ignore that um so these are the possible combinations when we have this amount of digits in the input string and for each combination except for these which are just same for each part so for all the other ones we could do permutations um and while we are checking we need to make sure it's between 0 and 255 and it's not having any leading zeros and we want to store them to return okay how would we be able to do this hmm valid okay well we do not want to separate into all these different cases because that's gonna be some not quite a good solution what if we just we are given a string and then we always try with one first until it doesn't work then we try one two and one three and then we try one two three that seems pretty tedious as well Lucian but it doesn't seem very smart um okay so if we have I mean if we are gonna try two one three and then we do this so this is gonna be so we have one two three options for each and we have four that's gonna be 81. um that doesn't feel very efficient oh gosh it's already been 20 minutes and that's haven't even found a solution already failed the interview okay I mean this seems like the only approach that I can think of right now even though it's tedious it's at least um is looks like it should work okay well I can think of something else right now so let's see if we can translate that into code so we have a string and we want to try one first and when we see it's not working we just move on to the next and then try this and then we move on to the next okay well I really don't want to have four loops but what would be the other way if you're gonna do one two three and then one two three all right I cannot think of something else right now so let's just use okay first stitches I don't think this is the solution we are looking for but it's good to start somewhere okay Okay so this string we need to does it say anything about length okay smaller than 20 so that 20. um substring we are starting at zero and using this many and we wanna convert this to Inked I mean we can do tripods we could do convert to int but is the input okay how is the input only digits okay so it will not this will not happen only digits start index and things yeah that's what remember okay we started zero and like this same as that and if I mean it's Gotta Be A from zero to 255 if it's outside of the strange we can just Skip and continue to the next round and they cannot have leading zeros okay if a one okay let's do a one if you want if a one it's not zero and it has a leading zero wait skip that as well it's in 30 to try parse okay let's see if that works otherwise we're gonna do in 32 try parts two so that's gonna start at oh so I won if I one is one and I do the length it should be the same check here right h mm okay this is repetitive which means we need to ref which means we should be able to refactor where does this start or you will just go to the end but that should be the same thing there so if it does work then we could put this result in the list which is what would this result be let's say S1 first part okay S1 Dot is to dot is three dot S4 okay hmm see if that works hmm let's go back to ours hmm yeah we are forgetting a lot of conditions here okay if s length hmm okay and if I think that's what's missing hmm oh yeah okay yeah so if we're here and there's still a lot left that it's not successful either if it's not the same then we continue okay so that's working oh okay very promising almost passed all test cases let's see what do we have here why would we have this okay because the zeros actually was parsed to hmm is it because when we pass zero a becomes zero one let's confirm that three is zero one zero yes okay so there's the problem so the special case when we have two zeros that does not work we cannot have two zeros there definitely need to refactor this because there's a lot of it's really repetitive at the moment we can definitely put that into a function and then we just call the function but let's just click make sure it works first other ones so if we have zero as the string that is also a pass if okay seems okay we'll clean up later seems like it didn't work um three okay this hmm weird okay one last okay I'll have a couple of zeros a few triple zeros hmm oh I mean I could add that in as well but it's also ugly at this point but at least we know that's the last step okay so this should work I'm really looking forward to refactoring this yes okay not at all the optimal solution okay well so this run time is ready now that reliable so this is like efficient enough I guess even though this is doing like the this is like Brute Force solution okay let's try to riff oh wait let's do timers with analysis and then try to refactor so we are doing four loops as mentioned here for each Loop we have only one two three just three loops well essentially this is not that bad because this is a constant is actually not gonna scale with input n in any way so no matter what the input is we are always gonna do in this many hmm so each for Loop will run three times and we have it's gonna run 81 times if it doesn't right into this continue so it's skipped somewhere if it does go all the way then the result is adding here so I guess we could actually count this as constant time and inside we are doing just constant type of work so I guess this even though this algorithm is just brute force and stupid it's still constant time and does not rely or depend on and the size of the input what about space we are doing we are not using any data structure we are just adding results to the list so this is all this constant all right I guess we have constant time and space okay now let me see if I can refactor this so we have functions calling functions instead of this whole blob okay and bummer that I wasn't able to use this somehow because this seems like it could save a lot of work but this would mean that we need to separate each cases all the input length separate into all different cases and that wouldn't be recursive like this isn't this is not recursive but that will have to be all different cases whereas this just handles all cases in one rhythm hmm all right maybe we have a much better Solutions we're gonna check out other Solutions later okay let's see if we can refactor this into a function yeah so we would have do we need to return anything um yeah I guess we could return the list of string okay what do we call this function it is gonna check if it's valid go on to the next bar let's call it check valid so far I only need to put in put string we want to put in I mean we are like if we look at the last for Loop we are using all the I one two three for so they need to be in the input parameters okay now I'm not super sure if this is the way to go okay I need to go eat dinner okay dinner after this motivation okay we have Inked I one two three four what else do we need um I mean we probably want this result list with us and what do we do inside foreign could we do something like if start and length part and length so we want to obvious substring what if we do okay let's see what if we do Boolean else without add um okay let's see if check valid is start would be three length will be I4 and the result string if that returns false we will continue otherwise we add the results okay so if I want if track valid here and one more is let's continue and one more zero one okay zero I won one I two three okay let's hope I did it correctly nope oh okay so we are passing in a list an eye list oh okay s watch hmm if what if we do if that's false what if this if that's true well I still need to get this hmm S one hmm Square me I still have all the i1 i204 I just don't want to do the substring thing again all right let's just do it there's a better way but it's substrained I won well this is this gotta be the stupid way to do this and um no that did not work foreign actually we are not even doing anything with this oh wait if itself okay if it's false then we skip if it's true we are actually coming okay hmm I believe I missed that hmm let's do something wrong something is wrong let's check oh actually could incorporate this as well okay if s length is smaller than or it's not a start no that would be length start plus length also return false okay let's say we have zero have S01 S01 started zero length is one that's not false substrings started to your left one we have a zero that's not true Parts is what is one so why isn't this okay so this should have passed um next okay I want to see how many is the steps it's gone foreign okay oh hmm but for this case it just simply didn't do oh why is it that it isn't even come to this um so it's something wrong here okay so that has returned false so you want to continue in each step okay so why did that return false let's see zero when we had zero one it returned false zero one foreign so nothing's wrong there a age zero oh okay I see so this is where I returned false hmm so weird that it didn't have this problem before weird before we pull this out into a method itself it was the same code so why didn't the react before okay if okay I see well these things happen yeah you're trying to edit too fast and you make a mistakes which only cost you all right so at least we got that fixed we can remove these console Red Line yeah I'm trying to stop using visual studio to debug this is well you won't be able to use the visual studio to debug during an interview or during your online assessment so now I'm forcing myself to use console Redline and whatever I can in the code itself instead of debugging stepping in Visual Studio which I usually do okay let's look at it one more time let's kind of store the results we have four check valid if it's not valid then we continue if it's valid we go to the next step for Loop check valid for Loop so we and we could incorporate this one somewhere here but I think it's fine to leave there otherwise we need to add an extra line here anyways and it will be like extra check for all the other check valid so I think this is fine and then we check valid if it's valid then we add it to the result right I was saying that this is not looking so good um it is working though is there any other way I mean then we will need to store all these substrains and we want to store those substrings then I mean we could add extra lines to store there so we don't have these but okay it'll be the same thing I guess this is fine and we are checking the length it's enough and we take out the substring and check if it's double zero triple zero and then we convert that to integer to do a final track if it's in the correct range and if it has a leading zero otherwise we are good okay my solution refactored hmm usually I'm gonna start looking at other Solutions but it's already been over an hour so I don't want to make this video super long so we're just gonna look really quickly and I will spend more time on it after I eat string and backtracking so this is supposed to be one of those backtracking algorithms which I did not do hmm I will need to work on it later to see if I can come up with the backtracking algorithm I think okay who can be this goat oh it's always so much fun looking at all the other Solutions oh look at that oh my God okay that does look very impressive okay four um wait a second okay so instead of checking it inside each Loop like I've done we're just gonna try out all the different kinds of ABCD combinations and then you just take out the corresponding substring and convert to integer and then check if they are all valid this is indeed much smarter hmm oh okay very nice indeed huh oh we do indeed have a recursive solution here okay now check out the top three okay I'm gonna stop recording now but I'm gonna come back and now that I've seen the idea behind the first solution I'm gonna yeah rewrite my solution to use that idea so usually I will just like look through quickly and get the idea then I will code that myself instead of copying their code or just looking at their code and somehow just doing it in another language so it's always good to try to code the better idea all by myself much better way to learn okay blah that's enough it's already too long yeah it took me unfortunately a lot of time to solve this so okay I'm gonna go have dinner now it's 8pm see you next time
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 `"192.168@1.1 "` 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
463
hey everyone welcome back and let's write some more neat code today so today let's solve island perimeter so this is an easy problem but i would say it's more of a medium problem in terms of difficulty it's similar to a different graph problem called number of islands and you may have solved that problem before this problem is pretty similar so we're given a grid and in this grid we actually only have one island so you can see this is like the water and this brown piece is the island so we're guaranteed to have exactly one island and the only thing we need to do is for this island we need to find the perimeter not the area right counting the area would just be counting the number of cells but we want the perimeter so for example this cell has a perimeter of three right this top or this left part this top and this right part so let me just redraw it so and this center cell it doesn't actually have a perimeter right because it's not connected to any water so this cell we can't really count the perimeter but take a look at this cell it has a perimeter of three the top the left and the bottom even though the left part is connected to the edge of the entire uh water it still counts as a perimeter so this perimeter is three and so what you can basically tell right taking a look at this perimeter we're really just counting the parts that are connected to water right watch connected to water or connected to the entire boundary right like this part is connected to the boundary so that counts as a perimeter and this part has a perimeter of two right the left and the right then you move down this part has a perimeter of two as well the bottom and the right this part has a perimeter of three and when you add all of that together we get a sum of 16 so that's what our output is going to be we just want to compute that perimeter and then return it now if you've solved pretty much any other graph problem before you can tell that this problem is going to require a graph algorithm you can do it with depth first search or breadth first search i'm going to choose to do depth first search because it's usually more simple and so that's what i'm going to do so we're going to do the depth first search algorithm right so you probably saw that coming if you've solved the graph problem before so what are we going to do well we can basically start at any of the cells right let's just start at this cell for convenience right what we need to do is we need to visit every single land portion of this graph right but that's not enough we need to somehow find the perimeter of it how are we going to do that well let's just look at it so starting here let's go in all four directions right let's go above to the right to the bottom and to the left and see which one of these neighbors happens to be land as well so first let's go up here this is clearly land right so this is one of the other cells of our island so from here let's also go in four directions let's go to the right let's go above let's go to the left and let's go down here to the bottom right but we know we already visited this bottom cell right that's where we came from so we don't need to visit it again how am i going to keep track of that well i'm going to create a set you could do an array and i'm going to call it visit right it's going to be a set and inside of that set i'm going to keep track of every single position that we visited right so the coordinates of this could be i and j right so for every position like this position i'm going to take the coordinates and put it into our set so i'm going to do something like this right visit i'm going to add to it the i and j the coordinates of all cells that we visited before that's going to help us when i actually write the code but from here you can tell that we only need to go in three directions now from this cell right so when we go above what are we going to find we're going to find that this is out of bounds we can't go there so therefore there's no land over here right so since there's no land over here doesn't that mean that this is technically a boundary doesn't that technically mean that this is going to be part of the perimeter right because if there was another cell here that happened to be land then we could not count this as the perimeter right but since there's nothing here there's no water there's no land there's nothing this counts as a perimeter so when i make a recursive call up here in our debt first search function what i'm going to do is i'm going to return 1 because that's going to be that 1 is going to be added to our total perimeter so let's keep track of our perimeter so let's add one to it right now our perimeter is going to be one we just counted this portion now let's make a recursive debt first search call to the right now i find that this is water if it was actually land i would not be able to count this as a perimeter but there's nothing here this is water so i'm going to count this as the perimeter again so i'm going to add one to our perimeter and the exact same thing clearly is going to happen when we go to the left right so since there's nothing here i'm going to return a 1 add that to our perimeter so now you may have noticed basically what we're going to be doing is a depth first search visiting every single cell in our island and once we get to the base case right the base cases when we get out of bounds we reach water or we literally reach the edge of our grid then the base case is basically going to be return one right basically we can add that as part of our perimeter and then once we've visited every single part of our island we're gonna take that sum for the perimeter and then return it right that's all we really need to do so just to show you a little bit of what's gonna happen next is okay so we visited that part now let's go over to the right over here right so in this position now we're going to do debt for search again now we can't go back there because we've already visited we can go down right and up right and each of those is going to be the base case so we're going to return 1 plus 2 plus 3 right so let's just add a 3. when we go left the exact same thing is going to happen right from here you know in any of the three directions we're allowed to move in we're gonna reach the base case we're gonna end up returning one for each of them so we can add three to our perimeter again now when we go down here right we have three directions to move we can't go back up because that's where we came from we can go left which is the base case right so add one there's nothing over here we go right that's another base case we add one and we can go down right down is going to continue our debt first search so really from this cell we're gonna be adding two so let's add two to our perimeter and now we have three directions to move in we can't go back up that's where we came from we can go to the right we can go down and we can go left if we go right we're gonna reach the base case add one to our perimeter if we go down we're also going to reach the base case add one to our perimeter so in total we're going to add two and then we can move left which is going to be the last cell that we need to visit in our island now from here we have three directions to move in up left and down right all three of those is going to reach the base case because there's no more island left for us to reach so one plus two plus three is going to be added to our perimeter you add all of these up three plus six plus four plus three that's going to be 16. that's quick math for you and so this is going to be the perimeter we visited every single cell in our island depth for search we had a very simple base case now let me show you what that's going to look like in the code so as i mentioned we are going to need one data structure i'm going to use a set but you could use a 2d array this is just going to tell us which cells of our island we already visited so we don't end up visiting a cell twice now i'm also going to create a depth for search function i'm going to put this function inside of another function so it's going to be easy we don't have to pass in every single parameter to every single function call we don't have to pass and visit into the function the only parameters we pass in are the coordinates of the cell that we're visiting so remember the main base case we have to worry about is if we're out of bounds right so if i was greater than or equal to the length of the grid basically the number of rows or if j was greater than or equal to the number of columns so if either of these are true then we're out of bounds there's a few more cases we have to check so if i is less than zero we're out of bounds or if j is less than zero that means we're also out of bounds of the grid and the last thing we have to check is if the position we reached is inbound so we check i and j and so if this position happens to be equal to zero that means we reached water so in this grid zero represents water one represents land so if any of this is true that means we reached out of bounds or we reached water which is the base case right so and we know in the base case we can return one because that means we reached the perimeter of our island right and there's actually one other base case so if the position that we reach is in visit that means we're visiting a part of our island that we already visited before so that's the base case where we end up returning zero because we can't you know add to our perimeter if we're visiting a island cell that we already visited before but if neither of these base cases is true that means we got to a grid cell and we can start adding to the perimeter so basically we're going to go in all four directions right so the first direction is going to be i is the same and j is added one right we're moving to the right i think with that uh call and we're going to basically call our depth first search four times one for each direction adding to our perimeter each time so this direction is gonna be i plus one j stays the same and a couple more directions we also need to subtract so this is i think gonna be the direction to the left j subtracted by one and i subtracted by one j stays the same so these are all four directions we've totaled our perimeter now right with well at least recursively right we see depth for search we're making a recursive call and then all we need to do is return that perimeter but actually one last thing i forgot is we need to make sure to add uh i and j to our visit set so visit set dot add i and j so that we don't end up visiting i and j multiple times when we're making this recursive call right we you see we're making recursive calls we don't want to visit i and j multiple times so now that we've finished our debt for search function the only thing left for us to do is call that depth first search function right so on i and j but the thing about our island is part of it could be water and part of it could be land we need to find at least one cell in our island that is land and we're guaranteed to have a cell like that so we just need to find it so we technically need to iterate over the entire uh or the entire grid potentially so let's do that so i and j basically we're iterating over the entire 2d grid and if we get to a position so if grid of i and j is one or non-zero of i and j is one or non-zero of i and j is one or non-zero right then we're going to call debt for search and we can return the result of the debt first search and you can see that when we run this function it does work and it's relatively efficient because this is a linear time algorithm linear meaning you see that we're only going to visit each cell in our grid once and what's the size of the grid it's going to be n times m right because n is going to be the number of rows m is going to be the number of columns this is going to be the size of the grid we're only visiting each position in the grid once or even twice but that's still going to be linear so the time complexity is going to be big o of n times m so this is the time complexity this is a linear function but the memor the memory complexity is also going to be the same n times m because you see we have a visit set right so potentially we might add every single position in the grid to our visit set that takes up extra memory so our memory and time complexity is going to be this big o n times m so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon you
Island Perimeter
island-perimeter
You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water. Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes ", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. **Example 1:** **Input:** grid = \[\[0,1,0,0\],\[1,1,1,0\],\[0,1,0,0\],\[1,1,0,0\]\] **Output:** 16 **Explanation:** The perimeter is the 16 yellow stripes in the image above. **Example 2:** **Input:** grid = \[\[1\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0\]\] **Output:** 4 **Constraints:** * `row == grid.length` * `col == grid[i].length` * `1 <= row, col <= 100` * `grid[i][j]` is `0` or `1`. * There is exactly one island in `grid`.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Easy
695,733,1104
981
hey guys what's up this is steve today let's go through another legal problem 981 time based a key value stall let's take a look at the problem description first create a time-based keyword installed create a time-based keyword installed create a time-based keyword installed class time map that supports two operations number one is set which takes three parameters key value and timestamp so this is kind of a mutation or addition to a regular hash map which takes an additional parameter which is timestamp usually a hashmap or just a regular commonly seen map just takes two parameters one is key the at least value this one is just a mutation third no number two operation is get so gap instead of just a regular get method which takes one parameter only which is the key this one takes two the addition to this is a timestamp all right so let's take a look what the get method requires it has three requirements number one is returns a value such that set key value timestamp underscore previous was called previously with the time stamp underscore previous less than or equal to timestamp okay if it's not clear yet no worries we'll go through one example then things will be cleared second requirement is that if there are multiple such values it returns the one with the largest time stamp underscore previous so we're trying to find the most recent one if it's possible third is if there's no such values we can return an empty stream empty string here okay let's go through this one example here's the input timestamp is just to initialize the constructor to call the constructor and initialize the object output is now which makes sense set returns now right so set is always set written type is void so it doesn't return anything so set what do we set we said the key is full the value is bar and timestamp is one so this is what we set and then we call get we get foo and timestamp what so we're going to get bar right this is a perfect match and then we can call get through time stamp three we call get foo is here timestamp three we don't have a timestamp three here the biggest one the most recent one the closest one that is up to three is one so we return bar here as well then we call set now we call set with what because that with full it's still full and the bar the value becomes bar two with the timestamp full okay so here it doesn't necessarily mean that the key with the key equals to full the timestamp is one the value is part this entry doesn't necessarily mean get removed right it's actually not it's just the meaning that we have a new entry with a more recent timestamp matching to the same key got added into this mutated hashmap right so that is why when we call get fu is key is full and timestamp is 4 we're returning bar 2 here and then we when we call get full five timestamp is five we're not returning bar anymore because we have another timestamp which we have another entry with matching the same key but with a more recent timestamp is four instead of one so when we turning this one we're returning this one's value which is bar two here this is how this mutated hash map or bitcoin time-based keyword install bitcoin time-based keyword install bitcoin time-based keyword install this is how it works if we can work through a second example things will be even more clear like say the input is the timestamp so this is to initialize an object of this time-based key value style time-based key value style time-based key value style set so we set what set left this is the key and timestamp is 10 value is high and then we set again we said left this is still the key the same key and timestamp is 20. value is low so we set twice we set two entries in this time based key value stall right we can retrieve both 10 and 20. we can retrieve both high and low you see high and low both of them are retrieved that means none of the entries based simply based on the keys are erased if there is a more recent timestamp mapping to the same key comes in right that's what it means and then we call get one two three four five we call get five times so see here the first get we call with love the key is always love since we enter it only two left you can call whatever you want but it's not going to return anything for the simplicity of this example it costs get five times all with the key equals to love and then with different timestamps timestamp the first example timestamp is five what are we going to get we're going to get nothing right it's an empty stream why is that because there is no such a temp time step that is less than or equal to 5 right the minimum is 10 right so that's why it's returning empty stream next we call getlove10 timestamp is 10. luckily we have one timestamp that exactly matches 10 which is here that is why we're returning height and then third time we call get love do we have a 15 time stamp in the mutated hash map no we don't have it and then we try to find the last previous one that is most closest to 15 which is what which is 10 right so we said 10 here we set timestamp 10 value to be high that is why this call will return high here right i hope that makes sense and then we call left still the same key but timestamp is 20. so we have an exact match so we just return no here and then we call the same key left and then timestamp is 25. do we have a 25 timestamp in the stall no we don't have it but the closest one that we have is a 20. what does 20 have 20 maps too low that is why we're returning low here so the idea that come to me is that we can apparently we're going to use a map but how can we have a one more dimension which is the time step if we are simply using a regular hash map the key is just the key and the value is just the value then how do we get control of the timestamp it's apparently one more diagram one more dimension in this hash map right um there are multiple different ideas you can um so basically you can have you can create an object and then for the value of the hashmap you can use that object this object only has two fields one is timestamp the other is the value right you can do it that way the problem that comes with that idea is that you have to sort everything in that in the value set right based on the timestamp then you try of course you can do you can use a linked hashtag since the timestamp is it is strictly increasing right it says timestamp are strictly increasing and then you can do a binary search that is one way the more straightforward or the easier way for me is i think we can use a tree map right we can use a tree map instead of creating a customized object maybe you can do that time and space complexity might not be even worse to me i feel it's more concise that we can just use a tree map as the value as the type of the value of the mutated hashmap the key of the hashmap is still going to be the key it's still going to be the key and then the reason why we want to use a tree map is because for tree map all of the key set it's ordered by descent by natural order which in this case is what is exactly what we want right then first we'll call tree map get key and then we'll get a hash map inside this hash map the key is going to be the timestamp and it's in order so that we can very easily get whatever we need if it exists it's if there's a perfect timestamp match we can just directly return otherwise we can call floor key which is going to find us the greatest the number that is less than or equal to the timestamp i hope that makes sense let me put the idea into the actual code hopefully that help that will help so here we'll have a map type is going to be stream and then the value type is going to be map then here what we'll have is integer and then string i'll just call it map so once we initialize this we can just call it hashmap all right what then we do set so first we want to check if map contains key this key if it doesn't or just initialize one put new tree map in here and then what we'll get is we'll get this right so we get this what do we get the one that we are going to get is this tree map i need one more oops i need one more close parenthesis here and then oops this is wrong what i want is this type and i'll call it the time map for simplicity and then we'll get this now we're set it time map put time step and value this is the sand method all the way up to this point is very clear no any questions i don't believe so it's very straightforward right we can all that this class will have is just a map the type of the map is a string and a tree map all right and then we a little bit trick here in get is that we can call an api in tree set which is going to help us to get the closest timestamp that is the small that is either smaller than or exactly equal to the timestamp all right so first we'll have this i'll just call it time map again and then we'll call map get key uh what if key doesn't exist uh let's not consider that do is there a constraint will be called this many times operation strictly increasing let's not consider keynote doesn't exist yet see if it can be accepted and then so what called previous time map floor here so this api is going to return us the number the timestamp that is closest but still smaller than or equal to this timestamp this is the beauty of using a tree map uh and then let's use integer instead of into primitive type because it's possible that this one returns me and now if that is the case priv time equals now that means we don't have such a possibility which is this one right which is in this case it's written it's retaining an empty string which is here love the key does exist but the timestamp five there is no such a thing in the scheme a value like in the time-based key value stall time-based key value stall time-based key value stall that is exactly smaller than or equal to five so we're returning empty string here return empty string otherwise we'll just return time map get previous time all right and this is it let me hit the run code to see there if there's any compile error all right no compile error let me hit submit all right accept it as not super impressive in terms of time and memory um but it's fine or i guess there is no such a connotation that it's not all of the test cases are very valid it's not testing the counter case of whether the key exists in the key value stall or not let me hit submit one more time 50 20. no big difference but anyway here is the idea of how we can choose a combination of different data structures of existing diff different data structures do a combination of permutation to whatever you want to help solve the problem hashmap is a very powerful and very mature non-existing data and very mature non-existing data and very mature non-existing data structure feel free to use that to the best of your knowledge um problems like this may come in your real onsite or phone screens which is very common so practice this hopefully this makes sense if it does please do me a favor and gently tap the like button that's going to help a lot with the youtube algorithm and i really appreciate it and don't forget to subscribe to my youtube channel as i have accumulated a lot of different data structure algorithms computer science or interview or amazon web services certification exam tutorials hopefully i'll just see you guys in just a few short seconds in my other videos thank you very much for watching i'll see you guys in the next one
Time Based Key-Value Store
delete-columns-to-make-sorted
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. Implement the `TimeMap` class: * `TimeMap()` Initializes the object of the data structure. * `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`. * `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `" "`. **Example 1:** **Input** \[ "TimeMap ", "set ", "get ", "get ", "set ", "get ", "get "\] \[\[\], \[ "foo ", "bar ", 1\], \[ "foo ", 1\], \[ "foo ", 3\], \[ "foo ", "bar2 ", 4\], \[ "foo ", 4\], \[ "foo ", 5\]\] **Output** \[null, null, "bar ", "bar ", null, "bar2 ", "bar2 "\] **Explanation** TimeMap timeMap = new TimeMap(); timeMap.set( "foo ", "bar ", 1); // store the key "foo " and value "bar " along with timestamp = 1. timeMap.get( "foo ", 1); // return "bar " timeMap.get( "foo ", 3); // return "bar ", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar ". timeMap.set( "foo ", "bar2 ", 4); // store the key "foo " and value "bar2 " along with timestamp = 4. timeMap.get( "foo ", 4); // return "bar2 " timeMap.get( "foo ", 5); // return "bar2 " **Constraints:** * `1 <= key.length, value.length <= 100` * `key` and `value` consist of lowercase English letters and digits. * `1 <= timestamp <= 107` * All the timestamps `timestamp` of `set` are strictly increasing. * At most `2 * 105` calls will be made to `set` and `get`.
null
Array,String
Easy
null
838
hey everybody this is Larry this is day 27 of the legal daily Challenger Tuesday hit the like button hit the Subscribe button join me on Discord let me know what you think about today's forum and yeah in the video and so forth um hope y'all are having a okay week and excellent week whatever you like um yeah end of September a couple of days left let's get them let's go uh push Domino's 838 replace each Domino vertically upright and we sometimes we push some damage left or the right uh okay so then we'll go to do it stays upright okay so the left pushes the one next to one on the left okay so what does this mean this one means wait didn't draw they drew one for example two but not one okay fine uh so okay so I see so that is a domino and L push forces as an L um and then that if it's not pushed or if it's standing still right how do I in let me I'm just reading the output and kind of mapping it to here um okay so the third one is still because they didn't move but and this other one is still because just left and right okay I mean um so you can phrase it um and it is just that whether a domino is closer to a left or closer to the right um of course if you're doing naively it is going to be n Square so let's not do that let's uh let's actually pre-calculate the courses left and of pre-calculate the courses left and of pre-calculate the courses left and of course is right and oh yeah uh or how and I'll be more precise um left from the right side and right from the left side right so yeah um yeah and basically what we want to do is um okay so let's take we have n is equal to length of dominoes um then left is equal to say um let's say infinity right Infinity times n and now we said Infinity is equal to 10 to 20 Works mostly for me and then now we go from right to left because we're going to see the closest um foreign to the from right to left and this is actually similar to what is it diff or the acute degree of the contest if you did that one where you know you just pre-calculate you know you just pre-calculate you know you just pre-calculate you know the closest one maybe I would miss remember that one though something similar to that in any case so yeah so if Domino's of I is equal to um L then left of I is equal to zero otherwise F of I is equal to the left of I uh plus one right something like that um yeah I mean it's a little bit awkward because just because this is uh I plus one you know I plus one has to be less than n or something like this because otherwise then this is just we'll just keep it at Infinity I think that's okay it's a little bit awkward but it's a little bit okay um yeah and maybe the question is can we generalize this uh yes a little bit so let me rewrite this actually um let's go from left to right just to make it simplify a little bit um okay and then now we can just write it more naturally but it's like harder to make mistakes maybe so with dominoes is because of I is dominance of I is equal to Y then we set rate of I is equal to zero right else if I guess oh Sif um I minus 1 is greater than zero then writes up I is equal to Y sub I minus one plus one right and of course this can go over infinity per se but that's fine and the reason why I kind of delete data piece and quote it this way and so then now we can abstract it a little bit um so then we can go left uh closest maybe something like this um and then you have a an array which is called Domino's and um a direction say right someone like this and you know and is still do um yeah and then here we just set it the direction right and then now we can say right as you go to closest uh Dominos um we actually want to add um and right and then now left is equal to cosist of dominoes in Reverse left and then of course we reverse the answer anyway um okay so then now we have left and right and we are able to do the abstraction in a very quick way and yeah and also of course if you're doing uh tdd or just like testing which you should uh you could also just test this now and that makes it easier to kind of you know yeah just makes it easier to do it um except I'm one because I forgot to return the right okay fine but yeah and then now we can just do for eye in range of and um we also want to I think the one thing that we might be have to be a little bit careful with is just Infinity values so we can do something like left of Pi if you go to Min of infinity left of I um just I mean maybe you could handle it earlier as well to be honest but I'm just going to do it this way just to be a little bit queer and then here we go if left of I uh well let's say we have an answer away right um I like using none because if you forgot to throw something in you'll see it on the X on the output versus like if you have a default value I mean maybe it'll give you a good answer but on the debugging it may mess you up a little bit I mean this one is easier to see I think um okay so basically well first of all we want to set a and sub I is equal to abdominals of I right I guess it doesn't really matter because if this is zero then it'll just be that one anyway right so we'll do now we want to call someone if this is less than y sub I then answers of I is equal to left else or else if left sub I is greater than y sub I and sub I is equal to R else and oops why did that okay I don't know is it going to period right um do we want in a string okay we do one in a string so then we just return you know we join into a string that's pretty much it this is going to be linear time linear space hopefully it's also right it doesn't matter what it is if it's not right I see hmm I forgot a case or maybe I'm just really wrong oh yeah I because basically this is saying that um just left I actually have done about this case but then I was too slow to kind of remember it while I was typing this out excuse me but uh but yeah we also need to reset that's all I forgot to reset that's why but that's the good thing about this abstraction is you only have to correct the code in one place so here um if this is your direction we actually you know want to set this um I think else if Domino's of i as you go to period that um then we I guess do this actually do this thing and then else if this is the opposite direction then we actually want to set just as you go to Infinity again um yeah I guess yeah okay there we go so yeah so I think that was a misfortune if you say uh mistake a typo more than a typo just forgot uh to be honest but as you can see that's the beauty of abstraction right is that because of this we fix it by fixing one place and we don't have to do in two places even this to be honest we can fix it in one place right we can just be like uh and then now we could get rid of it in two places right um so yeah hopefully this is actually right a device then it doesn't matter how pretty the code is if it's wrong right let's give it submit this is going to be linear time in your space hopefully it's also right uh yeah well I don't know why this is so much slower okay uh yeah 910 day streak so that's kind of nice why is this type slow this is linear so I mean I guess we do a little bit more linear than we can I think that is one thing is that if you do it if you buy two for Loops like this way um it is a little bit faster only because you know you're not doing two reverses but um especially if you're you know writing in the contest situation um you know you just want to write them as fast as possible that set obviously there is especially lead code is a little bit awkward because sometimes you do want to have time and one out of space and all this stuff so I don't know uh okay cool that's pretty much all I have for this one let me know what you think line your time in your space I think I don't have to explain that deeply into this one you've never did a little bit more linear time and space constant but yeah uh that's what I have so stay good stay healthy to good mental health I'll see y'all later and take care bye
Push Dominoes
design-linked-list
There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string `dominoes` representing the initial state where: * `dominoes[i] = 'L'`, if the `ith` domino has been pushed to the left, * `dominoes[i] = 'R'`, if the `ith` domino has been pushed to the right, and * `dominoes[i] = '.'`, if the `ith` domino has not been pushed. Return _a string representing the final state_. **Example 1:** **Input:** dominoes = "RR.L " **Output:** "RR.L " **Explanation:** The first domino expends no additional force on the second domino. **Example 2:** **Input:** dominoes = ".L.R...LR..L.. " **Output:** "LL.RR.LLRRLL.. " **Constraints:** * `n == dominoes.length` * `1 <= n <= 105` * `dominoes[i]` is either `'L'`, `'R'`, or `'.'`.
null
Linked List,Design
Medium
1337
34
hey hello there so today's the binary search question that I picked as the city for fine first and last position of element in sorted array the question is just as follows we have a sorted integer arrays and we want to find the starting and ending position of a given target value the algorithm has to be in log in time so we apply binary search twice first to the first time to find the first position for the element the second time to find the last position of the element yeah so that's pretty much how to solve this in log in time I use in binary search twice and two days ago I was doing a little bit review so in my documents I was I have the template for search leftmost and search rightmost I think the code has to be modified a little bit from my last time the upper bound opposed originally said this to be the size of the race abstract by one you know points to the array loss the location that will actually cause problems so after some analysis and very fun debugging when I try to just copy and pasting those two pieces of code here and keep saying arrow find that I should actually increase the upper bound to be the full size of the Ring so yeah just as a real force off the memory I should try this one more time with another language I guess so we're gonna have two methods one is called binary search left which is going to take a reference to this vector and a integer target what this does is to apply binary search to find the left hand most occurrence position for this target value so initially the lower bound is 0 the upper bond is the array size it's not the array size subtracted by 1 so the condition is same thing and we are checking that if we are search for the left we want the left and most so what we want is that the middle element we are looking at is less than strictly less than the target so that when we you know keep searching the value that we find is going to be the first one that's actually equal to or larger than the talked about you that's pretty much the binary search left the binary search right it's almost identical except that we change this condition to be less than or equal to so the left the one when it's you know finally equal to the height the search space pinned down to one number that's going to be the first number that's largely larger than so as a result in this right code we return Aleph to substract by one so use this two sub routines to solve this problem we're basically just gonna grab try to apply this on this array with the target value and do that for the right as well and then we pretty much just going to return the pal that was on caveat to that we need to check the case where we have negative on negative 1 that's when actually the right is sorry what's happening hope my code is saved ok so that's when the feels very tricky why that just happened yeah we wanted the right to be larger than or equal to L if that's the case then we can safely return this pal otherwise it will be negative or negative on the case will we not be able to find a target if that's the case then I'll and right the left and right the right is actually going to be smaller than L it can look at the code and reason about that yeah so pretty much that's just the code the binary search left and right the only difference is this equal sign and the return L minus 1 in the right version is the left version just strictly less than so that we always want to bump L to be at least target you at least equal to the target it would be the first one that equal to the target this one I will end up with the first one that's larger than target so we return negative 1 to be the last one that equal to the target if it does exist and here we just have a little condition checking here to make sure that we don't return something that's funny you know if it's the case that we would likely to return funny that's because the number is not in there so we return negative 1 yeah or there could potentially be another case is that the array just have one number this will be catched in this condition check in here and we're returning negative 1 as a result so I think this is the code I sure I should quote this right No initializer list cannot used on right hand side operator what's the problem can I just yeah it works so this is the binary search code to solve this question one to the left one to the right
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value. If `target` is not found in the array, return `[-1, -1]`. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[5,7,7,8,8,10\], target = 8 **Output:** \[3,4\] **Example 2:** **Input:** nums = \[5,7,7,8,8,10\], target = 6 **Output:** \[-1,-1\] **Example 3:** **Input:** nums = \[\], target = 0 **Output:** \[-1,-1\] **Constraints:** * `0 <= nums.length <= 105` * `-109 <= nums[i] <= 109` * `nums` is a non-decreasing array. * `-109 <= target <= 109`
null
Array,Binary Search
Medium
278,2165,2210
1,947
hey what's up guys this is chung here again so this time lead code number 1947 maximum compatibility score sum okay so now this time we have a survey that consists of n questions right where each question's answer is either zero or one okay and then the survey was given to m students right from zero to n minus one and also same m mentors also numbered from zero to m minus one basically each of students and mentors will answer often questions okay and then the student's eye is a list of integers which contains all the answers of un questions for the student same thing for the mentors right and then basically each student will be assigned to one mentor and each mentor will have one student assigned to them right so basically one-to-one relations right so basically one-to-one relations right so basically one-to-one relations and then there's like compatibility score of a student and the mentor pair is the number of the answers are the same for the book for the both for both the student and the mentor right for example if student answer is one zero one it means that for answers for question zero student answer is one for ounce for question one student answer is zero two for two is one and the mentors answer zero one right similarly for question zero one and two and the compatibility score obviously is two because only two of them are the same right and then our task is to find the optimal student mentor pair to maximize the sum of the compatibility score right and we just need to return that compatibility score right so for example so we have three students and we have three mentors and when there are like also three questions in total right so the optimal uh pairing will be like this right where the final answer is eight okay and for this one it's like zero right so that's it and then the constraint is like this right i mean m and n is also only like eight right so you know every time when you guys say the constraints it's like only this like maybe smaller than 10 then it means that you know probably the time complexity will be like 2 to the power of 10 or 8 which means it's going to be a full permutation right so that and that's exactly what we were going to do for this problem because there's no greedy way to optimally assign the method to any student so which means we have to try all the possible combinations for each student against each mentor right basically what does it mean means that for student 0 we're going to try to assign a mentor from 0 to m minus 1 to the student to still than 0 and then for still the one we're going to try the same thing but we have to do like in the back tracking manner right because once the mender is gone we cannot assign this mentor to the other student that's why you know this is actually a common strategy for like a bit mask right where you know we're gonna have like a dfs okay we're gonna have like dfs where the first uh the so the first uh parameter is gonna be the i means basically now we are assigning the mentor for the current uh student okay and the second one is going to be the mat the bit mask right so the bitmask is still is what is the uh is the status of the after all the mentors right basically zero means it has not been assigned one means it's already been assigned let's say we have a zero one zero right then it means that okay we have assigned this mentor and this mentor which means only the zero ones can be used at this moment right and with this one right this two here we can basically we can try all the possible combinations and then the last one of course is going to be the score right we're going to also maintain the current score for each of the pair and in the end we just maintain uh update the final answer right uh whenever we have a sign uh each student visits corresponding mentor right and then we simply update the score right uh to find the maximum one so that's it right and pretty straightforward and let's do it then um i'm going to call it backtrack right so like i said the first i mask and score right and so if i is equal to m okay we haven't defined the m and n yet so m is going to be the length of student right basically the same also for the mentors and n is the number of questions going to be a number of uh do we need this n here probably we don't even need this n okay oh no i think probably we do okay so that's the number of questions right number of questions okay and then for the back tracking right so when i reached the end then we know okay we have assigned all each mentor with each student with this mentor that's when we need we can update the answer right so let's do this now look answer right and the answer is the max of answer dot score right um yeah and then we return right and then for j in range of m right so basically for the current student we're trying to assign students right try to assign all available mentors right to student high right and we have in total we have j uh we have m mentors we just need to check if the mandate is available right so basically the mask we check if that the mask value is uh it's zero okay this one equals to zero right it's a little bit uh bit manipulation here right then we do backtrack right back track of what backtrack of i plus 1 right and then for mask it's going to be the mask we're going to mark that mentor to be unavailable which means we're going to mark that one two into one right that's how we market it into one and then the score right so the score will be score plus uh okay well yeah we need to have another helper functions to get the score right so we have student and we have the mentor right so answer is going to be 0 and for i in range of n this time right so if s i is equal to m i then answer plus one okay return the answer right so here we think we can simply just call that helper function of students of i right then the mentor is of j okay yeah so that i think that's it right and then we can do a backtrack of zero okay right and then return the answer yep missing one of the required record oh here oh right here so okay accept it and let's run it all right cool so it works right because it can pass because of time complexity for this one is what um so we have i here right so i is like we have n right n times 2 to the power of n right and then for each of them we have like what each of here we have oh then this is going to be another times n for this one and times oh we have m and i'm sorry so the i is m right the mask is so is 2 to the power of m and then inside here we have a m and then here is another it's another n right this one is it's a of n here is o of m right so that's the total time complexity i think right and so for this one do we need the dp here uh to memorize the result you know probably not um because you know i don't think there's any overlapped uh subs uh scenarios here because we have given because the i always moving forward right and every time is moving forward you know the state will be different so basically they will do we don't need to store we don't need to use like dp to store any of the previously calculated results because the eye is always moving forward yeah i think this is one way of doing it and the other one is what i think the other one is we can do a maximum at the beginning instead of updating this one to the end so what i mean is that you know so for this one you know i'm passing this score along the way to the end to update the final answer right or we can what we can always we can return this score all the way to the top to update the uh the answer so that we don't have to pass this one lot in the back tracking so this is what i mean um so here uh we don't need the score anymore right so instead whenever we reach the end we simply return to zero it means that we don't have any score that we can collect right and then here we have answer dot zero right and here uh we don't need this one anymore it's gonna be so something like this it's gonna be answer equals the max of answer right here we have this and then we don't need a score here right it's going to be the mask and all we have all we need is this one plus right this one and then grab score plus the backtracking right so this one is this we need a okay right and then we simply return the uh the answer in the end right that's another way of solving this problem instead of passing the score along with it we simply just accumulating the score up right we pop it we ma we bubble it up to the very top and then every time we do a maximum of that so this one is a pretty this is like a very standard uh classic dp template right so if i run this one i believe this should also work oops oh so and then we can simply return the back track right okay if i run this one this would also work yeah right so same similarly and this one i know with this one you know we can definitely use like a memorization in python right it's going to be a lru cache right none right so this is like very standard dp solution right with like two uh two-dimensional dp right so if i run uh two-dimensional dp right so if i run uh two-dimensional dp right so if i run this one this should also work oh i think i'm i was wrong about the scenario the branches analysis okay yeah i thought there wouldn't be any uh duplicated scenarios but given the uh the run time seems like the dp one definitely runs much faster than the non memor memorization version let me think oh i see why because okay i think i was totally wrong yeah sorry because when uh you know if the i you know if the first person uh if per first person picked a mentor uh one and second student picked mentor zero right or if the per or if the first person a student picked mentor zero and the second student pair is the mentor one then the end result of this i will be the same right basically and then when we add like when we are reaching the person to here uh sorry the student two here you know we will end up with the same mask right basically both the first mentor and the second mentor will be has already been uh un uh used right so which means that no basically yeah you're i was wrong about that so we should definitely use dp uh the memorization version of the this backtracking actually it's not a backtracking that i should call it dp here instead you know but it did it does have some backtracking mechanism uh concept in here right so this one should like call dp uh because you know like i said you know both of the this uh both this uh this branch and this branch will end up with the same state here right that's why you know we need to we should memorize this the result for this state so that you know when the second branch reaches the state it can simply return the value right that's why you know okay correction we should step for this one we should definitely use this kind of dp uh version right because you know like i said so for this one though the time complex they will be correct like the one i said is going to be m times uh 2 to the power out of m right and then for here it's going to be a m times n right so this is going to be a time complexity this is the one with the uh the memorization because you know i think the time complies complexity analysis for the previous one was not accurate because they could be duplicated state right or the duplicated branch yep i think that's it right i mean i know the uh this video is a little bit confusing because uh because of my mistake at the very beginning i thought uh we don't need to use dp to solve this problem but you know turns out we should use dp instead and yeah i think other than that it's like a if we now i got to think about it this is a very like not another very classic uh dp template where it's a 2d dp state where the first one is the index second one is the beat mask right and then yep i think that's it and thank you for watching this video guys and stay tuned see you guys soon bye
Maximum Compatibility Score Sum
number-of-different-subsequences-gcds
There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]` is an integer array that contains the answers of the `ith` student (**0-indexed**). The answers of the mentors are represented by a 2D integer array `mentors` where `mentors[j]` is an integer array that contains the answers of the `jth` mentor (**0-indexed**). Each student will be assigned to **one** mentor, and each mentor will have **one** student assigned to them. The **compatibility score** of a student-mentor pair is the number of answers that are the same for both the student and the mentor. * For example, if the student's answers were `[1, 0, 1]` and the mentor's answers were `[0, 0, 1]`, then their compatibility score is 2 because only the second and the third answers are the same. You are tasked with finding the optimal student-mentor pairings to **maximize** the **sum of the compatibility scores**. Given `students` and `mentors`, return _the **maximum compatibility score sum** that can be achieved._ **Example 1:** **Input:** students = \[\[1,1,0\],\[1,0,1\],\[0,0,1\]\], mentors = \[\[1,0,0\],\[0,0,1\],\[1,1,0\]\] **Output:** 8 **Explanation:** We assign students to mentors in the following way: - student 0 to mentor 2 with a compatibility score of 3. - student 1 to mentor 0 with a compatibility score of 2. - student 2 to mentor 1 with a compatibility score of 3. The compatibility score sum is 3 + 2 + 3 = 8. **Example 2:** **Input:** students = \[\[0,0\],\[0,0\],\[0,0\]\], mentors = \[\[1,1\],\[1,1\],\[1,1\]\] **Output:** 0 **Explanation:** The compatibility score of any student-mentor pair is 0. **Constraints:** * `m == students.length == mentors.length` * `n == students[i].length == mentors[j].length` * `1 <= m, n <= 8` * `students[i][k]` is either `0` or `1`. * `mentors[j][k]` is either `0` or `1`.
Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a valid subsequence for x , then the subsequence that contains all multiples of x is a valid one too. Iterate on all possiblex from 1 to 10^5, and check if there is a valid subsequence for x.
Array,Math,Counting,Number Theory
Hard
2106
1,286
at all so today continuing on this be weekly contest 15 the third the problem iterator for combinations so let's see what the problem asks us to do so it's 1286 iterator for combination and the problem says we want to design an iterator class that has three things a constructor so iterators usually have just the constructor next method and has next and in this method the constructor has two parameters a string of characters that are sorted in distinct lowercase English or sorted order they are distinct and they are lowercase English letters and we have a number combination length also as an argument and two other functions next the written the next combination of specific length combination length and hasnext which returns true if and only if there exists an X combination right and so we wanna what we want to do here is we want to create an iterator that for ABC gives us a b a c and b c and so you can see here it gives us a B BC and AC so you could see it gives us the combinations in order right there is no C a right because that's not in the right order right and so how can we implement something like this so right away combinations here it's it already tells us if they're in iterator for combinations and that's exactly what it was um and what I well asks us to do so right away we should think about creating combinations right because if you look here the characters length is 15 right but the problem is that next and has next may be called 10 to the power of 4 times so next and has next needs to be really efficient but the constructor initialization can be a liberating it can take a little bit more time right and so for to get a combinations we can just is backtracking that the permutations in combinations and these kind of things that generate a list of choices we can use backtracking to solve that so let's see how comes solve this problem so as we said we as we will use backtracking to solve this problem and then I have a video I will put in the description that explains in details how you can kind of a blueprint to solve backtracking problems and that's what I will be using here and for backtracking essentially what that video says is that you need to find when like what is the partial solution that you will pass around in your recursive function for backtracking and we need to find well when does that back when does that partial solution becomes a solution is the solution how can you know that it's a solution so that you can just process it and then what does processing the solution look like and then at each point of salt like at each partial solution what are the candidates that you can go to next and if you can come up with all of this then maybe you could add some pruning for your backtracking solution but essentially these are the main steps and so what is our partial solution here so what we want is generate combinations of characters so for ABC want to generate combinations of lengths let's say two that's what the example says so what do we need to do so to generate combinations of length two of ABC well starts with a and so start with a first and then add to it the next character a B or skip B and then do C so AC and then we also have BC okay but I want to do them in order oh sorry here pick B and then pick a her you have to pick the next one you can't pick the one before that's the difference with permutation and so we can only pick BC so this is the that list that we have right and so with the order you could see is a B first and then a C second and then three BC right and so here for the order thing that means that in our combinations must let's say we are at a position I and then when we move we can only move to the positions after it so our or Lascars position index so our for loop for the index in characters well it would be in the range starting from the position itself so that we can get that character and then you only move to the next you don't go backwards because we want only those in order right and so already we know that we need to know what is our character partial solution so that we can append B to it so we need the s which is string so far right and we need the index in the current we need to know two things actually we need to know the index in the current character set right so index and this is index in current character set and we need to know also the index in the combination itself like this a is index zero this B is index one so that we can know when we have a solution is when the length is equal to the length of the combination that we are asking we can also do length of s right actually let's do that so that we can reduce the state for ourselves but essentially this is all we need to know the index in the current characters so that we can only go so that we can process them in order and we need to know what s is and one do we have a solution well we have a solution when the length of s is equal to the combination length that the problem asks us to follow right in this case when the length of the string is equal to 2 what is the plot processing a solution so the problem asks us to return every time when we call next we want to return the next combination right so we could either have a list add them to a list and every time keep track of the index so that every time we return the next in the order or the other thing we can do since next once you move next you can't move back so we don't need to keep track of the previous element we can just use queue and when we are asking next we can just pop the element I returned it and so here our processing can be we initialize in the constructor initializes a queue right first we initialize a queue and then here we can just pop from the front the here we can just sorry add to the back of the list because the order has to be a B first AC first BC first so BC has to be in the backup of the list so we append to the cube the s the string right and then when we want to in the house in the next call we can just call Q dot pop left that will give us the front which means it will give us a B first and an AC and NB C now processing the candidates we said we have this for loop right so that we can get the right order so here that means we need to do a for I in the range of to get the next candidate character than we need to append and so index and then length of chars and what do we need to call our backtracking function again let's call it helper our backtracking function here so we need to call helper well the new string which is the partial state we just chose this I to be added to it so we do Charles of I and then what is the index of the next character to go to what we have to in advance the index by one so that we don't repeat the character itself multiple times so index plus one and that's pretty much it that's all our backtracking solution needs so now let's try to cut it so let's just try to cut this generate portion the other thing the other portion is really easy to do we'll do it only code but the complete backtracking function for generating combinations in this case is well we will need to define our helper function that gets passed it s which is the partial solution and the current index in the character set and we check if the partial solution became is a solution right now so we check if the length of s is equal to the combination length then at that point we can just append it to the Q so the Q would be a variable on the class so Q that append s right and then after that we go through the candidates right we go through the candidates so for I in range of index and length of character we called the function again and now since we chose the character position I will do s plus and we need to go to the next position in car cars and so I plus one right and then in the next call we will skip the one in at position index and world pass in the wallet in this index plus one which is in this case it will be doing AC right and that's pretty much it now let's just take this cuddle up with the full solution for the combination iterator okay so now let's call this solution up so we already know the our generate function that we need to do but here what keep track of the characters we have that were passed as parameters and the Skip track of the combination line and we will need to also have it define out our queue that will put elements end so collection is that thank you and want me to enforce collections here and then we will need to do general do the helper function with backtracking so that we can fill the queue with the all the combinations possible right and so that will be as we said the partial state s or the partial solution and then the in the current index that we are at in the character set and so we define that function partial solution and the current index and then we check if the length of if we have a solution so the length of s equal to if it is then we add to the queue we process of the solution which is just adding it to the queue here otherwise we all say return here we go through the candidates States so in generate in helper of no sorry in the range of index so we want to go from the count index all the way to the end because we want them in order length of characters and then we call a helper function again for the next state here and so that would be S Plus what the character that we chose and then the index of the next character to choose which is just I plus 1 sorry and that's pretty much it and for the next function while we could just as we said cut from the key word since part from the front of the queue since the smallest combination we would be would have been added first so it would be at the front of the queue and so to part it off we do pop left but the problem is this will give us well let's see first of all this will give us and then if it's wrong we will it's part if it definitely is wrong we'll fix it so that we can see the error and then here we'll just check that soft queue is not empty so we could do it by checking that let's say the length is bigger than 0 this will check that it's not empty but we could also just convert this to a pool and it will be true if the list is not empty and it will be false if the list is empty that's something in Python so let's see what next year will give us um yeah I need to say self here mmm this is soft target okay so actually it's pretty good it's already passes because we just added it like this so now we can just submit okay so this solution passes yeah so that's Co the other way we can use this is a sterile I used like a function here to generate because it's good to get some practice with backtracking and in an interview also probably they won't let us use a library to do this but in Python there is this library called import tool ETF tools sorry called it a tools that has this function called combinations where you could give it an iterable so it can be even a list of characters and the length of the combination that you want and it will generate the combinations for you in the right order so essentially it will be doing this helper thing for us so if I use the example that we have ABC 2 and just convert it to a list you could see it give us pairs of them and so we could just join this and get the list that we want so we can just join X here and that will give us the strings that the combinations that we use to help us to generate and so instead of generating it ourselves we could just do this so Q would be equal to so we could just pass or we could actually for our Q here just passed since for a Q if we look at two important collections again so DQ also accept I think it's accepts and iterables is just passed to the Q here now this passed with the iterator combinations right and so here it would be the characters like and then the combination looks like so that this and we don't need to define this function here the only thing we need is because the combinations returns to us a pair here one would pop the first one we need to join them so that we can give what the method expects back right and that's pretty much it and the other solution of course is tonight's now use a queue and then just keep track of the index and increment us yourselves yourself and that's also valid yeah so we just want a fast way really I know of one way to get the next and the has next one that's all that matters really and so let's submit this okay so this also passes yeah so that's the for this problem if you enjoyed this video please like and subscribe thanks for watching and see you next
Iterator for Combination
constrained-subsequence-sum
Design the `CombinationIterator` class: * `CombinationIterator(string characters, int combinationLength)` Initializes the object with a string `characters` of **sorted distinct** lowercase English letters and a number `combinationLength` as arguments. * `next()` Returns the next combination of length `combinationLength` in **lexicographical order**. * `hasNext()` Returns `true` if and only if there exists a next combination. **Example 1:** **Input** \[ "CombinationIterator ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\] \[\[ "abc ", 2\], \[\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, "ab ", true, "ac ", true, "bc ", false\] **Explanation** CombinationIterator itr = new CombinationIterator( "abc ", 2); itr.next(); // return "ab " itr.hasNext(); // return True itr.next(); // return "ac " itr.hasNext(); // return True itr.next(); // return "bc " itr.hasNext(); // return False **Constraints:** * `1 <= combinationLength <= characters.length <= 15` * All the characters of `characters` are **unique**. * At most `104` calls will be made to `next` and `hasNext`. * It is guaranteed that all calls of the function `next` are valid.
Use dynamic programming. Let dp[i] be the solution for the prefix of the array that ends at index i, if the element at index i is in the subsequence. dp[i] = nums[i] + max(0, dp[i-k], dp[i-k+1], ..., dp[i-1]) Use a heap with the sliding window technique to optimize the dp.
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
Hard
null
1,968
hey guys today we're going to talk about question array which item is not equal to average of neighbors so you are given a zero index array numbers of distinct integers you want to rearrange the elements in an array such that every element in the rear range array is not equal to the average of its neighbors okay let's look at what does that mean so basically what i mean is the ranger array should be a property that such that for every i in that range one less than equal to i less than num star length minus one and nums i plus one there were two is not equal to num i so basically right here so for example if i at index one right will be two and is i minus one this position and i plus one is position play add up together divide by two shouldn't be the same as number two that's what it means so let's look at our approach you know so first i basically my mindset is i try to sort it first you know i try to sort the array and i change to list arraylist because it's more easier for me to remove it at the elements if i need to you know i need to swap the position if i need to change the position so i use the i change it change this array to the list first and then i sort it here i run through the you know front of i equal to one to the last element of the list so i check if the you know left if i the current index for example is one is the element at the left an element of the right divided by two that number is equal to number you know number two you know i need to change something and i need to basically re move it move that move the next one move the right one element to the at the end of the array so basically that's what i did here so you know and i check if the right most element is not equal to like that it's not at the end of the last element that i can move it you know because if i if the element is at the right and most i cannot move to anywhere so i check if that condition is true so temporary equal to the element you know i plus one i remove the element first and i add attempt to the end else you know i swap you know the element at the current index i wish the was the first element you know because things we cannot move it because in this case else case indeed the i plus one element is at the end of the list so i cannot move it to end again so i move to the front and then i convert back to the array and then boom i written result yep and for this one the time capacity should be of n because i run to every element in the nums array time and space complexity should be open too because i create another list to help so time is open space is open all right thank you guys have a nice day you
Array With Elements Not Equal to Average of Neighbors
maximum-building-height
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`. Return _**any** rearrangement of_ `nums` _that meets the requirements_. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** \[1,2,4,5,3\] **Explanation:** When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5. When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5. When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5. **Example 2:** **Input:** nums = \[6,2,0,9,7\] **Output:** \[9,7,6,2,0\] **Explanation:** When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5. When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5. When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3. **Constraints:** * `3 <= nums.length <= 105` * `0 <= nums[i] <= 105`
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
Array,Math
Hard
null
1,579
Hello everyone welcome, you are my channel and I always suggest that if you read my graph concept playlist, then graph bill Wickham is very fine, try it once, for that remove the maximum number of cups, graph full travel is fine. The name of the question is this and what is it, after reading it from my playlist of graph concepts, which is a cake walk, it has been explained in such a way and this question will be okay, just apply, nothing else but we will also see why DSE happened to apply. Okay, it is Google, so look at the question, it is given in the question that Alex and Bob, they have an undirected graph in which there are nodes, okay, there are n notes, there are numbering of notes, one is three forages, geography is there, those are three. What will be the first type in which only Alice can move? Second type in which only Alice can move. Third type 3 in which both can move. Okay, so now the input will be given like this. First value type will be U and second will be the value of note. If you say Urb type then it will be type three type tu or type one. What is the maximum edge you can remove? Remove it. Okay and what is the meaning of traveling? Start from any note and go to any note as much as you can remove. Yes, the answer is asking how many can you remove? Okay, so now let's understand from the example. Look here, this is the input. Here N = 4 means Look here, this is the input. Here N = 4 means Look here, this is the input. Here N = 4 means total 4 notes. Okay, so the graph is something like this. 1234 is given, look, pay attention. Here, the types are given here, these are the first types, okay, the first entry and the remaining two are the edges, these notes are clear till now, so here we write separately which is which type, then which will be type three. It will be of blue color in which both people can walk, which will be type one, the red color type, which will be green, that will be type you, what is after that, type one, sorry, let's check, okay, so we have removed both of these, now check. Let's do that if we start from here from the story also but for example, if Luck starts from here then let's see whether Alice can go to every note or not. Okay, so you have to go from one. Science, this is the blue one, so both. Can travel to go tu pe to like here a gaya because this blue is ahead so both people can walk in it ok now can go to four or not they see so the sun is on ca3 now to 3 se back se tu It will go to pay and then from here it will go to 4 because it can go on raid. So here Bob can go from story to story also to note. Okay, so now let's see how we will solve this. So now look, the most important question comes from this. Why will it be solved and how? There is a question of DC in your mind. Okay, so first of all, you will not remove this mother of yours who is the most beautiful, then someone else will remove her. Okay, so that will be a very long and complex method and that is probably the right method too. No, it is okay, what does it mean that BFS and DFS are a mistake, they cannot be made with it, okay, then DSC is a question of how and why, understand that, if you pay attention, then what is the best way to make it, like a mother takes all these notes. I have 1234 notes, how many should I give for the starting major, how many should I give, but I need to know the minimum number of edges, the minimum number of agencies, I will lose my head, okay, so what will I do by making only one catch? I will go and see if all the problems are there or not, then I will make another one ahead, let's see if all the problems are there or not, then I will make another orange one, then I will make another one, I will find out that okay, all the edges are negotiable, okay, this is the journey, all the edges are there, so we have How much further did I have to make, just by making one, two, three, all the graphs became traversable and if the exact change was given, then how many extra inches were given in vain. Okay, so my answer should be given only if it can be seen, but I have noticed one thing here. What did you do in the beginning, kept all the notes empty, alone slowly built it, while checking, what did I teach you that in the beginning, all the people are alone, then slowly say, if you want to join, then they come in a group, then they take the mother, they join. If this is also included in this group, then it is understood that brother, this question will be made from DSC. Okay, now let's see how to apply for DSO and yes, they will solve the bill. So when I was explaining it to you, now at this time You must have understood what we will do, in the beginning all the notes will be different, gradually I will travel through whatever edge I have given and will see that if whatever I have given ahead is connecting, then connect. We will do it, okay, and all the people who are connecting will be connected, that is, we will connect in minimum numbers, and we will know exactly the life we ​​have, and we will know the minimum number of connections, we will know exactly the life we ​​have, and we will know the minimum number of connections, we will know exactly the life we ​​have, and we will know the minimum number of connections, we will know from 10 U, okay and Now one thing is given in the question that brother, the complete tower should be there in the last. Okay, so what is the full meaning of complete that all the components should be in one group in the last. So what does it mean that when in the starting So okay, everyone is different, in the beginning everyone will start joining separately, if they start doing union, then in the end everyone should be in the same group, meaning in the end till now, how many components were there in the beginning, one, two, three, but when If we start doing union, then I need to get only one component which is there, it should be all in this only then the entire graph will be successful. Okay, so let's try it once and see the example given and see if it works with DSO. How it will be solved and it will become clear further. Okay, when we run from the example, see if you understand from this example, then before starting the example, we should know two things. First of all, remember this, sorry, both in the same graph. If the information of is correct, then only which edges will be there in the graph of type one and type one, at this time both can work. Okay, so that is, if we define the robbers, then what will we do, we have to reduce them separately for both, right? If it does n't work separately, then we will create a DSO class and create two objects, one for 41, one for Bob, okay if we do that code then it will be clear, but we just need to know that both of them are separate. It is butter to handle, okay, for our ease, the first point, the second point is very important, understand that but as an example, I have two notes. Okay, now someone comes with a band, he has to say, brother, I have to add type one, so what did I do? If there is no one in front, then why should I put Type 1 in front? He said, I have to put one of Type 1 in front for Bob, so right now I have zero present of Type 1, it can work in it, if Bob can't work, then one for Bob also. Will have to be added further, ok now tell me one thing, now some guy should come with type 3 first, ok, we are removing it now, if some guy comes with type 3, then what did I do, he turned me into type 3, ok, now let's take me to mom later. Someone said, for whom should one of type 2 be fitted in front? For Bob, I would say that it is not necessary to fit because in type 3, both can work. Okay, so I did not fit. Okay, now someone else is saying to fit type 1 gas only. So look, last time we had to make two separate front butts for Else and Bob, now I got reduced to only one yard. You see what this means is what will we do first, okay first then why because type What will be the benefit of 3, because both of them can walk, then in future we will take Type One Type. This is the request that may not happen, we will not have to make them because Type Three will help us, so it is always safe. That we should process the type three first, then it is okay, then observe type three should come first, after that you or one, whoever it is, Arun Care, it is okay but if type three should come first, then what will we do, we will sort it in descending order with respect. If your type is correct then A will go first then 22 then 11 will go. Ok then 33 so now let's start processing it in this order. Okay so look here let's start one by one so remember the LS's in starting. Pass Total Number How many components will there be 4 notes 1234 Bob will also have tax notes One Tu Three Four This was the same in DSP in the beginning all the notes are different so how many components in total do we have Now how many components does Alex have tax and How many components does Bob have? There are different components, then as we do the union, the components will be reduced, so first I will come to this. Okay, it is 3, which means it is for Alice and also for Bob. There is talk of connecting both of them, it is okay for one and you, first let's come to this, it means both of them are from different Jats, then both of them will have to be brought into the group, so what did I do, if both of them are in the group. Merged and made parents one. Okay, so one component is reduced. If we have blocked it, then we keep track of how many draws we have done. A similar science has been added to the group. This was of type three, so if we did it for Alice, then we did it for Bob. We will have to do the same for 'One' and 'Tu' is the for 'One' and 'Tu' is the for 'One' and 'Tu' is the parent of 'One' itself is 'You', both belong to different parent of 'One' itself is 'You', both belong to different parent of 'One' itself is 'You', both belong to different groups, so we will have to merge both of them, so if I do it then the size of the component is reduced by one, total three components will come now. Its end is also made into a forest. Okay, so we have drawn one ahead, we have done this, now there is only one of them, so look here this is a forest, okay now let's come, we will do this with both of them. If both have to be connected, you and three have to be connected then first they ask you who is your parent, one is one, that means both are separated, it is okay, both are from different houses, so bring three here, right. The thing is, look, only two components are visible, both are correct, now here we come to one, that means Alice is being talked about and one and three are being asked to be connected, the crosses of three are also one, so there is no need to connect. So, this time we did not draw this forward, we did not need this thing, okay, similarly here too, one, two, four, one means we are talking about Alice, in this we are being asked to connect you and four, so Your parents are one and four's parents are four themselves, so if they are from different houses, then four will also be unionized, then four came here and the size of the company got reduced and science made us draw it, only then. Ma, whatever is here, we will make plus one that we have drawn one more, it is just okay, now let's come here, we are also talking about one and you, so the payment of one is one, you are one only. Right, both are already connected. There is talk of three and four. Both are from different houses. Here we have done union. The size of the complaint has been reduced to 1. So we will have to add plus one. We are already connected. Six. How many did we give to her? If we just do it, then we can remove two further that brother, the entire graph should be equal, all the notes will be written at one place, all will be connected to each other and look, this is also correct, all the components are inside it. There is only one component, everyone can travel, both of them should be of the same size as the complaint, then what answer will we return, the total is ok, so understand our story point something like this, first of all, what will be the story point, understand the story that 21 will be a bob. It will be okay and after that remember I told you to sort because I want to process type three first. Okay, we will process it. What things will we pay attention to, how far forward we have drawn, we will keep the account Katra and the components of both will keep decreasing. Whenever we have created any further It is clear till now, okay, so here we know that just by doing this, the pudding code made from story point will also be very easy, okay, so look, let us code it, so first of all we have to If I have to write the code of DSC then like every time what I do is that I take a separate code of DSO from here which we have written but what I said that DSO has to be written for two people and not for Bob for 41. So, let's create a separate class for them, let's create a class for DSO only. Okay, remember that. What we did is, we pasted the complete code of our DC here. Okay, components should also be known. Write's complaint. How many starting total number of notes is done, so what did I say that I will make diu for Alice, then there will be n in DSO in which it is ok from node, we have learned this. Okay, after this what did I say that we need to sort. It used to be typed first of all, what do we have to create separately for Alice and Bob, so we have created it, after that we have to do sorting, it is done, okay now let's start our remaining sorry points, let's write the account further. How many age drops have we done till now, it is zero in the beginning, now everyone is doing it, okay, there are three levels in the agency, earlier it used to be that what is the brother's type, is his type okay , so first let's ask in his world, that is, F. We are searching for Alice, she is with her parents, if it is not equal, okay, we will have to do union, we have done urine, okay, and now we go to you, similarly, let's do Bob's thing, Bob will do this thing sometime, who will have to make it, but pay attention to one more thing. When you are doing a union then the component will also have to be reduced. If the component is missing then one less thing is done. Union is included in the code. Here is what the components do - we will have to do this components do - we will have to do this components do - we will have to do this too. So we were saying that the components are being reduced. If we have to do mines, then we should not miss this important thing. Okay, okay, till now everything is clear. If type is three, then union is done with Alice, union is done with Bob and if add is further, then add account. Plus plus done ok, apart from this what can happen that type is equal tu then union will have to be done ok till now it is clear so see the story point is complete first made a graph for both of them after sorting all who has If he is type three then Babar Ali, both have to be done. If you are type one, then you have to do it only for Bob. If you are type one, then first you have to do it for him. Okay, now when everything is over, what did I say in the last that IF N WHAT? The thing was that if we take out Alex's component, write a function here and say, we will return a single component, right and Bob's single comment should be only one, then what will we do total OK, now let's run this example. It used to happen myself, so I have missed this thing, I am fine with you, okay this time
Remove Max Number of Edges to Keep Graph Fully Traversable
active-users
Alice and Bob have an undirected graph of `n` nodes and three types of edges: * Type 1: Can be traversed by Alice only. * Type 2: Can be traversed by Bob only. * Type 3: Can be traversed by both Alice and Bob. Given an array `edges` where `edges[i] = [typei, ui, vi]` represents a bidirectional edge of type `typei` between nodes `ui` and `vi`, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return _the maximum number of edges you can remove, or return_ `-1` _if Alice and Bob cannot fully traverse the graph._ **Example 1:** **Input:** n = 4, edges = \[\[3,1,2\],\[3,2,3\],\[1,1,3\],\[1,2,4\],\[1,1,2\],\[2,3,4\]\] **Output:** 2 **Explanation:** If we remove the 2 edges \[1,1,2\] and \[1,1,3\]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2. **Example 2:** **Input:** n = 4, edges = \[\[3,1,2\],\[3,2,3\],\[1,1,4\],\[2,1,4\]\] **Output:** 0 **Explanation:** Notice that removing any edge will not make the graph fully traversable by Alice and Bob. **Example 3:** **Input:** n = 4, edges = \[\[3,2,3\],\[1,1,2\],\[2,3,4\]\] **Output:** -1 **Explanation:** In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable. **Constraints:** * `1 <= n <= 105` * `1 <= edges.length <= min(105, 3 * n * (n - 1) / 2)` * `edges[i].length == 3` * `1 <= typei <= 3` * `1 <= ui < vi <= n` * All tuples `(typei, ui, vi)` are distinct.
null
Database
Medium
null
412
is another beginner problem called fizzbuzz it's quite popular it's a children's game where you have to keep the sound of your face or it's a buzz giving an integer ends return a string of array answer one index where these are the rules you basically had to uh return fizzbuzz if I the eye position is divisible by three and five or you turn fifths if it's divisible by three or you turn bus if it's divisible by five then you return I if it's not on develop the conditioner true so basically more of like an ordering um so to give an example basically the input is at the end where you just go through each of the height position until the end and the output is the index of the string the constraint is greater than or equal to one and it's less than ten thousand we stand at the raised to the fourth so yeah so for example you're given this input as n their N is a let's say your end is five so you have to go through one two three four five so the output would be uh if it's one then still one then two three is modular by three is so this is face four is neither uh divisible by five or four so this is still four and five is Buzz right this is divisible by five so this Buzz yeah so this will be your output array um the thing to note is you need to be familiar with the operator called modular module is like the remainder of the number and to know if a number is divisible by a certain factories you use the module operator and then check if it's equal to zero so to those of you who are not familiar with modulo you better check it out um it's easily being taught in um in any programming course because it's very it's one of the most important basic operator that you need to know so let's go ahead in the code section so I'll just go with the loop where I starting from one I is less than the length of n basically less than equal so basically going through until the end value so I plus so the thing to note is there are multiple checks that you need to do because I modular 3 is equal to zero or n it's basically n not an order five is equal to zero and you need to have a response which is an array so you could create an array here make the string with a length of uh and you could basically just this start with you can start zero is the starting index so that's how you do this in go language n is the capacity well it's a yeah serious delay length is the number of items in the array so rest is equal to a pen press and then you append phase bus so you want to do this now you want to do this on the next one also just paste face then put Buzz this okay so here is you want to put the eye but you need to put a string because I isn't it right so you need to convert it so the way you convert a string to any interesting is oy oh i2a is your I here it's a function in Gola building function then return press so let's see if this is going to work okay I guess one more plus valid argument type and so no n is already in sorry only the land here okay that's the first someone let's submit it yeah there you go so yeah this is a fizzbuzz problem um so if you like this video please hit like And subscribe and we'll see you again in the next episode of this beginner course of lead coding um and thank you for watching
Fizz Buzz
fizz-buzz
Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_: * `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`. * `answer[i] == "Fizz "` if `i` is divisible by `3`. * `answer[i] == "Buzz "` if `i` is divisible by `5`. * `answer[i] == i` (as a string) if none of the above conditions are true. **Example 1:** **Input:** n = 3 **Output:** \["1","2","Fizz"\] **Example 2:** **Input:** n = 5 **Output:** \["1","2","Fizz","4","Buzz"\] **Example 3:** **Input:** n = 15 **Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\] **Constraints:** * `1 <= n <= 104`
null
Math,String,Simulation
Easy
1316
423
hey everybody this is larry this is day 28 of the march leeco daily challenge uh hit the like button hit the subscribe button hit me on discord let me know what you think about dave's prom yes the questions are back let me know what you think uh and today's problem is we construct original digits from english uh yeah so i usually solve these lives i was a little slow fast forward or watch it on faster speed or something like that uh but okay given out of order english representation of i'll put the digit okay what does that mean five four five but only okay input only contains lowercase english letters and can be transformed okay um hmm i think this problem could be a little bit more specific but i guess it means that like there's an o and a n and a e and a zero some in some uh format two okay and then the question is uh how do you do this right i mean the first thing you can do is just change this to a frequency table and then kind of go through it um one thing to notice that it is always valid um so that means that you know you don't have to worry about uh you don't have to worry about it like you know you don't have to worry about certain scenarios let's kind of play around with it let's have um let's have a mapping so yeah so frequency table we just do collections like count of s and you can think about this as a hash table and just go through that my dog process is just to spell out the words for a second so um and again one thing that i might do is uh just have you know depending on how i like to do it you um maybe i'll have like zero um one two three four five six seven eight nine right okay so what does this mean right um i mean i assume that there's some way of doing it in a greedy way um for example because this is always valid if there's a z in there that means that you use all the z for zeros right um so you greedily do that way and i don't know if there's an easy way to kind of figure out how to uh you know six only has x for example um but then it gets trickier right with like one and two and so forth so hmm and i don't know that there's a easy way because five for example could be anything well okay let's at least you know um let me think about this but yeah let's just have a map you know map string as you go to this and this is a technique that i mentioned from time to time uh i'm more conscious about so that i don't have to do it is that i can actually just pause this right um so we could actually we could split this by comma and then you know we could do for um pair in this and then we return here that split of the space right so then now we can have mappings as you go to this thing and if you want to kind of see what oops what this looks like i'll print it out real quick just to kind of show you uh the one liners do get a little bit messy and i apologize for that bit but uh but it's just about springing out into four loops right so zero to map one to one and so forth um you can probably map the first one to number but i don't think it actually matters um because you return it in a string anyway and you return the string in ascending order right so it doesn't really yeah uh and then the question is okay yeah this is a little bit weird because now i'm like kind of doing it manually and what i'm doing is that okay we know that um you know z for example like we were saying earlier and then there's a u and four x and six and then you know maybe you could eliminate those right um but then after you eliminate those are you still able to do it well maybe so it's a little bit awkward um because basically okay because then now we want to do them in order maybe and in a greedy order and then let's do it one by one so now we can do we say we said um we said six because there's an x so we know that for every x this should be good right um and then after that let's see let's remove this i mean i think we said you so yeah so we could do that as well and maybe we could have an algorithm to do this to be honest but uh i don't know right uh let's see and then after that we can do the five because five have and maybe we could you know do a dependency graph yeah we could have win like a loop or something just to do this uh in a programmatic way but i guess now i'm mostly done so uh maybe not mostly done but well seven in that case is you know after all the fives v is unique again so we can do the seven and then here you know we did 2 for the w let's see 8 for the g uh and then now nine i guess for the nine but it doesn't matter one for the one as well so that means that okay one and then nine and then three right so this is definitely very uh hacky in a way but you can kind of do it um you can think about it as a dependency graph where um oh no you're not even dependency graph you just do a while loop right you do a while loop to see like a if i contain any string over containing character that any other characters don't have you know uh we can use that in the beginning right so you could have write that um i did it manually so i don't know and then now uh we can do it um yeah let's get the answer put it in a way so for x uh for was it digit uh word in mappings um you know uh let's see there's a couple ways to do this is there a set division is there counter division in python that would be pretty cool but uh but yeah so basically we will get a um a frequency of the word so frequency or character words i guess i don't know oops it's equal to collection start calendar of the word and again this just sets up the frequency map is a very easy way to do in python but in any language even in python you can do it with a for loop right and then now we get um we get how many you know how many what is the smallest number um that has overlaps right um because now um yeah for example z is the smallest one um so then we are going to be terminated by the z so i think i worry a little bit about making sure that i am correct oh no because there's always a valid um there's always a valid answer okay so that means that you know i was worried a little bit about with like i mean i know that i already talked about this but i sometimes trick myself like if there's five z's and one year then what do you do right or maybe in a different case there's only two v's and two years but you need two years to contain you for seven well the thing is this is always gonna be valid so you don't have to worry about it as long as you're doing the right order and so as long as we trust that then we go okay um no let's just say min overlap mean count is equal to uh let's just say some infinity number so fault of infinity uh and then now we go for each key and frequency character right for c in frequency character dot keys um min overlap is equal to the min of well itself or the min of frequency character of c or mappings no not mavericks f the other one of c right so basically this just does uh counts the number of possible uh characters there is and then well we um we appen the digit times um times min overlap as the answer but we also want to go for the keys again to um so yeah to kind of subtract that out from the frequency table because that's how many basically now we're consuming that many number of uh characters right so now we overlap and then we just and this should be maybe good uh we should sort it at the end because now we want to sort it by the digit order i mean this is a little bit lazy but that's fine you could do bucket sword or whatever you know there's some linear time algorithms you want to call it that um but yeah and then we just joined it back into a string let's give it a go is this roughly okay uh so that looks good yes i'm gonna give it a submit and hope it's okay a little bit lazy today on this edge cases oh no um why do i get that wrong though that's odd actually i don't expect that cheese so this should be two because i don't convert it to int in any way so that's actually unexpected unless i uh did something silly which is possible i've been very silly lately um seems like this is just returning one oh this is wrong this is i hm uh this is very well i actually was thinking about this oh yeah i miss wrote this one so basically this calculates um i need to write this a different way i think i set this wrong i set this up incorrectly but basically what i want is that okay for example if they're like eight z's we should set this to z or z right um eight of them and not one i don't know why i did it this way now that i think about it um but the idea the algorithm is correct but my implementation is very bad maybe it's just today i feel like i've been okay except for my implementation it's just been all over the place um let's think about how i want to do this right uh i think what i want is actually this um yeah i think i'm just having a i don't know everyone's gonna have one of these days and hopefully that makes sense but yeah i don't know why i did it i think i was thinking of something similar and i kind of skipped over it because i was going too fast i need to slow down that's one of my problems i've been going lately is that i've been having too many problems in my head um and like i just speed two up too fast i go by too fast without really thinking about what i'm doing um but yeah so this looks good now um i should have tested that case i guess but um but yeah but basically that's what i wanted to do min overlap is just account of like the you know like basically if you have the word zero how many times can it show up in the frequency map the most right um and one of those characters is going to be zed so this is why this works i think i could be wrong let's give it a submit before i talk a little bit more okay cool yeah so it's always going to be constrained by the z and because this is always valid we don't have to worry about additional checking or even make decisions because um you know if this fight like i said earlier there's five sets in s then we know there's gonna be five zeros no matter what and we just have to subtract the other ones um and that means that by definition um there will be at least five years at least five r's maybe always unique actually but at least five o's as well um because if they're more o's they just go to other characters so we definitely abuse the fact that this the input is always valid um so yeah so what is the complexity of this is just going to be linear time um because we for each character in the string we put in a frequency map so this takes linear time and then here you can actually pre-cache this of you can actually pre-cache this of you can actually pre-cache this of course the mappings table and the frequency character of the map um and of course these overlaps uh calculation will at most the of alpha where alpha is the number of characters or number of characters in the alphabet which is 26 which is constant time if you want uh or of alpha if you prefer so yeah and this is of course uh this is just a 10 digits so it's gonna be a lot of you know so is it just the number of digits times the number of alphabet um and then plus a linear time for creating this frequency table um in terms of oh and i guess this is like i said i did it the lazy way with sorting but there's only 10 elements so you could say it's you know 10 log 10 or digits times log digit or one depending on how you want to phrase it's all you know as long as you're consistent with your reasoning and logic it's fine in terms of space this is uh o one because this or alpha depending on you know how you wanna call it this is constant this is or all of them with digits if you like i don't know um yeah uh what else what i was going to say yeah and then the answer is just going to be linear in the size of the output which you cannot do better i guess you can do it in price but uh in python that's not really friendly for strings but yeah so roughly speaking this is all linear time uh let me know what you think uh hit the like button hit the subscribe and join me discord let me know what you think and hope you have a good day hope you have a good rest of the weekend and yeah have a you know stay good stay healthy and to go mental health i'll see you the next day bye
Reconstruct Original Digits from English
reconstruct-original-digits-from-english
Given a string `s` containing an out-of-order English representation of digits `0-9`, return _the digits in **ascending** order_. **Example 1:** **Input:** s = "owoztneoer" **Output:** "012" **Example 2:** **Input:** s = "fviefuro" **Output:** "45" **Constraints:** * `1 <= s.length <= 105` * `s[i]` is one of the characters `[ "e ", "g ", "f ", "i ", "h ", "o ", "n ", "s ", "r ", "u ", "t ", "w ", "v ", "x ", "z "]`. * `s` is **guaranteed** to be valid.
null
Hash Table,Math,String
Medium
null
1,351
all right let's talk about the common negative numbers in the sorted matrix so you are given an environmental grid which is stored in non-disk increasing which is stored in non-disk increasing which is stored in non-disk increasing order and you have to return a number of negative numbers in the grid so this is supposed to be super simple name is your char diagram so it's going to be 4 3 2 negative 1 3 2 1 negative 2 negative 3 right so this is supposed to be how many one two three four five six seven eight so um this is supposed to be easy like when you traverse basically you just have to traverse from the top left two bottom right so you're going here after you finish starting another row and then finish so it basically is dilated so what is the efficient way so the negative number is always starting for the last one right so this could be better like if we just make it the other way so it's still going to be the first row and then but we do it reversely right this is going to be super easy so if you check the number is positive you break so you stop at this point so you go on the next row right and this one you stop at this point you just go on this one and you stop at this point and then go on this row and you stop at this point so this is supposed to be easy so let me just uh just start coding so you have very easy result i'm going to return result and i'm going to traverse the entire grid right so it's going to be stopped on video i listen gridlocking and i plus all right so i'm going to start it from the uh starting from the positive number to the negative numbers which is going to be what in i j preview okay lesson with uh real balance and then j plus first this is the um uh this is from positive sonata right so from positive to negative so i have to check if we ai aj is less than zero if this is true then the result plus so let me just go check my solution and this will be right all right so let's talk about the other way so i'm still going to uh i'm just copy and paste all right so let's talk about it so i'm starting from the last one to the beginning to the first one so if there's an uh value less than zero and then i increment else which is the positive number pause the number i just break so you are going to just find out this is more a little bit i'm not guaranteeing i mean it's a little bit uh efficient than uh negan number which is correct right see all right let's talk about timing space so this is going to be space constant and this is going to be time and by m so m represents the length of the grid and then m represent the width of the grid right doesn't matter which one you design like it should be m by n so this is the environment and this is the solution and i will see you next time bye
Count Negative Numbers in a Sorted Matrix
replace-the-substring-for-balanced-string
Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`. **Example 1:** **Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\] **Output:** 8 **Explanation:** There are 8 negatives number in the matrix. **Example 2:** **Input:** grid = \[\[3,2\],\[1,0\]\] **Output:** 0 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `-100 <= grid[i][j] <= 100` **Follow up:** Could you find an `O(n + m)` solution?
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
String,Sliding Window
Medium
null
263
Hello children welcome to our college so today we are going to see the question its name is the next number that first let us understand the problem what is the next number the next numbers which give the number whose if you do prime factorization then you will have ₹ 2 five do prime factorization then you will have ₹ 2 five do prime factorization then you will have ₹ 2 five Prime factors should be known conventions governing loot in next numbers if I talk about first 10 next numbers then we will have 12345 680 if you do pre factorization of these then you will get 235 in prime factors Top question is that you are given a number If you want to print the anniversary number, then how will you do it? So let's see this example, like I told you to print your 15th street number, I told you to print 150, so you printed 153, now what will happen in the report? The next number will be the tourist from The Amazing Two Three Arrested Daabi Into Five Race to the Scene, then you will get the Yagya Number today with all the combinations. You will be able to calculate it and generate Yagya Number till the end. And after that you softened these numbers till distant and then you printed the numbers, I have given the brute force of this in the notes also, you can see it more than 5 times, so now let us see it in DP approach. What did we say in the DP approach that we have kept three points? Suppose you have calculated your destiny number, you have calculated your K plus one. When we look at the approach of username DP, we see that we have kept till this element. Or from this till the teacher, we have selected all the states, before that we have the dates, now from those states we have to find the answer of the next question, so similarly we have the Takhli numbers lying there, we had to do Kepler to find out the number, so what will be in it, then joker. Plus Vanasthali number will be minimum, it will be P1 * * * Vanasthali number will be minimum, it will be P1 * * * Vanasthali number will be minimum, it will be P1 * * * Three or P 3125, P 153, these numbers will be already generated, then the next number that is going to come will be all the stars of these numbers that will arise or the sum of five times. You should understand this because the next number will be 13, which is already a generator number, its price will be three, this will be five times, if this thing was not there, then assume that we have the next number coming out, one is X back to X by. Three or f5 should be there in the already generated numbers. If it is not there then the next number Suppose now we have 10 next numbers, now we have to talk about length number, then what will be the number for 11th, smallest multiple, all already calculated numbers, i.e. next calculated numbers, i.e. next calculated numbers, i.e. next tension logged in numbers will be 1516 or 2015, where did 325 6 come from? If it comes from 100 or 125 then the already written numbers will let us see the small s multiple and in this case the next number will be 15 so right now we were doing 325. Next time if we do into five then the next number will be caffeine so now we Let's see, we will not need to account for pimples multiples every time, we will keep this point first, we will keep increasing our multiples accordingly, we will see you in the court, if you understand it more as a son than a code, if you look at its code, then first the maintenance would take equal to two. If I am there then I will keep the counter here for you for free and made a DPR for five plus one side's DP 2012 A i.e. the first number is there so DPF hi kya tha humare paas jo next number will be two times Of GPF seats or three times a day Pintu will be C3 or five times deep into CO then why will the digital numbers be multiple if to * dec21 If this was our number then we will do it if to * dec21 If this was our number then we will do it if to * dec21 If this was our number then we will do it for if we have the number then we will cut the number similarly five numbers It came and we did it because in August 2002 this next number came out. There is no need to calculate the next number two plus one separately. So we mix one with our senior deputy chief and minus one and then see that once. You, as we just saw, your number is 10:30, the test is well, you number is 10:30, the test is well, you number is 10:30, the test is well, you understand the question, we will meet in this video of ours.
Ugly Number
ugly-number
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`. Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_. **Example 1:** **Input:** n = 6 **Output:** true **Explanation:** 6 = 2 \* 3 **Example 2:** **Input:** n = 1 **Output:** true **Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. **Example 3:** **Input:** n = 14 **Output:** false **Explanation:** 14 is not ugly since it includes the prime factor 7. **Constraints:** * `-231 <= n <= 231 - 1`
null
Math
Easy
202,204,264
1,921
Hello friends, today's problem is element maximum number of monsters. In this problem we are playing a video game. In this we have to defend our city from monsters. We have to know the distance of each monster from our city and at what speed it will come towards our city. It is a given that the distance and speed of each monster can be different. We have a weapon with the help of which we can kill a single monster. We can kill a single monster at a time, after that The weapon takes a minute to charge and after that we can use the weapon again, that means we can kill a monster in a minute. If the monster reaches our city then we lose the game. The game will end there. What we have to tell is that we have to return the maximum number of monsters that we can eliminate before they reach our whistle. Like in this example. We are given three monsters and their speed is given, then in what order should we eliminate the monsters? Obviously, eliminate the monster that reaches our whistle first, then eliminate the one that is reaching after that, then basically. If we shorten the monsters on the basis of time at which they are reaching our city, then what will happen to us? The monster arriving first should be killed first and then the second one. Then thud ko and so on and how can we calculate the time, we have given the distance and given their speed from the whistle, so if we calculate the distance by speed, then our time will be calculated, how much time will that monster take to reach our whistle, then simply We will do distance by speed, in this example, our speed is given same, everyone is one, so whatever distance will be, that much time will be taken, how much time will it take, first one will take one, then second will take three and third will take four, how much time will it take? Already our sorted order. When everyone arrives, what will we do first of all, we will kill this monster who is arriving first, then we will kill this monster on the first time unit, we will kill this monster on the second time unit, we will kill all the monsters. So what will be our output if we take this example and our speed is given i.e. our speed is given i.e. our speed is given i.e. our distance will be the same amount of time it will take for the monster to reach the whistle, how much time will it take, how much tooth will it take and first of all what will we do? We will kill this monster and we will see on time one, if this monster reaches our whistle then it means our game will be over. We could kill only one monster at a time, so we killed the one who was reaching first. After that, it will take one minute for our weapon to charge but in that time this monster will reach our city and our game will be over. In this case, if we are able to kill only one monster, then what do we have to return? Similarly, if we see this example 324 532, the speed of our buses is different, first of all we will have to find out the time of everyone, when will they reach, what will be our time, 3/5 i.e. 0.6, 2/3 i.e. 0.66 and 4/2 3/5 i.e. 0.6, 2/3 i.e. 0.66 and 4/2 3/5 i.e. 0.6, 2/3 i.e. 0.66 and 4/2 i.e. If we see that they are already i.e. If we see that they are already i.e. If we see that they are already in sorted order, if they were not sorted, what would we do? We would shorten the time based on time, then we would kill the first monster at zero second and then see which monster we would kill at the first time. When we go to kill for the first time, before that this monster will reach our whistle, hence our game will be over. In this case, if we are able to kill only one monster, then what do we have to return? One, then simply what will we do? First of all, we will find out the time at which our monsters are reaching the whistle and then we will shorten them. On the basis of time, we will kill the monster coming first and then the one arriving after that and so on like this. The number of monsters we will be able to kill means that after every kill we will increase our time unit by one and if the monster is coming after that then we can do one more kill but if the next monster is coming before that then Our game will be over and all the fighters we have killed till then will be returned, so what will we do, we were given distance and speed vector, first of all we have to calculate the time vector, we will make a complete loop and calculate the distance by speed for tomorrow's time. We will figure out when each monster will reach the seat and then we will shorten them in ascending order so that the monster that is reaching first is killed first and the one that is reaching later is killed later to check that we are We will loop from zero to It is possible but it is also possible that monster reaches our city before we go to kill, in that case our game will be over in the middle, so we will check the time at which we are going to kill. If at that time our monster reaches the whistle, we can kill only one monster in a minute. If the time of our IS monster is less than the time at which he reaches the whistle, that means we will not be able to kill him. And our game will be over, in that case we will return all the monsters we have killed till I. If we are able to kill everyone, then we will return all the monsters we had in the last. What will be our time complexity from here? We will need a loop of this size. From here also, we will need a loop of this size. But for sorting, it will take us n lag off n so much time. So what will be our overall tongue stick? n lag off n will it dominate and what will we get for face complex T? If we take a vector of size n, what will be the space complexity of n? Thank you guys.
Eliminate Maximum Number of Monsters
eliminate-maximum-number-of-monsters
You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city. The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon. Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._ **Example 1:** **Input:** dist = \[1,3,4\], speed = \[1,1,1\] **Output:** 3 **Explanation:** In the beginning, the distances of the monsters are \[1,3,4\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,2,3\]. You eliminate the second monster. After a minute, the distances of the monsters are \[X,X,2\]. You eliminate the thrid monster. All 3 monsters can be eliminated. **Example 2:** **Input:** dist = \[1,1,2,3\], speed = \[1,1,1,1\] **Output:** 1 **Explanation:** In the beginning, the distances of the monsters are \[1,1,2,3\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,0,1,2\], so you lose. You can only eliminate 1 monster. **Example 3:** **Input:** dist = \[3,2,4\], speed = \[5,3,2\] **Output:** 1 **Explanation:** In the beginning, the distances of the monsters are \[3,2,4\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,0,2\], so you lose. You can only eliminate 1 monster. **Constraints:** * `n == dist.length == speed.length` * `1 <= n <= 105` * `1 <= dist[i], speed[i] <= 105`
null
null
Medium
null
399
hey everybody this is Larry this is day 20th of delico day challenge hit the like button to subscribe button drop me a Discord let me know what you think about today's problem um yeah so hope you enjoyed the intro I am still in Georgia I'm right now I'm in uh an area called kaspaki um it's basically a mountain town Mountain area there's a lot of hiking and stuff so that's what you're seeing now um I just saw definitely check out the Instagram if uh if that's you know just in general but uh yeah uh I'm in a mountain Hotel it's kind of um it's actually very nice the internet is actually relatively fast but uh but the lighting is kind of awkward so hopefully you don't miss my face too much if you do follow the Instagram anyway okay so let's look at today's problem 3.99 evaluate division today's problem 3.99 evaluate division today's problem 3.99 evaluate division okay so you're giving it away in a way of wearable pairs equation in a way of real numbers values where equation I is equal to a survive you survive and why is I as you go to hey okay each A or B sub I is a string that represent a single variable you are given some queries where query subj C sub D is and you must find okay so there's no division by zero there's no contradiction by uh oh God so this is kind of um uh what you might call it this is just going to be um shortest pathway I mean or it doesn't even have to be a short path but just like in a way connect account connected conductivity because as long as you're able to come from you know um two variables then you're able to get to it um that's one way to do it as well but uh let me see I think the other way of doing it is just using putting everything in um uh with respect to one number or something or one variable and then just represent everything with respect to that and then that should allow you to do it um yeah I think either one is fine I think I'm gonna do the breakfast search right because I don't know I actually don't remember how I did it last time but I feel like this time you know I'm feeling it uh yeah it's okay let me think about how I want to do this first so uh I mean it doesn't really matter what um basis we use uh meaning we just have to pick a variable and then kind of keep to it um so yeah so basically yeah I mean we'll just take like equations of zero and we'll call it the basis okay and then basically now we try to figure out yeah and then now let's just create the edge list right also this hotel even though it's very nice and very cozy maybe I gotta do it earlier because I think there is a table like outside but it's raining so it's not very helpful but uh but yeah there's no that's why I'm doing it on bed and also in a weird setup but uh but yeah okay so in this case uh we just put an adjacency list you append to see oops we see and the other way around as well maybe I mixed this up but it's fine but um okay so I just I'm adjusting my setup a little bit because it's actually uh not gonna lie very uncomfortable uh because I'm just like doing it in a very awkward place but uh yeah okay yeah and then now um set up the queue we append the basis uh we wanted to say the was it translation maybe or something like this um let's just say let's just call it ratio I don't know if you go to a lookup table thing right man and then of course ratio of basis is equal to one and then probably like the Q is greater than zero current as you go to Q top left and then for v c in decency list of current then what do we want to say um so okay so if we not in ratio that means we haven't done it yet then we have to append um we but we could also set the ratio now which is equal to ratio of current by the time assume or divided by C it should be one or the other um yeah but that's easy to fix I think this is one of those things where if you think through clearly and Define your things clearly you could get it quickly um but I'm Adam redefined it and honestly way tied to that I hiked like 10 miles in the Mounds in snow slash and everything and it was a mess uh and I carried all my camera equipment so it's really expensive uh very tiring very uh exhausting is what I meant to say but yeah for you we encourse um and then now we Translate uh something like ratio of U I don't know it's something like this or some variation of this right um oh yeah I've checked because for some reason uh if you not in Ratio or we issue I forgot about that case um I think what I want to do is actually not this because it's way easier to whatever um what you need to do is at least print out modify each step of the way right almost like uh like almost like testing a component so that we can see um because then now you can you know for example a is one B is 2 C is six that means it's a over C okay so that means that okay that's actually right uh what is this B over a uh um so B o a coming like this then this the most awkward way to write it I think uh oh that messed up why is the what's PC obesity is killing oh damn I'm messed up it's a connected components thing I didn't realize that I thought for some we okay I actually miss read this a little bit um or at least in the sense that um I don't know if I've misread it I mean I did misunderstood it I don't know if I misread it uh in the sense that I thought when it said that all queries will be evaluated I just thought that they're all connected but they're actually not so that's fine I mean it basically now you have to do a connected components thing and then kind of do it that way let me try to think of this um a clean way to do it doing it um yeah I mean I think we can just uh it's not that big of an issue so yeah I mean I think this is fine it's just yeah it's because everything is self-contained so because everything is self-contained so because everything is self-contained so it this is actually um not relating to it so we can do something like okay we just redo this but so then now let's say about this right so now we have for you we in was it equations right uh we can do something like this foreign basis not in ratio then we do this I think that should be good even though it's very confusing maybe let me see if it works first okay so now it works okay let's give a submit oh no I misunderstood it oh I see um because then now I'm doing two things that are not connected um I see I think I misunderstood it again about uh the input being always valid or again I just misread it uh in that single answer cannot be determined part um because then now they're in two different components so you can't do it this way um now I wish I did with connected components again uh of connectivity but actually I mean we can do we're gonna add the same idea for Union fine except for you know uh yeah we could definitely yeah uh do the same idea as Union fine uh of just uh declaring your parents and in this case your group so then now it's not me I really should have uh saved that case but yeah it's I think it's just me trying to be lazy to be honest I think the white boy could have uh to do it to be honest um or not the right way to do it but uh what did I do how do I like put in a sauce uh because the right way to have done it is just to rewrite it but I think I was trying to um do um classic situation of you know like I did 90 of the code I just have to you know make changes so that it works and it's true but then like we just end up forgetting some cases and stuff like that as a result which happened here so yeah um this is gonna be linear time linear space we plus e is the linear part of it um because basically we look at each Edge once and we look at each node once and each and the nodes come from the edges right so um so yeah so this is linear in the size of the input um yeah that's what I have for this one let me know what you think I'm curious what I did last time uh I did Ford War show that's right I was thinking about doing foil washer and I forgot because I was thinking about connectivity um I remember we break these things that n is equal to 20 so there's only at least the most 40 things and even then you know it wouldn't be because then you know it wouldn't take that long but uh but yeah to be honest I just forgot I mean it's probably best or like you know it's fun to try other things so it's fine too so yeah um cool uh that's all I have for this one let me know what you think stay good stay healthy to go mental health I'll see you later take care bye foreign
Evaluate Division
evaluate-division
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable. You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`. Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`. **Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. **Example 1:** **Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\] **Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\] **Explanation:** Given: _a / b = 2.0_, _b / c = 3.0_ queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_ return: \[6.0, 0.5, -1.0, 1.0, -1.0 \] **Example 2:** **Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\] **Output:** \[3.75000,0.40000,5.00000,0.20000\] **Example 3:** **Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\] **Output:** \[0.50000,2.00000,-1.00000,-1.00000\] **Constraints:** * `1 <= equations.length <= 20` * `equations[i].length == 2` * `1 <= Ai.length, Bi.length <= 5` * `values.length == equations.length` * `0.0 < values[i] <= 20.0` * `1 <= queries.length <= 20` * `queries[i].length == 2` * `1 <= Cj.length, Dj.length <= 5` * `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
Do you recognize this as a graph problem?
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
Medium
null
131
hello everyone i hope all of you are having a great time and welcome to day fifth of december echo challenge let's quickly talk about today's question in today's question is palindrome partitioning here we are given an input string s and we need to partition the input string such that the every possible division leads to a palindrome we need to return all the possibilities for palin palindrome partitioning of s and we already know the definition of a palindromic string which is same when i trade it from the backwards direction so let's try and understand it by an example here we are given an input string as aab so we need to split aab in such a manner that all the partitions are palindromic in nature and we need to return all such possibilities so let's walk through the first case we have divided aaa into singular units a and b as you can see these are of one unit length these are palindromic in nature and when you merge these three together in order then you will lead to the input string s a plus b will lead to the input string s similarly let's walk through the second case we have divided the input string at the second index between a and b such that it remains palindromic in nature followed by b so these are the only two possibilities in which the input string can be divided such that all the substrings are palindromic in nature so let's quickly walk through the presentation that i have created for this and let's get started palindrome partitioning lead code 131 it's a medium level question on lead code and i totally feel the same oops it says we have already solved this question and yes we did it in the month of december 2020 it's more than a year back and we use the backtracking approach to actually come up with the algorithm i'm attaching the link of the video and in case we have already solved backtracking one question we have also done backtracking two question i'm also attaching the link to its video and for that we use the dynamic programming approach use today's opportunity to revise both these concepts and if someone is looking for detailed backtracking playlist or dynamic programming playlist i'm attaching those two in the description below as well i hope you enjoy both these solutions if you do 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
Palindrome Partitioning
palindrome-partitioning
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`. **Example 1:** **Input:** s = "aab" **Output:** \[\["a","a","b"\],\["aa","b"\]\] **Example 2:** **Input:** s = "a" **Output:** \[\["a"\]\] **Constraints:** * `1 <= s.length <= 16` * `s` contains only lowercase English letters.
null
String,Dynamic Programming,Backtracking
Medium
132,1871
31
all right so in today's problem we are going to look at the problem next permutation how do we generate the next permutation given a sequence that we already have so if our sequence is 1 2 &amp; 3 the next permutation in that 2 &amp; 3 the next permutation in that 2 &amp; 3 the next permutation in that sequence is going to be 1 3 &amp; 2 if I sequence is going to be 1 3 &amp; 2 if I sequence is going to be 1 3 &amp; 2 if I have 3 2 1 as my permutation that I'm given the next permutation in the sequence is the first permutation because this is the last permutation of the numbers 1 2 &amp; 3 the numbers 1 2 &amp; 3 the numbers 1 2 &amp; 3 this is the last permutation so we just return the empty array there is no next permutation 1 5 &amp; 2 permutation 1 5 &amp; 2 permutation 1 5 &amp; 2 what is being next permutation the next permutation is 2 1 5 when you're looking at these you might not see a pattern and I myself I do not see a pattern but we do not see a pattern until we understand how permutations are built all right so we have two choices to this problem we first we can generate every single permutation until we hit the permutation we are given and then we go one step forward that will give us the next permutation the problem with that approach is we are going to be doing factorial time work and factorial times and whatever work we're doing in our base case or our individual calls but we are going to go through at worst and factorial permutations if we're given the last permutation and this is a very expensive way to go about things the point of this problem is not to have you brute force it like this the point of the problem is to see whether you really know how a permutation is built and whether you can do a in-depth case whether you can do a in-depth case whether you can do a in-depth case analysis if you have not seen my video on building permutations and permuting a string I highly recommend that because that will help you a lot with understanding what goes on here but let's investigate now let's start connecting the dots and see how is a permutation built so if we're given 1 2 &amp; 3 what we need to do is we need 3 &amp; 3 what we need to do is we need 3 &amp; 3 what we need to do is we need 3 slots the point of a permutation is to exhaust the possibilities of placing each one of these letters in a slot and then recursing and then placing the rest of the numbers so here's an example at the first position we have the choice of placing the 1 the 2 or the 3 when we're doing it like this temporal order gets precedence so we're going to place the first item the least item which is 1 so I want you to notice something 1 is not in our possibility space we are at the second slot we only have 2 choices we have 2 slots we have 2 choices and at this second slot we can either put a 2 or 3 notice that so what you see here is we planted a 1 and that's exactly where our permutation stands in its state right now they decided to plant a 1 and notice they decided to plant a 2 so at this position we either could plant the 2 or 3 the decision was made by this person or power to this permutation panned out to place the 2 at this position at this state it holds a state it is currently exploring the number of ways it can place two and then recurse we place the 2 and we explore all possibilities and then after replaced the two our decision space is down to 3 now all we can place here is a 3 let's place the 3 and now we have exhausted our decision space at this slot all we could place is the 3 so now we ask ourselves the question we ask ourselves what is the next permutation to 1 2 3 now do you notice how we understand more about the problem we understand more about these states that the permutation we are sitting in came from where did it derive from what state is this slot in this slot is in this state of exploring the placement of to notice that we have exhausted all the placements all we could place here is 3 we've done 3 so what we need to do to find the next permutation is backtrack 1 ok we back - one and again we're gonna get to the - one and again we're gonna get to the - one and again we're gonna get to the core algorithm but I just need you to understand this walkthrough so we got through the three and now this slot is at the three is back in the decision space and notice we planted on two we explored all of the possibilities that two's placement had to offer which was placing a three-year and now two has placing a three-year and now two has placing a three-year and now two has exhausted itself and the two returns to the decision space so now we can use either two and or three at this position the next thing the two place is going to be a three before it was two did all victim it's exploring this was on its last permutation and now we place the three and now notice three is not in our decision space anymore and now all we can place here is two and so now one three and two so what is the overarching state is we planted a one what else could we have planted here we could have planted two or three so all the while we're doing our exploring over here we are doing it off of the planting one while we're doing our exploring here we're doing it off the planting three while we're exploring here we're doing our planting off of two it is all about planting and exploring possibilities so this is the next permutation so let me ask you what would the permutation after this be so what we notice is that a section that is decreasing has exhausted itself and reached its last placement if we try to find the next permutation what we would do is we would need to see where we need to backtrack so what we do is we notice that two has exhausted all the possibilities so we need to erase two and return it to the pool and notice we have no more things to explore at the second slot we've tried the two we've tried the three so we erase the three and so now we have explored all the possibilities with one rooted in the first slot now what is the next item to get routed to is the next item to get the routing and now our decision space has adjusted itself to gets the planting we're now exploring on - and now we have we're now exploring on - and now we have we're now exploring on - and now we have two choices for the second we can place the one or the three and now we choose precedence on the lesser item so one gets the placement and then all we can put in the last slot is three that's all we have left so this is the next permutation this is the permutation after the permutation we just made so I want you to start noticing a pattern what we're doing is we're looking for a strictly decreasing section because that is the section that has exhausted itself this has exhausted itself so this would get erased so the element before the strictly decreasing section is the element that still has options to explore so now the next option would be to explore the three and then so on so what we notice is the item right before is strictly decreasing section is the item of interest that is what we need to do our modulation on in order to advance us to the next permutation because the strictly decreasing section has exhausted itself the item before that section has items that it can swap between it still has more choices for its slot so let's look at a concrete example to see this pattern so this is a very tricky case analysis problem this is not something where you just instantly know the answer and I need you to make a few intellectual jumps here so that you can really let this sink in so what we just noticed is each of the decisions are plantings so imagine I am given this permutation we'll see why these are important but notice this person said lemme plant six it goes out of our decisions base they said let me plant two it goes out of our decisions base they said let me plant one and then one disappeared from the decision space but notice here this item is before a strictly decreasing section remember we just established a strictly decreasing section is on its last permutation if this section is on its last permutation what do we need to modulate what is right before that strictly decreasing section why so when we are at slot number three we have these choices we already expressed all of zeros decisions if we are on one if we chose one to be placed in the slots we have passed all of zero is behind us that's not going to be on our next permutation planting we need to consider what is the next item that we plant here so these are the items left to us our cut out of our decision space so we have a 1 3 4 and a 5 and notice our 1 is the item that was chosen so the next item to take one's position the position right before the strictly decreasing section the item is the next greatest item to the right of 1 what is the next greatest item is 3 so we look for the item that is the next greatest item in the decreasing section we look for 3 because guess what 3 is next up in line to get the placement at this slot and then 4 will get a placement mmm 5 so what we do is we swap these items we swap the 1 and a 3 so that 3 gets its placement it is next okay so now we've almost completely simulated going to the next permutation we've swapped the next routing before the decreasing section but notice that this is on the last permutation if we were going to plant at 3 so what we need to do is turn this strictly decreasing section into an increasing section so we are on the first permutation of planting at 3 this would be the last permutation of planting at 3 we want to be at the first permutation planting at 3 so we reverse this sub list we don't need to sort it we can just reverse it because it's already in reverse sorted order and so now this is how we find the next permutation notice we've only done linear time operations we're not pulling into factorial timing of Lex T we've been able to use case analysis to stay linear in how we solved the problem so 3 got its next routing and these suffix has been minimized when it is decreasing it as maximized it is on the end of itself but when it is increasing then we have my's this we have minimized the routing and guess what this is the next permutation and that is how you find the next permutation without using factorial time or expending a brute force solution and so now the time and space complexities are very straightforward and is the length of the permutation string we start with so the time complexity is going to be O of n we're going to scale in a linear fashion as our input gets arbitrarily large this is because all we do is linear time passes we're going to do a linear time pass to find the longest decreasing sequence we're going to do a linear time pass to reverse that sequence and we're just going to do a constant time swapping so none of this is going to take us past the linear time for space we're going to stay constant so the reason it's constant is we're just going to be using local variables we're just going to be using pointers we're not going to be using anything that scales our space as the input gets very large so these are the time complexities so if you liked this video hit the like button subscribe to the channel I hope this explanation was as clear as possible this is not one of those questions that scales well to other questions it's really one of those things where it's a raw case analysis and really understanding the backtracking of permutations to be able to analyze a solution like this it's not something that is going to apply for many things so that's all for this one
Next Permutation
next-permutation
A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order. * For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`. The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). * For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`. * Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`. * While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement. Given an array of integers `nums`, _find the next permutation of_ `nums`. The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** nums = \[3,2,1\] **Output:** \[1,2,3\] **Example 3:** **Input:** nums = \[1,1,5\] **Output:** \[1,5,1\] **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 100`
null
Array,Two Pointers
Medium
46,47,60,267,1978
1,913
hello everyone welcome back to another video in this video we are going to solve with Lead Core problem which is named as maximum difference between two pairs so in this question you will be given an input array in which you will be given some numbers and you have to return the maximum output which will be the product of Maximum difference between two pairs but what do you mean by duplex so let's see from our first example let's try to understand and see what should we are approach foreign S40 42 so when we subtract 42 by 8 we get 34 as and answer so this would be the answer for power solution so what we can see from the question is that first of all if we solve the a we will able to find the answer in N log n time complexity that n is the number of terms in your n okay so if we saw this using sort algorithm and Z Plus simply write 2 4 5 6 7 as a solution so let's see the code for the same first of all we are going to sort our array by using sort function and then we are going to find the total length of the vector and then we are going to use written simply return the last indexing so we are going to return the product of the last and last hurricane index abstracted by the first and the second index so now let's run the program and submit it and let's check if a code works or not so as you can see here we have successfully submitted our code and it's working and beats 100 of the
Maximum Product Difference Between Two Pairs
make-the-xor-of-all-segments-equal-to-zero
The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`. * For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`. Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**. Return _the **maximum** such product difference_. **Example 1:** **Input:** nums = \[5,6,2,7,4\] **Output:** 34 **Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). The product difference is (6 \* 7) - (2 \* 4) = 34. **Example 2:** **Input:** nums = \[4,2,5,9,7,4,8\] **Output:** 64 **Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). The product difference is (9 \* 8) - (2 \* 4) = 64. **Constraints:** * `4 <= nums.length <= 104` * `1 <= nums[i] <= 104`
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
Array,Dynamic Programming,Bit Manipulation
Hard
null
382
daily challenge which is 382 English random number so as per this question uh we have given a single linked list written the random nodes value from the linked list each node must have the same probability of being chosen so uh there are two methods we need to implement solution and one is and get random okay so if you're given an English let's suppose one two three and four so at every time get random get code so you need to return any random number from range one to four okay this is the size of the link list and you need to return any node value randomly okay so if you want to go in an easy way easy services simply you will create an arraylist at the starting when solution get cold okay foreign so it is a very easy way to approach this question very easy way that what are my observation like if I try to write my observations what was the observation key solution will give me the link list the whole link list okay and I need to return random number from linked list at the time where get random get code okay so these are the two observations and as I know like if I want to go in a very easy way I will do this I will follow this approach error list mad dot random that's it okay let me uh show you the code of this very easy approach so what I just did I created an arraylist this is a global error list okay range at the time solution get cold I am pushing all my elements into the array uh creating a random number generating a random number using math dot random and within the range dot size okay and simply returning range dot get like array particular element okay in order of one so this function is order of n and this is order of one basically okay so but the space complexity here is order of n due to error list and time complexity is also order often but if you are sitting in an interview right now so you came up with this easy approach now the interviewer is asking for a follow-up question what was the for a follow-up question what was the for a follow-up question what was the follow-up question follow-up question follow-up question if you scroll down in this question there is a follow-up question but if the there is a follow-up question but if the there is a follow-up question but if the link list is extremely large and it is less is unknown to you what is the interviewer is asking yeah foreign you need to imagine there is a link list or there is a stream with unknown size so can we resolve it with uh without using extra space that is a follow-up question from the interviewer follow-up question from the interviewer follow-up question from the interviewer okay so this can be resolved if we broad our mind if you like if you want to stop at the easy solution that is totally up to you but if you want to broaden up your mind so then devil came up within algorithm which is nothing but sorry this is the spelling reservo assembling I will tell you the simple way to understand this algorithm very simple way just keep your focus here just listen it I will use very simple words so the understanding of this algorithm will be very easy what is the simplest way to describe this algorithm is and the reservoir is happening algorithm but this sampling algorithm says like uh I will choose K elements from n numbers n is not defined to me right now okay it can be a stream or something anything choose K element from n numbers what is the main thing in this we need to implement we need to make sure each element which gets selected has should get selected sorry for the bad handwriting should get selected with the same probability keep in mind same probability and numbers message okay keep this definition in your mind so it will be very easy for you to understand okay now what if I selected now why this Reservoir algorithm I am using Okay I will give you one scenario let's suppose you are given a link list one two three you are picking a random number in this range the time you are picking this uh the number from this range I added few numbers from here side and added few numbers for from here side but as per our easy approaches yeah foreign problem generator what he wants to ask keep thinking that way that the size is unknown to me there is a kind of strain is given to you now you need to give me a random number with an equal probability okay so now let me give in a small example let's suppose we have a stream one two three four and we need to pick random three elements from it so we will create a resolver okay as per this algorithm the reserver there is an array named as reserver which will first pick the first three elements now the probability of picking randomly these elements probability I am saying probability will be one by three of picking every element okay because there are in the reservoirs there are three elements and the size is also three okay so the picking every element is one by three but now what if 4 came into the picture so if 4 came into the picture I need to pick now three elements only so one of the element will get replaced if I need to pick 4. if 4 came into a string I need to replace one of the element from this so what will the probability in this case so probability will be nothing so let's suppose like one for one I will see the probability so for one stays with the probability of so what if p o four probability of 4 will not of node go get selected probability of 4 at the time when 4 is not selected because there can be a transform because 4 cannot be selected I need to pick random elements so that will be nothing but one by four because that is the another element came into the stream so which is nothing K plus 1 okay one element came into the stream if two elements came into same so the total size will be K by K plus 2. same will be K plus 3 of 3 elements came now one element came into picture so this will be 1 by K plus 1 this is nothing but K plus 1 okay so the probability of choosing the probability what I am saying po4 is not selected probability of 4 does not get selected is one by four plus what if p what if the fourth element got selected what is the probability of that is nothing but three by four into I need to replace either 2 or either 3. so the probability of that is two by three I can select either 2 or either three and if I see this that will came three by four now for uh selecting four randomly in this the server array the randomly picking element a probability of every element get paid with a probability of three by four as per the definition of the reserver algorithm is saying make sure each element which gets selected should get selected with the same probability now here the probability of each and every element is same which is three by four this is the only thing we need to tackle in this problem this is the only thing we need to tell the interviewer or the program generator yes there is a way if we want to think in that way if there is a strain given to us with the unknown size I can use Reservoir algorithm and in Reservoir algorithm what I will do I will make the probability of selected every element same by using this formula now let me write the formula here as well what we implemented here so what will be the formula came here that is nothing probability of okay what will the uh what will be the formula what we did in the element which we need to select okay so let me uh take that number as x was in the reserver last time multiply probability of x was replaced by K plus I okay so from this formula I came up to this and the probability of each element get picked up is same okay so this is the simplest definition of reservoir algorithm okay let me give you a brief of this uh code of this as well so I created a head okay and I put all the values in my head and this will be order of one operation noun in this case the scope is one the key the size of the reserver is one and here I am selecting uh matte dot random is less than 1.0 here I am doing nothing I am than 1.0 here I am doing nothing I am than 1.0 here I am doing nothing I am calculating the probability nothing else okay and every time while current is not equal to null I am incrementing my scope okay and I am updating my chosen value when the probability is getting satisfied okay and at the end I am returning chosen value okay so this is order of one this whole thing is order of n so the whole time complexity will be order of n the space complexity will be order one okay uh that's it from this current video uh if you like this if this video helped you so like this video And subscribe to this channel thank you very much
Linked List Random Node
linked-list-random-node
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen. Implement the `Solution` class: * `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`. * `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. **Example 1:** **Input** \[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 3, 2, 2, 3\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. **Constraints:** * The number of nodes in the linked list will be in the range `[1, 104]`. * `-104 <= Node.val <= 104` * At most `104` calls will be made to `getRandom`. **Follow up:** * What if the linked list is extremely large and its length is unknown to you? * Could you solve this efficiently without using extra space?
null
Linked List,Math,Reservoir Sampling,Randomized
Medium
398
1,759
hey there welcome to pomodora Jo for Thursday November 9th 2023 today we're looking at lead Cod problem 1759 count number of homogeneous substrings this is a medium problem all right so we're given a string s we need to return the number of homogeneous substrings of s since the answer may be too large return it modulo 10 9th + 7 and then it modulo 10 9th + 7 and then it modulo 10 9th + 7 and then it describes what this homogeneous substring is a string is considered homogeneous if all of the characters in The String are the same so it's just the same character repeated a substring is a contiguous sequence of characters within a string so that means all the characters have to be grouped together they have to be next to each other so let's take a look at this example a BB CC C A all right so each one of these characters can be a substring by itself so that's a b c all the way a so that means we have 1 2 3 4 5 6 7 8 so that's eight substrings that are homogeneous cuz they're just one character and that character is the same as itself so that's eight right there then we have B and B that's another one so that's nine and then we have these two C's the first two C's that makes 10 so the first two C's make 10 the second two make 11 and then all three make 12 and then we can group these two A's together so that gives us 13 so we have 13 total homogeneous substrings all right cool so let's put 25 minutes on the pom over timer and we will get started so for this one we're going to move fast so let's see what we can do here we'll have some result we'll set it equal to zero and at the end we'll return our result all right so for this one we'll start simply we're going to have a start and an end index so we're going to be going through our string one pass the start index will start the current substring the end index will be the index of the end of this current substring and we'll just count how many of these characters are the same so let's do that so we'll have some start set it equal to zero we'll have some end set that equal to zero now we're going through the entire string so while start is less than the length of our string S I think we might be using this more than once so let's get that out here we call it s length or slen so this is just the length of our string all right so now while the start is less than our string length so first let's get our current character so our current character C is just going to be the string at this start index all right now while we still have the same character so while our string at the end index is equal to C and while end index is still in range and end is also less than our s length then we can keep moving our end down further so our result will increase by one because we found one new substring and then our end will increase by one as well we'll go to the next index all right so we're moving our end further down the line as long as this character is the same as our current character now when we break out of that Loop that means we found a new character or we're at the end of our string that means we have some substring window here we have a start index and an end index so let's get the Delta the difference between those two indices all right now this might take a little bit of explaining so see if I can draw a little diagram here so we've just found some start index and end index for a bunch of characters let's just say it's a so a now we have some start index that's going to be here start and some end index that's here okay so let me see if I can explain this so now that we have the start and end index of our range we can see that one unique string would be the entire list of these letters here so that would be 1 2 3 4 5 six so this would be these six A's together would be one unique substring but we also know we could remove one and that's also a unique substring so that's two and then three four five and six so we can get six unique substrings this way so this is a little bit difficult to describe so I'm going to try this with a little diagram here so imagine you have eight A's you found your start you kept going down the line until you found your end you found eight different A's so if you start it at start and go to end those eight A's will give you one unique substring or one homogeneous substring but you can also get one let's see so all eight will give you one but then you can remove one from the start let's say and the remaining seven give you second one and then you can remove another one and the remaining six give you another one so you can keep removing one a for each of these A's until you get down to one a left so you can have 8 7 6 5 4 3 2 and 1 so that gives you eight unique substrings for one a that you remove you get a unique substring so you can remove up to eight A's you get eight unique substrings so imagine you anchor your end point this a becomes your anchor now you can add one a for each one of these additional A's so you start with one a you can add seven more A's so that's going to give you seven homogeneous substrings two A's 3 A's Four A's five up to eight A's that's seven substrings so you start with that seven next you change your Anchor Point you anchor at this a okay so you had seven unique substrings with your previous a now you're going to Anchor with this a how many A's can you add to this a well you can only add six more A's but you can add one at a time so that's 6 5 4 3 2 1 so now you have seven more substrings so what's the total here well for every a you can basically add the number of A's in that step so you can start with eight and then you move down to 7 6 5 4 3 2 1 so you can basically add the sum of all of those individual integers in the range from one to our Delta here all right I'm hoping this makes sense so what we want to do here is we want to increase our result by the sum of the range from one to our Delta so if we apply this to our example of the eight A's this will give us one a and then 2 A's 3 A's 4 A's 5 A's basically this will take us from 1 through 7 Delta is eight but this range is not inclusive so you go from one through seven and you'll sum those so you'll basically get seven to start with and then you'll add six you'll add five and then add four add three add two add one so that's doing the same thing that we were doing with our moving our end points around I'm hoping this makes sense this is really hard to picture and I'm not describing it super well so now we've gone through while our end is still the same character we're going to update our Endo once it's not the same character anymore or we've run out of characters then we find our Delta we can update our result by summing the range of our Delta and then we do need to reset our start we're going to set our start now to our end point and start again so start will equal end and then we restart all right one quick thing before we do this let's swap this around we want to check our bounds before we try to use them so let's do this well the end is less than the length of our string and then we can use it and our end is equal to our string at this index is equal to C all right hopefully this works okay seems to work let's see if we can pass all the tests wrong answer okay let's use this test case now the wrong answer here is not because we calculated wrong look how big this answer is going to be it's because we didn't follow the instructions I need to return this answer modulo 10 the 9th + 7 all right let's do that + 7 all right let's do that + 7 all right let's do that here 10 to the 9th plus 7 okay try this again all right passing that new test case let's see if we can pass all the tests and we pass and let's see we don't do very well we only beat 28% for 29% do very well we only beat 28% for 29% do very well we only beat 28% for 29% for runtime 77% for memory all right for runtime 77% for memory all right for runtime 77% for memory all right let's jump back here really quick because there is something we can do this was more of an example of how you could do this you find the start and end indices and then you calculate these different sort of permutations they not really permutations uh different Windows within our range so this is one way to do it there is another way to do this and should be faster so let's do that here let's see we don't need start but we do need let's see we'll do this all right so for this one we'll need to keep track of our previous character so I still need this starts as none okay now for every character in our string and if this character is equal to the previous character so it's the same character that we just had then we're going to keep track of our character counts so our count here I'll call it current count will increase by one we have one more length of our substring so let's have some current count out here all right now if it's not the same so we have a new start for our substring well in that case we have to reset our current count so our current count gets reset to one we're starting out with a new single lettered substring and then we do have to set our previous character equal to this character now here's the trick at this point we can take our entire current count and we can add it to our result so result plus equals our current count so this is doing basically what we did with our Loops but it's doing it in a much more compact way so in this case we're going to keep track of our current count as we're going so our current count is going to keep growing 1 2 3 4 5 6 7 now in our previous implementation we would calculate that same range and sums by finding our start and end indices and then we would add one 2 3 4 5 6 7 we would sum that range now we're actually keeping track of our range in our current C count we're going to start at one it'll go to 2 3 4 so on and so forth and we'll just be adding that entire I guess current count to our result similar to the way we did it with our range in this case we're just doing it as we go all right let's run this see if this is any faster all right seems to work let's see if it's faster though and it's significantly faster so now we're at an 84% for runtime and a now we're at an 84% for runtime and a now we're at an 84% for runtime and a 30% for memory so it takes a little bit 30% for memory so it takes a little bit 30% for memory so it takes a little bit more memory but it is much faster so this is definitely a better solution all right well we are out of time but I hope you enjoyed this I hope you had fun I hope you learned something I hope you can go out and write better code
Count Number of Homogenous Substrings
find-the-missing-ids
Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`. A string is **homogenous** if all the characters of the string are the same. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "abbcccaa " **Output:** 13 **Explanation:** The homogenous substrings are listed as below: "a " appears 3 times. "aa " appears 1 time. "b " appears 2 times. "bb " appears 1 time. "c " appears 3 times. "cc " appears 2 times. "ccc " appears 1 time. 3 + 1 + 2 + 1 + 3 + 2 + 1 = 13. **Example 2:** **Input:** s = "xy " **Output:** 2 **Explanation:** The homogenous substrings are "x " and "y ". **Example 3:** **Input:** s = "zzzzz " **Output:** 15 **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase letters.
null
Database
Medium
1357,1420,1467